Loading [MathJax]/extensions/TeX/AMSsymbols.js
OpenCV  
Open Source Computer Vision
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
How to Use Background Subtraction Methods

Next Tutorial: Meanshift and Camshift

Goals

In this tutorial you will learn how to:

  1. Read data from videos or image sequences by using cv::VideoCapture ;
  2. Create and update the background model by using cv::BackgroundSubtractor class;
  3. Get and show the foreground mask by using cv::imshow ;

Code

In the following you can find the source code. We will let the user choose to process either a video file or a sequence of images.

We will use cv::BackgroundSubtractorMOG2 in this sample, to generate the foreground mask.

The results as well as the input data are shown on the screen.

Explanation

We discuss the main parts of the code above:

//create Background Subtractor objects
Ptr<BackgroundSubtractor> pBackSub;
if (parser.get<String>("algo") == "MOG2")
else
VideoCapture capture( samples::findFile( parser.get<String>("input") ) );
if (!capture.isOpened()){
//error in opening the video input
cerr << "Unable to open: " << parser.get<String>("input") << endl;
return 0;
}
//update the background model
pBackSub->apply(frame, fgMask);
//get the frame number and write it on the current frame
rectangle(frame, cv::Point(10, 2), cv::Point(100,20),
cv::Scalar(255,255,255), -1);
stringstream ss;
ss << capture.get(CAP_PROP_POS_FRAMES);
string frameNumberString = ss.str();
putText(frame, frameNumberString.c_str(), cv::Point(15, 15),
//show the current frame and the fg masks
imshow("Frame", frame);
imshow("FG Mask", fgMask);

Results

References