python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python  OpenCV背景分离

详解python  OpenCV如何使用背景分离方法

作者:uncle_ll

这篇文章主要为大家介绍了python OpenCV如何使用背景分离方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

目标

在本章中,将学习:

理论

实现

让用户选择处理视频文件或图像序列。在此示例中,将使用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)

结果

附加资源

以上就是OpenCV如何使用背景分离方法的详细内容,更多关于OpenCV背景分离的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文