python opencv背景减法 [英] Python opencv background subtraction
问题描述
我需要做的很简单:
1-加载5帧视频文件
2-检测背景
3-在每一帧上,一一:
-1-减去背景(创建前景蒙版)
-2-对前景蒙版进行一些计算
-3-保存原始帧和前景蒙版
1- load a 5 frames video file
2- detect background
3- On every frames, one by one :
-- 1- subtract background (create foreground mask)
-- 2- do some calculations on foreground mask
-- 3- save both original frame and foreground mask
只看5帧和5个对应的fgmasks:
Just to see the 5 frames and the 5 corresponding fgmasks :
import numpy as np
import cv2
cap = cv2.VideoCapture('test.avi')
fgbg = cv2.BackgroundSubtractorMOG()
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
# Display the fgmask frame
cv2.imshow('fgmask',fgmask)
# Display original frame
cv2.imshow('img', frame)
k = cv2.waitKey(0) & 0xff
if k == 5:
break
cap.release()
cv2.destroyAllWindows()
打开并正确显示每个框架,但是显示的fgmask与显示的原始框架不对应.在此过程中的某个地方,fgmask的顺序变得混乱.
Every frame gets opened and displayed correctly but the showed fgmask do not correspond to the showed original frame. Somewhere in the process, the order of the fgmasks gets mixed up.
背景确实被正确减去,但是我没有得到5个预期的fgmasks.
The background does get subtracted correctly but I don't get the 5 expected fgmasks.
我想念什么?我觉得这应该很简单:while循环在视频的5帧上运行,并且fgbg.apply对每帧应用背景减法功能.
What am I missing ? I feel like this should be straightforward : the while loop runs over the 5 frames of the video and fgbg.apply apply the background subtraction function to each frame.
opencv-2.4.9-3
opencv-2.4.9-3
推荐答案
正如bikz05所建议的那样,运行平均方法在我的5个图像集上效果很好.谢谢你的提示!
As bikz05 suggested, running average method worked pretty good on my 5 images sets. Thanks for the tip !
import cv2
import numpy as np
c = cv2.VideoCapture('test.avi')
_,f = c.read()
avg1 = np.float32(f)
avg2 = np.float32(f)
# loop over images and estimate background
for x in range(0,4):
_,f = c.read()
cv2.accumulateWeighted(f,avg1,1)
cv2.accumulateWeighted(f,avg2,0.01)
res1 = cv2.convertScaleAbs(avg1)
res2 = cv2.convertScaleAbs(avg2)
cv2.imshow('img',f)
cv2.imshow('avg1',res1)
cv2.imshow('avg2',res2)
k = cv2.waitKey(0) & 0xff
if k == 5:
break
这篇关于python opencv背景减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!