基于混合高斯模型,对运动背景下的背景进行建模学习,其中运动物体可以较好的判断
#include <stdio.h>
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <cvaux.h>//必须引此头文件
#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
string videoFile = "test3.avi";
VideoCapture capture;
capture.open(videoFile);
if (!capture.isOpened())
{
cout<<"read video failure"<<endl;
return -1;
}
BackgroundSubtractorMOG2 mog;
Mat foreground;
Mat background;
Mat frame;
long frameNo = 0;
while (capture.read(frame))
{
++frameNo;
cout<<frameNo<<endl;
// 运动前景检测,并更新背景
mog(frame, foreground, 0.001);
// 腐蚀
erode(foreground, foreground, Mat());
// 膨胀
dilate(foreground, foreground, Mat());
mog.getBackgroundImage(background); // 返回当前背景图像
imshow("高斯模型前景", foreground);
imshow("高斯模型背景", background);
//// //当前帧与背景图像差分
//// Mat sub1=frame-background;
//// Mat sub2=background-frame;
//// Mat sub=sub1+sub2;
////
////// Mat sub=(sub3+foreground);
//// IplImage subimage=sub;
//// //cvCvtColor(&subimage,&subimage,CV_BGR2GRAY);
//// //imshow("chafen",sub);
////
//// cvSaveImage("subimage.jpg",&subimage);
//// IplImage* subjpg = cvLoadImage("subimage.jpg");
//// IplImage* psubImg = cvCreateImage(cvSize(subjpg->width, subjpg->height), IPL_DEPTH_8U,1);
//// CvMat* psubMat = cvCreateMat(subjpg->height, subjpg->width, CV_32FC1);
//// cvCvtColor(subjpg,psubImg,CV_BGR2GRAY);
//// cvConvert(psubImg, psubMat);
//// //二值化前景图
//// cvThreshold(psubMat, psubImg, 15, 255.0, CV_THRESH_BINARY);
//// cvErode(psubImg, psubImg, 0, 1);
//// cvDilate(psubImg, psubImg, 0, 1);
//// cvShowImage("背景差分法前景目标",psubImg);
if (waitKey(25) > 0)
{
break;
}
}
return 0;
}