Toady’s tutorial is about MOG Background Subtractor in OpenCV Python. We are going to use the built in MOG2 background subtractor with OpenCV Python. In this code we will create a VideoCamera Class to simplify the process of background subtracted frame capturing.

Here is the output how it gives the binary image as an output

MOG Background Subtractor Python Code

This is the complete code which used to generate the above mentioned output.

import numpy as np
import cv2
import time
import datetime

class VideoCamera(object):
    def __init__(self):
        self.img_array = []
        self.label_array = [] = cv2.VideoCapture(1),320),240)
        (grabbed, frame) =
        fshape = frame.shape
        self.fheight = fshape[0]
        self.fwidth = fshape[1]
        self.backgrnd = None
        self.fgbg = cv2.createBackgroundSubtractorMOG2(history = 40, varThreshold = 100, detectShadows = False)
    def __del__(self):
    def get_frame(self):
        success, image =
        fgmask = self.fgbg.apply(image)
        return fgmask
        #return jpeg.tobytes()
myCam = VideoCamera()


    if cv2.waitKey(1) & 0xFF == ord('q'):

# When everything done, release the capture

Code language: Python (python)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.