- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
cv::cuda::BackgroundSubtractorMOG 是 OpenCV 的 CUDA 模块中提供的一个类,用于在 GPU 上执行基于高斯混合模型(Mixture of Gaussians, MOG)的背景建模与前景分割算法。它属于 OpenCV 中用于视频分析和计算机视觉任务的一部分,适用于实时视频流中的运动目标检测。
该类实现了基于 高斯混合模型 的背景/前景分割算法,并利用 CUDA 在 GPU 上加速处理过程。它主要用于从视频流中分离出移动的物体(前景),是视频监控、行为识别等应用的基础组件。
构造函数 && 参数
cv::cuda::BackgroundSubtractorMOG::BackgroundSubtractorMOG
(
int history = 200,
int numComponents = 5,
int blockSize = 3,
bool noiseVariance = true
);
参数 | 描述 |
---|---|
history | 历史帧数,用于学习背景模型。越大越稳定但响应慢。默认值:200 |
numComponents | 每个像素点使用的高斯分量数量。通常为 3~5,默认为 5 |
blockSize | 图像块大小(以像素为单位),用于局部背景建模。默认值为 3 |
noiseVariance | 是否使用固定噪声方差进行优化。默认启用 |
主要方法
1. apply函数
对输入图像帧 frame 应用当前背景模型,生成前景掩膜 fgmask。
void apply
(
InputArray frame,
OutputArray fgmask,
double learningRate = -1,
Stream& stream = Stream::Null()
)
- frame: 输入图像(8UC3 彩色图或 8UC1 灰度图)
- fgmask: 输出前景掩膜(CV_8UC1,0 表示背景,255 表示前景)
- learningRate: 学习率(0.0 ~ 1.0)。若为负,则自动根据历史长度计算。
- stream: CUDA 流对象(用于异步操作)
- getBackgroundImage函数
获取当前估计的背景图像。
void getBackgroundImage
(
OutputArray backgroundImage,
Stream& stream = Stream::Null()
) const;
- backgroundImage: 输出背景图像(与输入图像同类型)
代码示例
#include <opencv2/cudabgsegm.hpp>
#include <opencv2/cudaobjdetect.hpp>
#include <opencv2/opencv.hpp>
int main()
{
cv::VideoCapture cap( 0 ); // 打开摄像头
if ( !cap.isOpened() )
return -1;
cv::cuda::GpuMat d_frame, d_fgmask;
cv::Mat frame, fgmask;
// 创建 MOG 背景建模器
cv::Ptr< cv::cuda::BackgroundSubtractorMOG > bgSubtractor = cv::cuda::createBackgroundSubtractorMOG();
while ( true )
{
cap >> frame;
if ( frame.empty() )
break;
cv::cuda::GpuMat d_frame( frame );
// 应用背景建模
bgSubtractor->apply( d_frame, d_fgmask );
d_fgmask.download( fgmask );
// 显示结果
cv::imshow( "Foreground Mask", fgmask );
if ( cv::waitKey( 30 ) == 27 )
break; // ESC 键退出
}
return 0;
}