Ask Your Question

Findcontours() no working correctly in background subtraction

asked 2015-07-14 10:12:12 -0500

Katrina_V gravatar image


I am trying to obtain the foreground objects from the background using background subtraction model. There will only be a person walking in foreground whom I have to track and draw a bounding box around him. I have written following code for the same.

The Background subtraction works properly when findcontours() function is not added. However on using the function findcontours() function, the background model obtained does not give proper output. Please help me.

without findcontours()

image description

with findcontours()

image description

#include <opencv2/opencv.hpp>
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <stdio.h>
#include <iostream>
#include <sstream>
using namespace cv;
using namespace std;

RNG rng(12345);

// Global variables
Mat frame; //current frame
Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method
Mat frame_check;
Ptr<BackgroundSubtractor> pMOG2; //MOG2 Background subtractor
int keyboard; //input from keyboard

//void processVideo(char* videoFilename);
void processVideo();
void processImages(char* firstFrameFilename);

int main(int argc, char* argv[])

    //create GUI windows
    namedWindow("FG Mask MOG 2");
    //create Background Subtractor objects
    pMOG2 = createBackgroundSubtractorMOG2();

    VideoCapture capture(0);

    if (!capture.isOpened()){
        //error in opening the video input
        cerr << "Unable to open video file: " << endl;
    //read input data. ESC or 'q' for quitting
    while ((char)keyboard != 'q'){
        //read the current frame
        if (! {
            cerr << "Unable to read next frame." << endl;
            cerr << "Exiting..." << endl;
        //update the background model
        pMOG2->apply(frame, fgMaskMOG2);
        frame_check = fgMaskMOG2.clone();

        //process here

        //morphological opening (remove small objects from the foreground)
        erode(frame_check, frame_check, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
        dilate(frame_check, frame_check, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

        ////morphological closing (fill small holes in the foreground)
        dilate(frame_check, frame_check, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
        erode(frame_check, frame_check, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

        vector<vector<Point> > contours;
        vector<Vec4i> hierarchy;

        /// Detect edges using Threshold
        //threshold(frame_check, frame_check, 100, 255, THRESH_BINARY);
        //find contours
        findContours(frame_check, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

        /// Approximate contours to polygons + get bounding rects and circles
        //vector<vector<Point> > contours_poly(contours.size());
        //vector<Rect> boundRect(contours.size());

        ////approximate contours by rectangles
        //for (int i = 0; i < contours.size(); i++)
        //  approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);
        //  boundRect[i] = boundingRect(Mat(contours_poly[i]));

        ////draw bounded recatangles
        //Mat drawing = Mat::zeros(frame_check.size(), CV_8UC3);
        //Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));

        //for (int i = 0; i< contours.size(); i++)
        //  //drawContours(drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point());
        //  rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0);
        //  //circle(drawing, center[i], (int)radius[i], color, 2, 8, 0);

        imshow("Frame", frame);
        imshow("FG Mask MOG 2", frame_check);
        //get the input from the keyboard
        //keyboard = waitKey(30);
        keyboard = waitKey(1000);
    //delete capture object

    //destroy GUI windows
    return EXIT_SUCCESS;
void processVideo() {

edit retag flag offensive close merge delete



ahh, wait, findContours() "eats up the image" (see the Note there) , if you further need the image, you have to clone() it before.

so - that's unrelated to bgmog

berak gravatar imageberak ( 2015-07-14 10:18:26 -0500 )edit

Thanks for the reply. What do you mean ""eats up the image". There is nothin on the link. Also what should I clone?

Katrina_V gravatar imageKatrina_V ( 2015-07-14 11:13:11 -0500 )edit

findContours(frame_check.clone(), contours, ...);

and the link again:


berak gravatar imageberak ( 2015-07-14 11:16:30 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2015-07-14 12:17:35 -0500

Katrina_V gravatar image

Sorry! are right, I got it . Thank you!!! But I have got another problem... How to bound the object by a rectangle ? I tried capturing all the points but it bounds the whole screen :P!!!

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2015-07-14 10:12:12 -0500

Seen: 2,289 times

Last updated: Jul 14 '15