您好,欢迎访问一九零五行业门户网

python  OpenCV怎么使用背景分离方法

理论背景分离(bs)是一种通过使用静态相机来生成前景掩码(包含属于场景中的移动对象像素的二进制图像)的常用技术
顾名思义,bs计算前景掩码,在当前帧与背景模型之间执行减法运算,其中包含场景的静态部分,考虑到所观察场景的特征,可以将其视为背景的所有内容。
背景建模包括两个主要步骤:
1.背景初始化
2.背景更新 第一步,计算背景的初始模型,在第二步中,更新模型以适应场景中可能的变化
实现让用户选择处理视频文件或图像序列。在此示例中,将使用cv2.backgroundsubtractormog2 生成前景掩码。
from __future__ import print_functionimport cv2import argparseparser = 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 objectsif 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
代码分析分析上面代码的主要部分:
cv2.backgroundsubtractor对象将用于生成前景掩码。在此示例中,使用了默认参数,但是也可以在create函数中声明特定的参数。
# create background subtractor objects knn or mog2if args.algo == 'mog2': backsub = cv2.createbackgroundsubtractormog2()else: backsub = cv2.createbackgroundsubtractorknn()
cv2.videocapture对象用于读取输入视频或输入图像序列
capture = cv2.videocapture(args.input)if not capture.isopened: print('unable to open: ' + args.input) exit(0)
每帧都用于计算前景掩码和更新背景。如果要更改用于更新背景模型的学习率,可以通过将参数传递给apply方法来设置特定的学习率
# update the background model fgmask = backsub.apply(frame)
当前帧编号可以从cv2.videocapture对象中提取,并在当前帧的左上角冲压。使用白色矩形来突出显示黑色框架号
# 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)
以上就是python  opencv怎么使用背景分离方法的详细内容。
其它类似信息

推荐信息