Reputation: 580
How do i implement background subtraction(background model obtained by averaging first..say 50 frames..) in opencv I tried looking for some codes but found they were in python..im working in c++(visual studio 2013) A small working code snippet will help..thanks!
Upvotes: 0
Views: 1036
Reputation: 41765
OpenCV provide background subtraction capabilities. See BackgroundSubtractorMOG2, that models the background with a Mixture of Gaussians, and is therefore quite robust to background changes.
The parameters history
is the numbers of frame used to build the background model.
#include <opencv2\opencv.hpp>
using namespace cv;
int main(int argc, char *argv[])
{
int history = 50;
float varThreshold = 16.f; // default value
BackgroundSubtractorMOG2 bg = BackgroundSubtractorMOG2(history, varThreshold);
VideoCapture cap(0);
Mat3b frame;
Mat1b fmask;
for (;;)
{
cap >> frame;
bg(frame, fmask, -1);
imshow("frame", frame);
imshow("mask", fmask);
if (cv::waitKey(30) >= 0) break;
}
return 0;
}
Upvotes: 2