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

Prev Tutorial: High level stitching API (Stitcher class)
Next Tutorial: Meanshift and Camshift

Original author Domenico Daniele Bloisi
Compatibility OpenCV >= 3.0
  • Background subtraction (BS) is a common and widely used technique for generating a foreground mask (namely, a binary image containing the pixels belonging to moving objects in the scene) by using static cameras.
  • As the name suggests, BS calculates the foreground mask performing a subtraction between the current frame and a background model, containing the static part of the scene or, more in general, everything that can be considered as background given the characteristics of the observed scene.
  • Background modeling consists of two main steps:

    1. Background Initialization;
    2. Background Update.

    In the first step, an initial model of the background is computed, while in the second step that model is updated in order to adapt to possible changes in the scene.

  • In this tutorial we will learn how to perform BS by using OpenCV.

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.

  • Downloadable code: Click here
  • Code at glance:
    #include <iostream>
    #include <sstream>
    using namespace cv;
    using namespace std;
    const char* params
    = "{ help h | | Print usage }"
    "{ input | vtest.avi | Path to a video or a sequence of image }"
    "{ algo | MOG2 | Background subtraction method (KNN, MOG2) }";
    int main(int argc, char* argv[])
    {
    CommandLineParser parser(argc, argv, params);
    parser.about( "This program shows how to use background subtraction methods provided by "
    " OpenCV. You can process both videos and images.\n" );
    if (parser.has("help"))
    {
    //print help information
    parser.printMessage();
    }
    //create Background Subtractor objects
    if (parser.get<String>("algo") == "MOG2")
    pBackSub = createBackgroundSubtractorMOG2();
    else
    pBackSub = createBackgroundSubtractorKNN();
    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;
    }
    Mat frame, fgMask;
    while (true) {
    capture >> frame;
    if (frame.empty())
    break;
    //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),
    FONT_HERSHEY_SIMPLEX, 0.5 , cv::Scalar(0,0,0));
    //show the current frame and the fg masks
    imshow("Frame", frame);
    imshow("FG Mask", fgMask);
    //get the input from the keyboard
    int keyboard = waitKey(30);
    if (keyboard == 'q' || keyboard == 27)
    break;
    }
    return 0;
    }
    Designed for command line parsing.
    Definition utility.hpp:890
    n-dimensional dense array class
    Definition mat.hpp:829
    Class for video capturing from video files, image sequences or cameras.
    Definition videoio.hpp:766
    std::string String
    Definition cvstd.hpp:151
    std::shared_ptr< _Tp > Ptr
    Definition cvstd_wrapper.hpp:23
    int main(int argc, char *argv[])
    Definition highgui_qt.cpp:3
    Definition core.hpp:107
    STL namespace.

Explanation

We discuss the main parts of the code above:

  • A cv::BackgroundSubtractor object will be used to generate the foreground mask. In this example, default parameters are used, but it is also possible to declare specific parameters in the create function.
//create Background Subtractor objects
if (parser.get<String>("algo") == "MOG2")
else
  • A cv::VideoCapture object is used to read the input video or input images sequence.
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;
}
  • Every frame is used both for calculating the foreground mask and for updating the background. If you want to change the learning rate used for updating the background model, it is possible to set a specific learning rate by passing a parameter to the apply method.
//update the background model
pBackSub->apply(frame, fgMask);
  • The current frame number can be extracted from the cv::VideoCapture object and stamped in the top left corner of the current frame. A white rectangle is used to highlight the black colored frame number.
//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),
FONT_HERSHEY_SIMPLEX, 0.5 , cv::Scalar(0,0,0));
  • We are ready to show the current input frame and the results.
//show the current frame and the fg masks
imshow("Frame", frame);
imshow("FG Mask", fgMask);

Results

  • With the vtest.avi video, for the following frame:

The output of the program will look as the following for MOG2 method (gray areas are detected shadows):

The output of the program will look as the following for the KNN method (gray areas are detected shadows):

References