.. _Background_Subtraction: How to Use Background Subtraction Methods ***************************************** * 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. .. image:: images/Background_Subtraction_Tutorial_Scheme.png :alt: Background Subtraction - General Scheme :align: center * Background modeling consists of two main steps: #. Background Initialization; #. 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. As input, we will use data coming from the publicly available data set `Background Models Challenge (BMC) `_ . Goals ====== In this tutorial you will learn how to: #. Read data from videos by using :video_capture:`VideoCapture <>` or image sequences by using :imread:`imread <>`; #. Create and update the background model by using :background_subtractor:`BackgroundSubtractor <>` class; #. Get and show the foreground mask by using :imshow:`imshow <>`; #. Save the output by using :imwrite:`imwrite <>` to quantitatively evaluate the results. Code ===== In the following you can find the source code. We will let the user chose to process either a video file or a sequence of images. * Two different methods are used to generate two foreground masks: #. MOG #. MOG2 The results as well as the input data are shown on the screen. .. code-block:: cpp //opencv #include #include #include //C #include //C++ #include #include using namespace cv; using namespace std; //global variables Mat frame; //current frame Mat fgMaskMOG; //fg mask generated by MOG method Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method Ptr pMOG; //MOG Background subtractor Ptr pMOG2; //MOG2 Background subtractor int keyboard; //function declarations void help(); void processVideo(char* videoFilename); void processImages(char* firstFrameFilename); void help() { cout << "--------------------------------------------------------------------------" << endl << "This program shows how to use background subtraction methods provided by " << endl << " OpenCV. You can process both videos (-vid) and images (-img)." << endl << endl << "Usage:" << endl << "./bs {-vid