Opencv 4 C++ Tutorial simple Background Subtraction

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_bgsegm420.lib
opencv_core420.lib
opencv_videoio420.lib
opencv_imgproc420.lib
opencv_highgui420.lib
opencv_video420.lib 
Opencv Additional Include DIrectories
Opencv additional library directories
Additional Dependencies

Background subtraction C++ video

Opencv 4 C++ background subtractor 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("videoFile.mov")
  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
      bg_model->getBackgroundImage(backgroundImage);
      // 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;
}



Next Post Previous Post
22 Comments
  • Unknown
    Unknown January 31, 2016 at 11:10 PM

    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

  • Unknown
    Unknown February 23, 2016 at 4:49 AM

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

  • Pino
    Pino April 13, 2016 at 8:09 AM

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

    • Vl
      Vl September 20, 2016 at 11:36 AM

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

  • MITHUN
    MITHUN April 23, 2016 at 4:05 AM

    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?

    • Unknown
      Unknown December 21, 2016 at 10:33 AM

      Change to x64

    • Unknown
      Unknown March 22, 2017 at 11:06 AM

      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);

  • Unknown
    Unknown August 4, 2016 at 4:22 PM

    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

    • Unknown
      Unknown December 26, 2016 at 12:43 AM

      You must try to compile with opencv 3.x.x

  • YouLoseBellyFat
    YouLoseBellyFat September 20, 2016 at 6:36 AM

    This comment has been removed by a blog administrator.

  • Unknown
    Unknown October 8, 2016 at 5:26 AM

    Hello, Thank you for your Documents.

  • Unknown
    Unknown December 26, 2016 at 12:42 AM

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

  • Blogadmin
    Blogadmin October 15, 2017 at 12:00 AM

    This article is awesome here i tried another simple way to do background subtraction https://opencvcraze.com/background-subtraction-in-opencv-c

  • vaiybora
    vaiybora November 27, 2017 at 7:50 AM

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

    หีฟิต

  • Anonymous
    Anonymous December 1, 2017 at 10:41 PM

    thank for sharing

    หวยออนไลน์
    ทางเข้า sbobet
    ทางเข้า m8bet

  • Unknown
    Unknown March 12, 2018 at 4:38 AM

    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

  • Unknown
    Unknown July 2, 2018 at 10:06 PM

    Thank you for sharing beneficial information nice post learn mulesoft online

  • Unknown
    Unknown November 22, 2018 at 7:24 AM

    This comment has been removed by the author.

  • Unknown
    Unknown November 22, 2018 at 7:25 AM

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

  • Unknown
    Unknown March 5, 2019 at 11:05 AM

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

  • basha
    basha March 23, 2019 at 4:49 AM

    Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion Financials Online Training
    Big Data and Hadoop Training In Hyderabad
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion HCM Classroom Training
    Workday HCM Online Training

  • Jack sparrow
    Jack sparrow November 28, 2019 at 8:18 AM

    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 .


Add Comment
comment url