理论

实现

让用户选择处理视频文件或图像序列。在此示例中,将使用cv2.BackgroundSubtractorMOG2 生成前景掩码。

from __future__ import print_function
import cv2
import argparse
parser = argparse.ArgumentParser(
            description='This program shows how to use background subtraction methods provided by OpenCV. You can process both videos and images.')
parser.add_argument('--input', type=str, help='Path to a video or a sequence of image.', default='vtest.avi')
parser.add_argument('--algo', type=str, help='Background subtraction method (KNN, MOG2).', default='MOG2')
args = parser.parse_args()
## [create]
# create Background Subtractor objects
if args.algo == 'MOG2':
    backSub = cv2.createBackgroundSubtractorMOG2()
else:
    backSub = cv2.createBackgroundSubtractorKNN()
## [create]
## [capture]
capture = cv2.VideoCapture(args.input)
if not capture.isOpened():
    print('Unable to open: ' + args.input)
    exit(0)
## [capture]
while True:
    ret, frame = capture.read()
    if frame is None:
        break
    ## [apply]
    # update the background model
    fgMask = backSub.apply(frame)
    ## [apply]
    ## [display_frame_number]
    # get the frame number and write it on the current frame
    cv2.rectangle(frame, (10, 2), (100,20), (255,255,255), -1)
    cv2.putText(frame, str(capture.get(cv2.CAP_PROP_POS_FRAMES)), (15, 15),
               cv2.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,0))
    ## [display_frame_number]
    ## [show]
    # show the current frame and the fg masks
    cv2.imshow('Frame', frame)
    cv2.imshow('FG Mask', fgMask)
    ## [show]
    keyboard = cv2.waitKey(30)
    if keyboard == 'q' or keyboard == 27:
        break

代码分析

分析上面代码的主要部分:

# create Background Subtractor objects  KNN or MOG2
if args.algo == 'MOG2':
    backSub = cv2.createBackgroundSubtractorMOG2()
else:
    backSub = cv2.createBackgroundSubtractorKNN()
capture = cv2.VideoCapture(args.input)
if not capture.isOpened:
    print('Unable to open: ' + args.input)
    exit(0)
# update the background model
    fgMask = backSub.apply(frame)
 # get the frame number and write it on the current frame
    cv2.rectangle(frame, (10, 2), (100,20), (255,255,255), -1)
    cv2.putText(frame, str(capture.get(cv2.CAP_PROP_POS_FRAMES)), (15, 15),
               cv2.FONT_HERSHEY_SIMPLEX, 0.5 , (0,0,0))
# show the current frame and the fg masks
    cv2.imshow('Frame', frame)
    cv2.imshow('FG Mask', fgMask)
本文转载于:https://www.yisu.com/zixun/799723.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。