How to do it

You need to complete the following steps:

  1. Import the necessary modules:
import cv2import numpy as np
  1. 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')    while True:        status_cap, frame = cap.read()        if not status_cap:            break                frame = cv2.resize(frame, None, fx=0.5, fy=0.5)         fgmask = subtractor.apply(frame) ...

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.