Opencv C++ Tutorial Background subtractor


My favourite

  • Opencv tutorial people detection
  • Head people cascade download
  • Opencv tutorial optical flow
  • Opencv Video stabilization
  • Opencv car dataset download
  • Opencv tutorial Transparent mask
  • Opencv videowriter
  • Opencv FFMPEG
  • Opencv Canny edge and hough lines
  • Opencv tutorial C++ Background substraction

    Simple Opencv C++ code example how to from video remote the foreground from the background. Code is well described and working under opencv 3 and higher without any problems. I would like to reccomend instalation using the NUGET packages in case of Windows Visual Studio Development. Just visit the example how to install here.

    The technique to remove foreground from the background is basic technique to capture evants in web cameras or track the moving objects. In next blog post, I will show you how to draw bounding rectangle over the moving objects. The third blog in line apply kalman filter to track moving objects. This is not a people detection based technique. In case of  shaking, moving and variable light conditions this technique  doesn’t  work properly. In that case. Use haar cascades of LBP or something much better than background.. Lets visit this topics if you are interested Here

    I hope that the code is clear and well described. You can leave me a comment here.

    Background sustraction C++ video

    Opencv C++ background substrack code

    #include "opencv2/highgui.hpp"
    #include "opencv2/imgproc.hpp"

    #include <vector>
    #include <fstream>
    #include <iostream>
    #include <math.h>
    #include <Windows.h>

    #include "opencv2/video/background_segm.hpp"
    #include "opencv2/highgui.hpp"
    #include "opencv2/imgproc.hpp"

    using namespace cv;
    using namespace std;

    int main(int argc, const char** argv)
    // Init background substractor
    Ptr<BackgroundSubtractor> bg_model = createBackgroundSubtractorMOG2().dynamicCast<BackgroundSubtractor>();

    // Create empy input img, foreground and background image and foreground mask.
    Mat img, foregroundMask, backgroundImage, foregroundImg;

    // capture video from source 0, which is web camera, If you want capture video from file just replace //by  VideoCapture cap("")
    VideoCapture cap(0);

    // main loop to grab sequence of input files

         bool ok = cap.grab();

      if (ok == false){

              std::cout << "Video Capture Fail" << std::endl ; 


                    // obtain input image from source
                   cap.retrieve(img, CV_CAP_OPENNI_BGR_IMAGE);
                   // Just resize input image if you want

                  // create foreground mask of proper size
                  if( foregroundMask.empty() ){
                      foregroundMask.create(img.size(), img.type());
                  // compute foreground mask 8 bit image
                  // -1 is parameter that chose automatically your learning rate
                  bg_model->apply(img, foregroundMask, true ? -1 : 0);
                   // smooth the mask to reduce noise in image
                  GaussianBlur(foregroundMask, foregroundMask, Size(11,11), 3.5,3.5);
                  // threshold mask to saturate at black and white values
                  threshold(foregroundMask, foregroundMask, 10,255,THRESH_BINARY);
    Background Subtractor

                    // create black foreground image
                   foregroundImg = Scalar::all(0);
                   // Copy source image to foreground image only in area with white mask
                   img.copyTo(foregroundImg, foregroundMask);
                   //Get background image

                    // Show the results
                   imshow("foreground mask", foregroundMask);
                  imshow("foreground image", foregroundImg);

                   int key6 = waitKey(40);
                    if(!backgroundImage .empty()){

                  imshow("mean background image", backgroundImage );
                    int key5 = waitKey(40);




        return EXIT_SUCCESS;


    1. This article is very very awesome!!! while I’m reading it, i feel like growing up a bit. thanks to sharing it.

      free crack software

    2. Thank you man!
      I ran your code on OpenCV 3.1 and VS2013 and it was great!
      waiting for your future works

    3. Hallo,
      Many greetings from Italy.
      Congratulations for the job.
      There is a Visual Basic or Python version of your code?

      1. Hi, Sorry, I am using python sometimes, but never with opencv staff.

    4. hallo, I tried using opencv v3.1 and VS2012. the program crashed at line
      bg_model->apply(img, foregroundMask, true ? -1 : 0);

      The error i get is
      Unhandled exception at 0x000007FD9AF23F33 (igdfcl64.dll) in OPEN_CV_TEST.exe: 0xC0000005: Access violation writing location 0x0000000050C08990.

      Any suggestion?

      1. Could you explain on that a bit? Apologies as I am a beginner. I am using the x64 Opencv and visual studio versions but receive the same error. I have tried changing your code for Opencv 2.4 so instead of bg_model->apply(img, foregroundMask, true ? -1 : 0); I use bg_model->operator()(img, foregroundMask, true ? -1 : 0);

    5. i got an error when trying to compile with opencv 2.4.10 and VS 2013 : error: C2228: left of '.dynamicCast' must have class/struct/union

    6. This comment has been removed by a blog administrator.

    7. Hello, Thank you for your Documents.

    8. It's awesome! Thank you so much, bro ( and pro :D). How to reduce bright from object?

    9. This article is awesome here i tried another simple way to do background subtraction



    Follow by Email

    Powered by Blogger.