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 = []
self.video = cv2.VideoCapture(1)
self.video.set(3,320)
self.video.set(4,240)
(grabbed, frame) = self.video.read()
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):
self.video.release()
def get_frame(self):
success, image = self.video.read()
fgmask = self.fgbg.apply(image)
return fgmask
#return jpeg.tobytes()
myCam = VideoCamera()
while(True):
cv2.imshow('frame',myCam.get_frame())
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
#cap.release()
cv2.destroyAllWindows()
Code language: Python (python)