"""Offline verification lab for OpenCV Chapter 30: C++ OpenCV project practice."""
import json
import tempfile
from pathlib import Path
import cv2
import numpy as np
def case_image_filter_suite_and_video_fx():
img = np.full((160, 200, 3), (40, 80, 120), dtype=np.uint8)
cv2.rectangle(img, (30, 30), (170, 130), (220, 180, 60), -1)
cv2.circle(img, (100, 80), 30, (30, 50, 230), -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(img, (15, 15), 0)
edges = cv2.Canny(img, 100, 200)
inverted = cv2.bitwise_not(img)
restored = cv2.bitwise_not(inverted)
with tempfile.TemporaryDirectory() as tmp:
p_gray = Path(tmp) / "gray_output.png"
p_blur = Path(tmp) / "blurred_output.png"
p_edge = Path(tmp) / "edges.png"
saved_all = bool(
cv2.imwrite(str(p_gray), gray)
and cv2.imwrite(str(p_blur), blurred)
and cv2.imwrite(str(p_edge), edges)
)
actual = dict(
gray_shape=list(gray.shape),
blur_reduces_std=bool(float(blurred.std()) < float(img.std())),
edges_detected=bool(int(np.count_nonzero(edges)) > 0),
double_invert_exact=bool(np.array_equal(img, restored)),
saved_all=saved_all,
)
expected = dict(
gray_shape=[160, 200],
blur_reduces_std=True,
edges_detected=True,
double_invert_exact=True,
saved_all=True,
)
return dict(name="image_filter_suite_and_video_fx", passed=actual == expected, expected=expected, actual=actual)
def case_ar_alpha_overlay_and_plate_region():
# AR overlay with BGRA transparency mask
bg = np.full((200, 200, 3), (60, 100, 140), dtype=np.uint8)
overlay_bgra = np.zeros((100, 100, 4), dtype=np.uint8)
cv2.circle(overlay_bgra, (50, 50), 35, (20, 220, 250, 255), -1)
roi = bg[50:150, 50:150]
alpha_mask = overlay_bgra[:, :, 3] > 0
roi[alpha_mask] = overlay_bgra[:, :, :3][alpha_mask]
corner_preserved = bg[52, 52].tolist()
center_overlaid = bg[100, 100].tolist()
# Synthetic plate-like high-contrast rectangle localization (aspect ratio ~3:1)
car = np.full((180, 280, 3), (50, 55, 60), dtype=np.uint8)
cv2.rectangle(car, (90, 100), (195, 135), (240, 240, 240), -1)
for k in range(5):
cv2.rectangle(car, (98 + k * 19, 108), (108 + k * 19, 127), (20, 20, 20), -1)
car_gray = cv2.cvtColor(car, cv2.COLOR_BGR2GRAY)
_, car_bin = cv2.threshold(car_gray, 180, 255, cv2.THRESH_BINARY)
k_close = cv2.getStructuringElement(cv2.MORPH_RECT, (11, 5))
closed = cv2.morphologyEx(car_bin, cv2.MORPH_CLOSE, k_close)
contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
plate_boxes = []
for c in contours:
x, y, w, h = cv2.boundingRect(c)
if 2.0 <= (w / max(h, 1)) <= 4.5 and w >= 60:
plate_boxes.append([x, y, w, h])
actual = dict(
ar_corner_preserved=corner_preserved,
ar_center_overlaid=center_overlaid,
plate_box_count=len(plate_boxes),
plate_bbox=plate_boxes[0] if plate_boxes else [],
)
expected = dict(
ar_corner_preserved=[60, 100, 140],
ar_center_overlaid=[20, 220, 250],
plate_box_count=1,
plate_bbox=[90, 100, 106, 36],
)
return dict(name="ar_alpha_overlay_and_plate_region", passed=actual == expected, expected=expected, actual=actual)
def case_motion_detection_and_multi_tracking():
# Synthesize 8 frames with 2 textured targets moving in opposite directions
rng = np.random.default_rng(99)
bg = rng.integers(30, 60, (160, 220, 3), dtype=np.uint8)
t1 = np.zeros((32, 32, 3), dtype=np.uint8)
for r in range(4):
for c in range(4):
t1[r * 8 : (r + 1) * 8, c * 8 : (c + 1) * 8] = (240, 210, 40) if (r + c) % 2 == 0 else (30, 40, 200)
t2 = np.zeros((32, 32, 3), dtype=np.uint8)
for r in range(4):
for c in range(4):
t2[r * 8 : (r + 1) * 8, c * 8 : (c + 1) * 8] = (60, 240, 90) if (r + c) % 2 == 0 else (180, 40, 180)
frames = []
for i in range(8):
fr = bg.copy()
x1, y1 = 20 + i * 5, 25
x2, y2 = 160 - i * 5, 95
fr[y1 : y1 + 32, x1 : x1 + 32] = t1
fr[y2 : y2 + 32, x2 : x2 + 32] = t2
frames.append(fr)
# Inter-frame motion detection
g0 = cv2.cvtColor(frames[0], cv2.COLOR_BGR2GRAY)
g1 = cv2.cvtColor(frames[1], cv2.COLOR_BGR2GRAY)
_, motion = cv2.threshold(cv2.absdiff(g1, g0), 30, 255, cv2.THRESH_BINARY)
# Multi-object tracking using two native TrackerMIL instances
tr1 = cv2.TrackerMIL_create()
tr2 = cv2.TrackerMIL_create()
tr1.init(frames[0], (20, 25, 32, 32))
tr2.init(frames[0], (160, 95, 32, 32))
ok1_all, ok2_all = True, True
box1, box2 = (20, 25, 32, 32), (160, 95, 32, 32)
for fr in frames[1:]:
ok1, box1 = tr1.update(fr)
ok2, box2 = tr2.update(fr)
ok1_all = ok1_all and bool(ok1)
ok2_all = ok2_all and bool(ok2)
actual = dict(
motion_pixels_gt_200=bool(int(np.count_nonzero(motion)) > 200),
both_trackers_ok=bool(ok1_all and ok2_all),
target1_moved_right=bool(box1[0] > 35),
target2_moved_left=bool(box2[0] < 145),
)
expected = dict(
motion_pixels_gt_200=True,
both_trackers_ok=True,
target1_moved_right=True,
target2_moved_left=True,
)
return dict(name="motion_detection_and_multi_tracking", passed=actual == expected, expected=expected, actual=actual)
def case_yolo_postprocess_and_rendering():
img = np.full((240, 320, 3), (25, 25, 25), dtype=np.uint8)
blob = cv2.dnn.blobFromImage(img, 1.0 / 255.0, (416, 416), (0, 0, 0), swapRB=True, crop=False)
class_names = ["person", "car", "dog"]
# Simulated YOLO output rows: [cx, cy, w, h, obj, cls0, cls1, cls2]
outs = np.array(
[
[0.25, 0.35, 0.22, 0.30, 1.0, 0.94, 0.03, 0.03],
[0.26, 0.36, 0.21, 0.29, 1.0, 0.80, 0.12, 0.08],
[0.72, 0.62, 0.28, 0.24, 1.0, 0.05, 0.91, 0.04],
[0.50, 0.50, 0.15, 0.15, 1.0, 0.30, 0.25, 0.10],
],
dtype=np.float32,
)
h, w = img.shape[:2]
boxes, confs, cids = [], [], []
for row in outs:
scores = row[5:]
_, conf, _, loc = cv2.minMaxLoc(scores.reshape(1, -1))
if conf > 0.5:
cx, cy, bw, bh = int(row[0] * w), int(row[1] * h), int(row[2] * w), int(row[3] * h)
boxes.append([cx - bw // 2, cy - bh // 2, bw, bh])
confs.append(float(conf))
cids.append(int(loc[0]))
indices = cv2.dnn.NMSBoxes(boxes, confs, 0.5, 0.4)
kept = sorted(np.array(indices).reshape(-1).tolist())
canvas = img.copy()
labels = []
for idx in kept:
x, y, bw, bh = boxes[idx]
lbl = f"{class_names[cids[idx]]}: {confs[idx]:.2f}"
labels.append(lbl)
cv2.rectangle(canvas, (x, y), (x + bw, y + bh), (0, 255, 0), 2)
cv2.putText(canvas, lbl, (x, max(12, y - 6)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
actual = dict(
blob_shape=list(blob.shape),
kept_count=len(kept),
labels=labels,
drawn_green_gt_200=bool(int(np.count_nonzero(canvas[:, :, 1] == 255)) > 200),
)
expected = dict(
blob_shape=[1, 3, 416, 416],
kept_count=2,
labels=["person: 0.94", "car: 0.91"],
drawn_green_gt_200=True,
)
return dict(name="yolo_postprocess_and_rendering", passed=actual == expected, expected=expected, actual=actual)
def main():
cases = [
case_image_filter_suite_and_video_fx(),
case_ar_alpha_overlay_and_plate_region(),
case_motion_detection_and_multi_tracking(),
case_yolo_postprocess_and_rendering(),
]
print(json.dumps({"cases": cases, "figures": {}}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。
入口文件:projects/opencv-cpp-opencv-project-practice-lab/explore-cpp-opencv-project-practice.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-cpp-opencv-project-practice.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a575.zip