蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线实测 MJPG 视频读写往返、灰度/Canny/帧间差分、MOG2 背景减除及 LK/Farneback 光流

PYTHONWindows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。explore-cpp-opencv-video.py
explore-cpp-opencv-video.py179 行
"""Offline verification lab for OpenCV Chapter 28: C++ OpenCV video processing."""
import json
import tempfile
from pathlib import Path
import cv2
import numpy as np


def _make_synthetic_frames(n_frames=20):
    frames = []
    # Textured static background
    bg = np.full((120, 160, 3), (30, 35, 40), dtype=np.uint8)
    for y in range(0, 120, 20):
        cv2.line(bg, (0, y), (159, y), (50, 55, 60), 1)
    for x in range(0, 160, 20):
        cv2.line(bg, (x, 0), (x, 119), (50, 55, 60), 1)

    for i in range(n_frames):
        fr = bg.copy()
        x0 = 12 + i * 5
        y0 = 42
        cv2.rectangle(fr, (x0, y0), (x0 + 28, y0 + 28), (235, 220, 200), -1)
        cv2.circle(fr, (x0 + 14, y0 + 14), 6, (40, 80, 220), -1)
        frames.append(fr)
    return frames


def case_videowriter_and_videocapture_roundtrip():
    frames = _make_synthetic_frames(20)
    with tempfile.TemporaryDirectory() as tmp:
        avi_path = str(Path(tmp) / "output.avi")
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(avi_path, fourcc, 20.0, (160, 120))
        opened_writer = bool(writer.isOpened())
        for fr in frames:
            writer.write(fr)
        writer.release()

        cap = cv2.VideoCapture(avi_path)
        opened_cap = bool(cap.isOpened())
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = round(float(cap.get(cv2.CAP_PROP_FPS)), 1)
        read_frames = 0
        while True:
            ok, fr = cap.read()
            if not ok or fr is None:
                break
            read_frames += 1
        cap.release()

    actual = dict(
        opened_writer=opened_writer,
        opened_cap=opened_cap,
        size=[width, height],
        fps=fps,
        read_frames=read_frames,
    )
    expected = dict(
        opened_writer=True,
        opened_cap=True,
        size=[160, 120],
        fps=20.0,
        read_frames=20,
    )
    return dict(name="videowriter_and_videocapture_roundtrip", passed=actual == expected, expected=expected, actual=actual)


