Background Substraction with MOG2

Background Subtraction/Foreground detection is a very important step in detecting interesting objects in the footage. There are several methods to do this,
1. Absolute Difference Method
2. MOG (Mixture of Gaussian)
3. MOG 2
4. GMG

In this post, I will discuss the MOG technique for the background subtraction.


#include "stdio.h";
#include "iostream.h";

#include "opencv2/opencv.hpp";
#include "opencv2/core/core.hpp";
#include "opencv2/highgui/highgui.hpp";
#include "opencv2/video/background_segm.hpp";

using namespace cv;
using namespace std;

int main()

//global variables
Mat frame; //current frame
Mat resize_blur_Img;
Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method
Mat binaryImg;
//Mat TestImg;
Mat ContourImg; //fg mask fg mask generated by MOG2 method
Ptr< BackgroundSubtractor> pMOG2; //MOG2 Background subtractor

pMOG2 = new BackgroundSubtractorMOG2(300,32,true);//300,0.0);

char fileName[100] = "/Users/niro273/Downloads/cctv_footages/cctv.mp4"; //video\\mm2.avi"; //mm2.avi"; //cctv"; //mm2.avi"; //";//_p1.avi";
VideoCapture stream1(fileName); //0 is the id of video device.0 if you have only one camera

//morphology element
Mat element = getStructuringElement(MORPH_RECT, Size(7, 7), Point(3,3) );

//unconditional loop
while (true) {
Mat cameraFrame;

//get one frame form video

resize_blur_Img = frame;
//cvtColor(resize_blur_Img, resize_blur_Img, CV_BGR2HSV);

//Resize (Uncomment to resize)
//resize(frame, resize_blur_Img, Size(frame.size().width/3, frame.size().height/3) );

blur(resize_blur_Img, resize_blur_Img, Size(4,4) );
//Background subtraction
pMOG2->operator()(resize_blur_Img, fgMaskMOG2, -1);//,-0.5);

// Morphological closing operation
morphologyEx(fgMaskMOG2, binaryImg, CV_MOP_CLOSE, element);

//Shadow delete
threshold(binaryImg, binaryImg, 128, 255, CV_THRESH_BINARY);

//Find contour
ContourImg = binaryImg.clone();
//less blob delete
vector< vector< Point> > contours;
contours, // a vector of contours
CV_RETR_EXTERNAL, // retrieve the external contours
CV_CHAIN_APPROX_NONE); // all pixels of each contours

vector< Rect > output;
vector< vector< Point> >::iterator itc= contours.begin();
while (itc!=contours.end()) {

//Create bounding rect of object
//rect draw on origin image
Rect mr= boundingRect(Mat(*itc));
rectangle(resize_blur_Img, mr, CV_RGB(255,0,0));


imshow("Shadow_Removed", binaryImg);
imshow("Blur_Resize", resize_blur_Img);
imshow("MOG2", fgMaskMOG2);

if (waitKey(5) >= 0)


One thought on “Background Substraction with MOG2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s