Search code examples
c++opencvmotion-detection

Motion detection with OpenCV c++


I'm trying to play with my webcam and OpenCV. I follow this tuto : http://mateuszstankiewicz.eu/?p=189. But the only result I have is one red border and I don't understand why. Could anyone help me to make it right and fix this ?

Here is my code :

#include "mvt_detection.h"


Mvt_detection::Mvt_detection()
{

}

Mvt_detection::~Mvt_detection()
{
}

cv::Mat Mvt_detection::start(cv::Mat frame)
{
    cv::Mat back;
    cv::Mat fore;
    cv::BackgroundSubtractorMOG2 bg(5,3,true) ;
    cv::namedWindow("Background");
    std::vector<std::vector<cv::Point> > contours;

    bg.operator ()(frame,fore);
    bg.getBackgroundImage(back);
    cv::erode(fore,fore,cv::Mat());
    cv::dilate(fore,fore,cv::Mat());
    cv::findContours(fore,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
    cv::drawContours(frame,contours,-1,cv::Scalar(0,0,255),2);
    return frame;
}

Here is a screenshot of what our cam returns : enter image description here

I tried on two other video from there and there and there is the same issue.

Thanks for the help :).


Solution

  • As @Lenjyco said, we fixe the problem.

    @Micka had a good idea :

    Firstly the BackgroundSubtractorMOG2 as to be instancied only ONCE.

    We instantiate it in the constructor and play with the Hystory and Threashold:

    Mvt_detection::Mvt_detection()
    {
        bg = new cv::BackgroundSubtractorMOG2(10, 16, false);
    }
    

    10 : the number of image the backgound look back to compare.

    16 : the threshold level (blur)

    This way, we are now able to detect motion.

    Thank you !