def case_frame_grayscale_canny_and_absdiff():
    frames = _make_synthetic_frames(6)
    g0 = cv2.cvtColor(frames[0], cv2.COLOR_BGR2GRAY)
    g1 = cv2.cvtColor(frames[1], cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(g0, 100, 200)

    diff_moving = cv2.absdiff(g0, g1)
    _, motion_mask = cv2.threshold(diff_moving, 25, 255, cv2.THRESH_BINARY)
    diff_static = cv2.absdiff(g0, g0.copy())

    actual = dict(
        gray_shape=list(g0.shape),
        canny_edges_gt_0=bool(int(np.count_nonzero(edges)) > 0),
        moving_diff_pixels_gt_100=bool(int(np.count_nonzero(motion_mask)) > 100),
        static_diff_pixels=int(np.count_nonzero(diff_static)),
    )
    expected = dict(
        gray_shape=[120, 160],
        canny_edges_gt_0=True,
        moving_diff_pixels_gt_100=True,
        static_diff_pixels=0,
    )
    return dict(name="frame_grayscale_canny_and_absdiff", passed=actual == expected, expected=expected, actual=actual)


def case_mog2_background_subtraction():
    bg = np.full((120, 160, 3), (30, 35, 40), dtype=np.uint8)
    for y in range(0, 120, 20):
        cv2.line(bg, (0, y), (159, y), (50, 55, 60), 1)
    for x in range(0, 160, 20):
        cv2.line(bg, (x, 0), (x, 119), (50, 55, 60), 1)

    bg_sub = cv2.createBackgroundSubtractorMOG2(history=15, varThreshold=16, detectShadows=False)
    # Warm up background model on 10 static background frames
    for _ in range(10):
        bg_sub.apply(bg)

    # Now move a bright 28x28 square across 10 frames; last frame x0 = 20 + 9*8 = 92 -> center (106, 56)
    fg_mask = None
    for i in range(10):
        fr = bg.copy()
        x0 = 20 + i * 8
        y0 = 42
        cv2.rectangle(fr, (x0, y0), (x0 + 28, y0 + 28), (235, 220, 200), -1)
        fg_mask = bg_sub.apply(fr, learningRate=0.0)

    ys, xs = np.where(fg_mask > 0)
    cx = float(np.mean(xs)) if len(xs) > 0 else -1.0
    cy = float(np.mean(ys)) if len(ys) > 0 else -1.0
    actual = dict(
        fg_pixels_in_range=bool(600 <= int(len(xs)) <= 1200),
        centroid_near_target=bool(abs(cx - 106.0) <= 4.0 and abs(cy - 56.0) <= 4.0),
    )
    expected = dict(
        fg_pixels_in_range=True,
        centroid_near_target=True,
    )
    return dict(name="mog2_background_subtraction", passed=actual == expected, expected=expected, actual=actual)


def case_sparse_lk_and_dense_farneback_optical_flow():
    # Textured 160x160 frame with a sharp checkerboard patch shifted by (+4, +2)
    f0 = np.full((160, 160), 30, dtype=np.uint8)
    patch = np.zeros((48, 48), dtype=np.uint8)
    for r in range(6):
        for c in range(6):
            patch[r * 8 : (r + 1) * 8, c * 8 : (c + 1) * 8] = 230 if (r + c) % 2 == 0 else 50
    f0[50:98, 50:98] = patch

    f1 = np.full((160, 160), 30, dtype=np.uint8)
    f1[52:100, 54:102] = patch

    p0 = cv2.goodFeaturesToTrack(f0, maxCorners=100, qualityLevel=0.2, minDistance=6)
    p1, status, _ = cv2.calcOpticalFlowPyrLK(f0, f1, p0, None)
    good_old = p0[status.ravel() == 1].reshape(-1, 2)
    good_new = p1[status.ravel() == 1].reshape(-1, 2)
    delta = good_new - good_old
    lk_dx = round(float(np.median(delta[:, 0])), 2)
    lk_dy = round(float(np.median(delta[:, 1])), 2)

    flow = cv2.calcOpticalFlowFarneback(f0, f1, None, 0.5, 3, 15, 3, 5, 1.2, 0)
    roi_flow = flow[56:92, 56:92]
    dense_dx = float(np.mean(roi_flow[:, :, 0]))
    dense_dy = float(np.mean(roi_flow[:, :, 1]))

    actual = dict(
        tracked_points_gt_10=bool(len(good_old) > 10),
        lk_shift_accurate=bool(abs(lk_dx - 4.0) <= 0.3 and abs(lk_dy - 2.0) <= 0.3),
        farneback_direction_positive=bool(dense_dx > 2.0 and dense_dy > 1.0),
    )
    expected = dict(
        tracked_points_gt_10=True,
        lk_shift_accurate=True,
        farneback_direction_positive=True,
    )
    return dict(name="sparse_lk_and_dense_farneback_optical_flow", passed=actual == expected, expected=expected, actual=actual)


def main():
    cases = [
        case_videowriter_and_videocapture_roundtrip(),
        case_frame_grayscale_canny_and_absdiff(),
        case_mog2_background_subtraction(),
        case_sparse_lk_and_dense_farneback_optical_flow(),
    ]
    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-video-lab/explore-cpp-opencv-video.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-opencv-video.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCV

课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip

下载课程关联工程包:OpenCV

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a576.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习