Implementing background subtraction
Static cameras are used in many applications, such as security and monitoring. We can separate the background and moving objects by applying a process known as background subtraction. It usually returns a binary image with the background (the static part of the scene) in black pixels and the moving (changing or dynamic) parts in white pixels. OpenCV can implement this through two algorithms. The first is createBackgroundSubtractorKNN()
. This creates a K-Nearest Neighbour (KNN) background subtractor object. Then, we can call the apply()
function with the object to obtain the foreground mask. We can directly display the foreground mask in real time.
The following is a demonstration of how to use it:
import cv2 import numpy as np cap = cv2.VideoCapture(0) fgbg = cv2.createBackgroundSubtractorKNN() while(True): ret, frame = cap.read() fgmask = fgbg.apply(frame) cv2.imshow(...