本文主要内容是一个混合高斯背景建模[1]的OpenCV例子。
想要了解MOG原理可以参考混合高斯背景建模原理及实现
OpenCV的MOG例子代码如下:
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <math.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
bool pause = false;//是否暂停
int frameNum = 0;
int main()
{
uchar key = false;//用来设置暂停
VideoCapture video("test2.avi");
//Mat frame,mask,thresholdImage,output;
Mat frame,mask;
video>>frame;
//bgSubtractor(history,nmixtures,backgroundRatio,noiseSigma)
BackgroundSubtractorMOG bgSubtractor(5,2,0.75,false);
while(true){
video>>frame;
++frameNum;
//bgSubtractor(当前帧,二值图,学习率);
bgSubtractor(frame,mask,0.01);
imshow("frame",frame);
imshow("mask",mask);
waitKey(20);
//按键P切换暂停和播放
key = cvWaitKey(1);
if(key == 'p') pause = true;
while(pause)
if(cvWaitKey(0)=='p')
pause = false;
}
return 0;
}
构造函数可以使用默认构造函数或带形参的构造函数,调用的接口只有重载操作符():
//! the default constructor
CV_WRAP BackgroundSubtractorMOG();
//! the full constructor that takes the length of the history, the number of gaussian mixtures, the background ratio parameter and the noise strength
CV_WRAP BackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma=0);
//! the destructor
virtual ~BackgroundSubtractorMOG();
//! the update operator
virtual void operator()(InputArray image, OutputArray fgmask, double learningRate=0);
函数调用所涉及到的参数得根据实际应用场景进行调整,下面几张图只是简单的前景检测结果:
参考资料:
[1] KaewTraKulPong, Pakorn, and Richard Bowden. “An improved adaptive background mixture model for real-time tracking with shadow detection.” Video-Based Surveillance Systems. Springer US, 2002. 135-144. 引用次数:1228