Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Background subtraction problem

Hi I am working on a video processing project to detect foreground objects and my code to separate foreground and background is as follows :

#include "opencv2/core/core.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/highgui.h"
#include <stdio.h>
#include <opencv2/imgproc/imgproc.hpp>

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;;

    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(500,10,false);
    Mat img, fgmask, fgimg;

        cap >> img;

        if( img.empty() )

        if( fgimg.empty() )
          fgimg.create(img.size(), img.type());
        cv::Mat framecopy;

        //update the model
        blur(img,framecopy, Size(10,10), Point(-1,-1) );

        bg_model(framecopy, fgmask, update_bg_model ? -1 : 0);

        fgimg = Scalar::all(0);
        img.copyTo(fgimg, fgmask);

        Mat bgimg;

        /*std::vector< std::vector<cv::Point> > contours;
        std::vector<Rect> boundRect( contours.size() );

        for(int i=0;i<contours.size();i++)
            boundRect[i] = boundingRect( Mat(contours[i]) );
            cv::rectangle( img, boundRect[i].tl(), boundRect[i].br(), 255, 2, 8, 0 );


        imshow("image", img);
        imshow("foreground mask", fgmask);
        imshow("foreground image", fgimg);
          imshow("mean background image", bgimg );

        char k = (char)waitKey(30);
        if( k == 27 ) break;
        if( k == ' ' )
            update_bg_model = !update_bg_model;
                printf("Background update is on\n");
                printf("Background update is off\n");

    return 0;

and the resulting foregroundmask I got is : image description

t seems my code doesnt cover the whole object completely. Is there anyway I can improve it??