OpenCV Background Subtraction sample code

Dear Peter

Here is your answer.
I hope this posting & source code help to you.
And This page also is good explain to use background subtraction.

This is simple code for example background subtraction.

The input is cam video.
Before get video frame, source code set some options.
MOG2, ROI, and morphology

in while, blur is option for reduce noise,
And morphology is also option.
As your project purpose and camera environment, you add more pre-processing.

But I don't add labeling code, normally do labeling processing after background subtration, because blob selecting(valid size or not), blob counting, interpretation of blob.

More information
Background subtraction code.
Labeling (findContours)http://study.marearts.com/search/label/Blob%20labeling

Thank you.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char)
 VideoCapture cap(0); // open the default camera
 if (!cap.isOpened()) // check if we succeeded
  return -1;

 Ptr< BackgroundSubtractorMOG2 > MOG2 = createBackgroundSubtractorMOG2(3000, 64);
 //MOG2->setDetectShadows(1); //shadow detection on/off
 Mat Mog_Mask;
 Mat Mog_Mask_morpho;

 Rect roi(100, 100, 300, 300);
 namedWindow("Origin", 1);
 namedWindow("ROI", 1);
 Mat frame;
 Mat RoiFrame;
 Mat BackImg;

 int LearningTime=0; //300;

 Mat element;
 element = getStructuringElement(MORPH_RECT, Size(9, 9), Point(4, 4));

 for (;;)
  cap >> frame; // get a new frame from camera
  if (frame.empty())

  blur(frame(roi), RoiFrame, Size(3, 3));
  //RoiFrame = frame(roi);

  //Mog processing
  MOG2->apply(RoiFrame, Mog_Mask);

  if (LearningTime < 300)
   printf("background learning %d \n", LearningTime);
   LearningTime = 301;

  //Background Imge get

  morphologyEx(Mog_Mask, Mog_Mask_morpho, CV_MOP_DILATE, element);
  threshold(Mog_Mask_morpho, Mog_Mask_morpho, 128, 255, CV_THRESH_BINARY);  

  imshow("Origin", frame);
  imshow("ROI", RoiFrame);
  imshow("MogMask", Mog_Mask);
  imshow("BackImg", BackImg);
  imshow("Morpho", Mog_Mask_morpho);

  if (waitKey(30) >= 0)

 return 0;



  1. Hi. how do you measure the size of roi? what software did you used to get the coordinate of roi?

  2. Hi. how do you measure the size of roi? what software did you used to get the coordinate of roi?

  3. Anonymous25/7/16 22:49

    Nice work! This sample code (and links) were quite helpful for helping me understand background subtraction. One question: what is the purpose of the "LearningTime" variable? Why is it capped at 300 / who decided that the limit is 300? What is so significant about the first 300 frames?

  4. Good work. Can you have this code into python language? Can be improuve your code for optimization over sized data and speed?

  5. Anonymous18/9/16 13:58

    good evening sir , I use QtCreator with openCv3.1.0 . when I execute your code it crashes . then I realized that it is the instruction MOG2- > apply ( RoiFrame , Mog_Mask ) ; that crashes the program and when I put this statement in any comment on. Excuse me sir can you give me an idea ??

  6. Anonymous17/3/17 21:47

    wonderful task