Background subtraction - Python OpenCV

Background subtraction - Python OpenCV

Background subtraction is a commonly used technique in computer vision for detecting moving objects in videos, especially in applications like surveillance, traffic monitoring, etc. OpenCV provides several background subtraction algorithms.

Here's a basic overview of using background subtraction with OpenCV:

1. Using cv2.createBackgroundSubtractorMOG2()

This method uses the MOG2 (Gaussian Mixture-based Background/Foreground Segmentation Algorithm). It is one of the most popular techniques:

import cv2 cap = cv2.VideoCapture('video_path.mp4') # Use 0 for webcam feed fgbg = cv2.createBackgroundSubtractorMOG2() while True: ret, frame = cap.read() if not ret: break fgmask = fgbg.apply(frame) cv2.imshow('Original', frame) cv2.imshow('Foreground Mask', fgmask) if cv2.waitKey(30) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() 

2. Using cv2.createBackgroundSubtractorKNN()

This is another popular background subtraction method using the KNN algorithm:

import cv2 cap = cv2.VideoCapture('video_path.mp4') # Use 0 for webcam feed fgbg = cv2.createBackgroundSubtractorKNN() while True: ret, frame = cap.read() if not ret: break fgmask = fgbg.apply(frame) cv2.imshow('Original', frame) cv2.imshow('Foreground Mask', fgmask) if cv2.waitKey(30) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() 

Important Points:

  • You'll notice that there might be some noise in the foreground mask. You can use morphological operations like erosion and dilation to reduce this noise.

  • You might need to adjust the parameters of the background subtractors to get the best results for your specific videos.

  • For more advanced background subtraction or for dynamic backgrounds, consider training custom models or using deep learning-based techniques.

Always ensure that the video or webcam feed is appropriately closed using cap.release() and windows are destroyed using cv2.destroyAllWindows().


More Tags

uicollectionview bitwise-operators roles yticks android-appbarlayout codec triangle-count pkcs#8 nestedscrollview variable-declaration

More Programming Guides

Other Guides

More Programming Examples