我正致力于视频处理项目,以检测前景物体。下面是我的代码的一部分,用于分隔前景和背景。
#include "opencv2/core/core.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
using namespace std;
using namespace cv;
//this is a sample for foreground detection functions
int main(int argc, const char** argv)
{
VideoCapture cap;
bool update_bg_model = true;
cap.open(0);
if( !cap.isOpened() )
{
printf("can not open camera or video file\n");
return -1;
}
namedWindow("image", CV_WINDOW_NORMAL);
namedWindow("foreground mask", CV_WINDOW_NORMAL);
namedWindow("foreground image", CV_WINDOW_NORMAL);
namedWindow("mean background image", CV_WINDOW_NORMAL);
BackgroundSubtractorMOG2 bg_model;
Mat img, fgmask, fgimg;
for(;;)
{
cap >> img;
if( img.empty() )
break;
if( fgimg.empty() )
fgimg.create(img.size(), img.type());
//update the model
bg_model(img, fgmask, update_bg_model ? -1 : 0);
fgimg = Scalar::all(0);
img.copyTo(fgimg, fgmask);
Mat bgimg;
bg_model.getBackgroundImage(bgimg);
imshow("image", img);
imshow("foreground mask", fgmask);
imshow("foreground image", fgimg);
if(!bgimg.empty())
imshow("mean background image", bgimg );
char k = (char)waitKey(30);
if( k == 27 ) break;
if( k == ' ' )
{
update_bg_model = !update_bg_model;
if(update_bg_model)
printf("Background update is on\n");
else
printf("Background update is off\n");
}
}
return 0;
}
在前景蒙版窗口中,我会收到很多噪音以及实际的前景物体。此外,fulll对象被注意为前景。我还需要将前景对象与矩形绑定在一起。如果我在前景蒙版中绘制轮廓,Wil BoundRect()会做什么工作?...在查找轮廓(findcontour())和BoundRect函数时,最常推荐的参数是什么...提前感谢< / p>
答案 0 :(得分:2)
回答太迟了,但我希望这有助于其他人。
以像素完美的方式将前景与视频中的背景分开(对背景没有任何约束)是一个非常困难的问题。许多研究工作已经进入这一领域,仍然存在范围。因此,高斯的简单混合(如BackgroundSubtractorMOG2所使用的)可能无法给出非常准确的结果。噪声几乎是不可避免的,因为MOG的决定是基于颜色提示,并且背景中的某些像素可能适合由它制作的高斯模型。
您作为前景获得的这些像素实际上代表了变化。因此,如果您修改背景模型的学习率,您可以密切跟踪正在移动的像素。如果您可以假设您的背景是相当静态的,那么移动像素将代表您的前景,并可以帮助您在一定程度上解决问题。
我还建议在openCV中使用BackgroundSubtractorGMG函数。此函数从前几个(可设置的数字)帧中学习背景模型。如果可能的话,让前几帧不是前景。你可能会取得不错的成绩。