您的位置:首页 > 其它

前景背景分离方法(二)高斯混合模型法GMM(Gaussian Mixture Model)

2014-10-04 16:19 288 查看
int main()
{
VideoCapture capture("D:/videos/shadow/use3.MPG");
if( !capture.isOpened() )
{
cout<<"读取视频失败"<<endl;
return -1;
}
//获取整个帧数
long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);
cout<<"整个视频共"<<totalFrameNumber<<"帧"<<endl;

//设置开始帧()
long frameToStart = 200;
capture.set( CV_CAP_PROP_POS_FRAMES,frameToStart);
cout<<"从第"<<frameToStart<<"帧开始读"<<endl;

//设置结束帧
int frameToStop = 650;

if(frameToStop < frameToStart)
{
cout<<"结束帧小于开始帧,程序错误,即将退出!"<<endl;
return -1;
}
else
{
cout<<"结束帧为:第"<<frameToStop<<"帧"<<endl;
}

double rate = capture.get(CV_CAP_PROP_FPS);
int delay = 1000/rate;

Mat frame;
//前景图片
Mat foreground;

//使用默认参数调用混合高斯模型
BackgroundSubtractorMOG mog;
bool stop(false);
//currentFrame是在循环体中控制读取到指定的帧后循环结束的变量
long currentFrame = frameToStart;
while( !stop )
{
if( !capture.read(frame) )
{
cout<<"从视频中读取图像失败或者读完整个视频"<<endl;
return -2;
}
cvtColor(frame,frame,CV_RGB2GRAY);
imshow("输入视频",frame);
//参数为:输入图像、输出图像、学习速率
mog(frame,foreground,0.01);

imshow("前景",foreground);

//按ESC键退出,按其他键会停止在当前帧

int c = waitKey(delay);

if ( (char)c == 27 || currentFrame >= frameToStop)
{
stop = true;
}
if ( c >= 0)
{
waitKey(0);
}
currentFrame++;

}

waitKey(0);
}


//  基于混合高斯模型的运动目标检测
//  Author: http://blog.csdn.net/icvpr 
#include <iostream>
#include <string>

#include <opencv2/opencv.hpp>

int main(int argc, char** argv)
{
std::string videoFile = "../test.avi";

cv::VideoCapture capture;
capture.open(videoFile);

if (!capture.isOpened())
{
std::cout<<"read video failure"<<std::endl;
return -1;
}

cv::BackgroundSubtractorMOG2 mog;

cv::Mat foreground;
cv::Mat background;

cv::Mat frame;
long frameNo = 0;
while (capture.read(frame))
{
++frameNo;

std::cout<<frameNo<<std::endl;

// 运动前景检测,并更新背景
mog(frame, foreground, 0.001);

// 腐蚀
cv::erode(foreground, foreground, cv::Mat());

// 膨胀
cv::dilate(foreground, foreground, cv::Mat());

mog.getBackgroundImage(background);   // 返回当前背景图像

cv::imshow("video", foreground);
cv::imshow("background", background);

if (cv::waitKey(25) > 0)
{
break;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: