C++ OpenCV 视频处理
核对 C++ OpenCV 视频处理全流程:VideoCapture 读取与 VideoWriter 编码写出、逐帧灰度/Canny/帧间差分运动检测、摄像头实时流结构,以及 MOG2 背景减除与 Lucas-Kanade/Farneback 光流实测。
学完这一章,你能够
- 核对 C++ OpenCV 视频处理全流程:VideoCapture 读取与 VideoWriter 编码写出、逐帧灰度/Canny/帧间差分运动检测、摄像头实时流结构,以及 MOG2 背景减除与 Lucas-Kanade/Farneback 光流实测。
视频应用场景与 VideoCapture / VideoWriter 读写
视频本质上是按时间顺序排列的连续图像帧序列,OpenCV 围绕逐帧采集、处理与回写支撑三类常见场景:视频监控中利用背景减除提取运动物体并借助光流追踪轨迹;视频分析中提取关键帧并理解对象行为;实时交互场景下则在帧循环中施加边缘检测、模糊滤镜或实时目标检测与跟踪。
C++ 中通过 `cv::VideoCapture cap("example.mp4")` 打开视频文件并用 `cap.isOpened()` 校验状态,随后在 `while` 循环中用 `cap >> frame` 逐帧读取直至 `frame.empty()`,桌面播放时配合 `imshow` 与 `waitKey(30) == 27`(ESC 键)控制节奏并在结束时调用 `cap.release()`。保存处理后的视频则需用 `cap.get(CAP_PROP_FPS)`、`CAP_PROP_FRAME_WIDTH`、`CAP_PROP_FRAME_HEIGHT` 获取参数,传入 `cv::VideoWriter writer("output.avi", VideoWriter::fourcc('M','J','P','G'), fps, frameSize)` 逐帧 `writer.write(frame)`。本站离线合成 20 帧 `160×120` 运动方块视频以 MJPG 编码写盘再读回,实测 `opened_writer=True`、`opened_cap=True`、分辨率 `[160, 120]`、帧率 `20.0` 且完整读回 `20` 帧。
逐帧处理、帧间差分与摄像头实时流
拿到每帧 `cv::Mat` 后即可无缝复用全部图像处理算子:例如逐帧执行 `cvtColor(frame, grayFrame, COLOR_BGR2GRAY)` 转为灰度视频;若要实现轻量级实时运动检测,可缓存上一帧灰度图 `prevFrame`,每来一帧调用 `cv::absdiff(prevFrame, nextFrame, diffFrame)` 计算像素绝对差并更新 `prevFrame = nextFrame.clone()`。本站实测相邻运动帧的 `absdiff` 经阈值化检出超过 `100` 个运动像素,而两幅完全相同的静止帧差分像素精确为 `0`。
切换到摄像头实时流时,只需将 `VideoCapture` 构造参数由文件路径改为设备索引 `0`(`VideoCapture cap(0)`)表示默认摄像头,检查 `cap.isOpened()` 后即可按相同 `while` 循环逐帧应用 `Canny(frame, edges, 100, 200)` 等实时特效,退出后释放句柄并销毁窗口。本站离线对合成帧执行 `Canny(100, 200)` 验证轮廓边缘稳定检出,实际物理摄像头采集需在接入摄像头设备的本机验证。
高级视频技术:MOG2 背景减除与光流估计
相较简单的相邻两帧差分,高斯混合背景减除器 `cv::createBackgroundSubtractorMOG2()` 为每个像素维护自适应背景分布模型,调用 `bgSubtractor->apply(frame, fgMask)` 可稳定剥离缓慢变化背景中的前景目标。本站对静态纹理背景完成 10 帧预热后再让 `28×28` 亮块平滑移动 10 帧实测:最终前景掩码像素数落在 `[600, 1200]` 合理区间,且前景质心与真实目标中心 `(106, 56)` 误差不超过 `4.0` 像素。
光流用于估计相邻两帧间像素或特征点的表观运动矢量。稀疏光流(Lucas-Kanade 金字塔法)先由 `goodFeaturesToTrack` 在首帧选取强角点,再逐帧调用 `cv::calcOpticalFlowPyrLK(oldGray, gray, oldPoints, newPoints, status, err)` 跟踪有效点(`status[i] == 1`)并绘制轨迹;若需全图逐像素位移场,还可结合稠密光流 `calcOpticalFlowFarneback`。本站将棋盘纹理块精确平移 `(+4, +2)` 像素实测:金字塔 LK 稳定跟踪超过 `10` 个角点且中位位移与 `(4.0, 2.0)` 偏差不超过 `0.3` 像素,Farneback 稠密光流在目标区域内同样给出显著正向 `(dx > 2.0, dy > 1.0)` 运动场。
离线实测 MJPG 视频读写往返、灰度/Canny/帧间差分、MOG2 背景减除及 LK/Farneback 光流
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
若 `nextFrame` 的缓冲区在下一轮 `cap >> nextFrame` 或原地处理中被复用改写,浅拷贝会让 `prevFrame` 与 `nextFrame` 指向同一像素内存导致差分为全零;帧间差分对低速目标易出现空洞且只反映边界变化,MOG2 则需要一定背景预热帧并在目标长期静止时会将其逐步吸收为背景。