Skip to main content

Opencv 4 C++ Tutorial simple Background Subtraction

Opencv tutorial C++ Background substraction

This method is used to learn what belongs to the background of the image and what belongs to the foreground. The static cameras that monitor the area can very easily recognize, what is part of the image that is always here or there is something that is new and moving over the background. 

Background subtraction Visual studio 2019 project setup

If you have Opencv 4+ compiled or installed only steps you need to do is set the include directory with OpenCV header files. Set the Additional library Directories that point to \lib folder. Just note that Visual Studio 2019 should use VC16\lib. Finally, As additional dependencies, specify the libs used to resolve the function implementation in the code. The list for Opencv 420 is here. The different version of opencv is using different numbering for example opencv 440 will use opencv_core440.lib. 
Opencv Additional Include DIrectories
Opencv additional library directories
Additional Dependencies

Background sustraction C++ video

Opencv 4 C++ background substractor full source 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/imgproc.hpp"
using namespace cv;
using namespace std;
int main(int argcconst char** argv)
  // Init background substractor
  Ptr<BackgroundSubtractor> bg_model = createBackgroundSubtractorMOG2(500,16.0,true);
 // 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 
//file just replace //by  VideoCapture cap("")
  VideoCapture cap(0);
  // main loop to grab sequence of input files
  for (;;) {
    bool ok = cap.grab();
    if (ok == false) {
      std::cout << "Video Capture Fail" << std::endl;
    else {
      // obtain input image from source
      cap.retrieve(img, CAP_OPENNI_BGR_IMAGE);
      // Just resize input image if you want
      resize(img, img, Size(640480));
      // 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(1111), 3.53.5);
      // threshold mask to saturate at black and white values
      threshold(foregroundMask, foregroundMask, 10255, THRESH_BINARY);
      // 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);
Background extraction in opencv
      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

  10. I really like you post good blog,Thanks for your sharing.


  11. the blog is good and Interactive it is about CODING Developer it is useful for students and Mulesoft Developers for more updates on Mulesoft mulesoft Online training india

  12. Thank you for sharing beneficial information nice post learn mulesoft online

  13. This comment has been removed by the author.

  14. hello,
    thank you for sharing
    i want to ask, what can be BS is done with image ?? no video
    what can be BS is without looping for update background ?

  15. very useful...code works...thank you

  16. I am so proud of you and your efforts and work make me realize that anything can be
    done with patience and sincerity. Well I am here to say that your work has inspired me without a doubt. Here is i want to share about mulesoft training online with Free Bundle videos .


Post a Comment