"""Offline OpenCV lab for Ch16: video I/O, per-frame processing & motion detection."""
import json
import platform
import tempfile
from pathlib import Path
import cv2
import numpy as np
def run_cases():
cases = []
with tempfile.TemporaryDirectory() as tmp:
tmp_dir = Path(tmp)
in_path = str(tmp_dir / "synthetic_input.avi")
out_path = str(tmp_dir / "processed_output.avi")
width, height, fps, n_frames = 160, 120, 15.0, 12
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
writer = cv2.VideoWriter(in_path, fourcc, fps, (width, height))
writer_opened = writer.isOpened()
for idx in range(n_frames):
frame = np.full((height, width, 3), 24, dtype=np.uint8)
x0 = 16 + idx * 9
cv2.rectangle(frame, (x0, 40), (x0 + 28, 76), (40, 210, 240), -1)
writer.write(frame)
writer.release()
# Case 1: VideoWriter + VideoCapture roundtrip & metadata
cap = cv2.VideoCapture(in_path)
cap_opened = cap.isOpened()
got_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
got_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
got_fps = round(float(cap.get(cv2.CAP_PROP_FPS)), 2)
got_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frames = []
while True:
ret, frm = cap.read()
if not ret:
break
frames.append(frm)
cap.release()
c1_ok = (writer_opened and cap_opened and got_w == width and got_h == height
and got_fps == fps and got_count == n_frames and len(frames) == n_frames)
cases.append(dict(
name="video_write_read_metadata",
inputs=dict(fourcc="MJPG", width=width, height=height, fps=fps, frames=n_frames),
prerequisites="临时目录合成 12 帧 160x120 运动方块 AVI 视频",
action="使用 cv2.VideoWriter 写入 MJPG 视频并用 cv2.VideoCapture 逐帧回读,核对宽高、帧率与帧数属性。",
expected=dict(
writer_opened=True,
cap_opened=True,
frame_size=[160, 120],
fps=15.0,
frames_read=12,
),
actual=dict(
writer_opened=writer_opened,
cap_opened=cap_opened,
frame_size=[got_w, got_h],
fps=got_fps,
frames_read=len(frames),
),
measurements=dict(prop_frame_count=got_count, first_frame_shape=list(frames[0].shape)),
passed=c1_ok,
))
# Case 2: Per-frame processing (cvtColor, resize, Canny, findContours, drawContours, putText) & re-encode
out_writer = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
contour_counts = []
edge_counts = []
resized_shape = None
for idx, frm in enumerate(frames):
gray = cv2.cvtColor(frm, cv2.COLOR_BGR2GRAY)
resized = cv2.resize(frm, (80, 60))
if resized_shape is None:
resized_shape = list(resized.shape)
edges = cv2.Canny(gray, 80, 180)
edge_counts.append(int(np.count_nonzero(edges)))
_, bin_mask = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(bin_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contour_counts.append(len(contours))
annotated = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
cv2.drawContours(annotated, contours, -1, (0, 255, 0), 2)
cv2.putText(annotated, f"F{idx:02d}", (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
out_writer.write(annotated)
out_writer.release()
verify_cap = cv2.VideoCapture(out_path)
out_frames = int(verify_cap.get(cv2.CAP_PROP_FRAME_COUNT))
verify_cap.release()
out_size = Path(out_path).stat().st_size
c2_ok = (out_frames == n_frames and out_size > 1000 and resized_shape == [60, 80, 3]
and min(contour_counts) >= 1 and min(edge_counts) > 50)
cases.append(dict(
name="frame_processing_and_reencode",
inputs=dict(resize_dsize=[80, 60], canny_thresholds=[80, 180]),
prerequisites="回读得到的 12 帧 BGR 视频序列",
action="逐帧执行 cvtColor、resize、Canny、findContours、drawContours 与 putText 标注,再重新写入输出 AVI。",
expected=dict(
output_frame_count=12,
resized_shape=[60, 80, 3],
all_frames_have_contours=True,
all_frames_have_edges=True,
),
actual=dict(
output_frame_count=out_frames,
resized_shape=resized_shape,
all_frames_have_contours=min(contour_counts) >= 1,
all_frames_have_edges=min(edge_counts) > 50,
),
measurements=dict(
output_file_bytes=out_size,
mean_edge_pixels=round(float(np.mean(edge_counts)), 1),
min_contours=min(contour_counts),
),
passed=c2_ok,
))
# Case 3: Frame-differencing motion detection & MOG2 / Tracker API check
prev_gray = cv2.cvtColor(frames[0], cv2.COLOR_BGR2GRAY)
diff_pixels = []
for frm in frames[1:]:
curr_gray = cv2.cvtColor(frm, cv2.COLOR_BGR2GRAY)
diff = cv2.absdiff(prev_gray, curr_gray)
_, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)
diff_pixels.append(int(np.count_nonzero(thresh)))
prev_gray = curr_gray
# Compare against static identical frame pair (zero motion)
static_diff = cv2.absdiff(prev_gray, prev_gray)
_, static_thresh = cv2.threshold(static_diff, 30, 255, cv2.THRESH_BINARY)
static_motion = int(np.count_nonzero(static_thresh))
mog2 = cv2.createBackgroundSubtractorMOG2(history=10, varThreshold=16, detectShadows=False)
mog2_last = None
for frm in frames:
mog2_last = mog2.apply(frm)
mog2_fg = int(np.count_nonzero(mog2_last))
has_tracker_kcf = hasattr(cv2, "TrackerKCF_create")
c3_ok = (min(diff_pixels) > 300 and static_motion == 0 and mog2_fg > 300)
cases.append(dict(
name="frame_diff_motion_and_api_probe",
inputs=dict(diff_threshold=30, pairs=len(diff_pixels)),
prerequisites="12 帧运动方块序列与静止帧对照",
action="运行 cv2.absdiff + cv2.threshold 帧差运动检测、MOG2 前景分割,并核查 cv2.TrackerKCF_create 可用性。",
expected=dict(
all_moving_pairs_gt_300=True,
static_pair_motion_zero=True,
mog2_detects_motion=True,
),
actual=dict(
all_moving_pairs_gt_300=min(diff_pixels) > 300,
static_pair_motion_zero=static_motion == 0,
mog2_detects_motion=mog2_fg > 300,
),
measurements=dict(
min_diff_pixels=min(diff_pixels),
max_diff_pixels=max(diff_pixels),
mog2_last_fg_pixels=mog2_fg,
has_tracker_kcf_in_core=has_tracker_kcf,
),
passed=c3_ok,
))
payload = dict(version=platform.python_version(), opencv=cv2.__version__, cases=cases)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 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-video-lab/explore-video.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-video.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a597.zip