Python | Background subtraction using OpenCV



As the name suggests, it can subtract or exclude the background portion of an image. Its output is a binary segmented image that essentially gives information about non-stationary objects in the image. There is a problem with this concept of finding the non-stationary part, since the shadow of a moving object can move and sometimes be classified in the foreground.

Popular background subtraction algorithms:

  • BackgroundSubtractorMOG : This is a Gaussian blend based background segmentation algorithm.
  • BackgroundSubtractorMOG2 : It uses the same concept but the main advantage it provides is stability even when there is a change in brightness and better identification of shadows in frames.
  • Geometric multigrid : a statistical method is used and the pixel bayesin segmentation algorithm.

# Python code for background subtraction using OpenCV

import numpy as np

import cv2

 

cap = cv2.VideoCapture ( `/ home / sourabh / Downloads / people-walking.mp4` )

fgbg = cv2.createBackgroundSubtractorMOG2 ()

 

while ( 1 ):

ret, frame = cap.read ()

 

fgmask = fgbg.   apply (frame)

 

cv2.imshow ( `fgmask` , frame)

cv2.imshow ( `frame` , fgmask)

  

 

k = cv2.waitKey ( 30 ) & amp;  0xff

if k = = 27 :

break

 

 
cap.release ()
cv2.destroyAllWindows ()

Original video frame:

Background of the subtracted video frame:

Thus, we saw the application of a background subtraction algorithm that detects motion, life in video frames.