在计算机视觉领域,背景减除(Background Subtraction)是一种常用的技术,用于从视频序列中提取前景对象。
背景减除的核心思想是通过建模背景,然后将当前帧与背景模型进行比较,从而分离出前景对象。
OpenCV 提供了多种背景减除算法(MOG、MOG2、KNN),其中 MOG(Mixture of Gaussians)和 MOG2 是最常用的两种方法。
1、MOG2背景减除法
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
VideoCapture cap("input.mp4");
Ptr<BackgroundSubtractorMOG2> bg_model = createBackgroundSubtractorMOG2(500, 16, true);
Mat frame, fg_mask, background;
while (cap.read(frame)) {
bg_model->apply(frame, fg_mask);
bg_model->getBackgroundImage(background); // 提取背景图像:ml-citation{ref="1,2" data="citationList"}
imshow("Background", background);
if (waitKey(30) == 27) break;
}
cap.release();
return 0;
}
参数说明:
history=500
:模型训练帧数,值越大背景更新越慢varThreshold=16
:像素方差阈值,影响前景检测灵敏度detectShadows=true
:启用阴影检测(阴影显示为灰色)
GPU版MOG2与CPU版接口完全兼容,核心代码如下:
cv::gpu::GpuMat d_frame, d_fgmask;
cv::gpu::MOG2_GPU mog2;
mog2(d_frame, d_fgmask); // GPU加速计算
2、KNN背景减除法
Ptr<BackgroundSubtractorKNN> bg_model = createBackgroundSubtractorKNN(500, 400.0, true);
// 其他代码与MOG2逻辑相同
特点对比:
-
KNN对运动模糊更鲁棒,MOG2更适合快速光照变化
-
两者均需10-20帧初始化才能生成有效背景
常见问题排查:
-
背景残留前景物体
-
增大MOG2的history值(建议>500)
-
降低加权平均法的alpha值(建议<0.02)
-
-
背景更新延迟严重
-
MOG2/KNN:减小history值(最低100)
-
加权平均法:增大alpha至0.05-0.15
-
-
CPU占用过高
-
限制处理分辨率:
resize(frame, frame, Size(640,480))
-
跳帧处理:每2帧处理1帧
-