Background subtraction
If you have a video of a steady scene with some objects moving around, it's possible to separate a still background from a changing foreground. Here, we will show you how to do it in OpenCV.
Getting ready
Before you proceed with this recipe, you need to install the OpenCV version 3.3 (or greater) Python API package with contrib modules.
How to do it
You need to complete the following steps:
- Import the necessary modules:
import cv2 import numpy as np
- Define a function that opens a video file and applies a few background subtraction algorithms to each frame:
def split_image_fgbg(subtractor, open_sz=(0,0), close_sz=(0,0), show_bg=False, show_shdw=False): kernel_open = kernel_close = None if all(i > 0 for i in open_sz): kernel_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, open_sz) if all(i > 0 for i in close_sz): kernel_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, close_sz) cap = cv2.VideoCapture('../data/traffic.mp4') ...