问题描述
我正在使用每5秒钟左右将快照发布到网络的相机.相机正在监视一行人.我希望我的剧本能够告诉我一行人有多久.
I'm working with a camera that posts a snapshot to the web every 5 seconds or so. The camera is monitoring a line of people. I'd like my script to be able to tell me how long the line of people is.
-
起初,我以为可以使用
BackgroundSubtractorMOG
,但这只是产生黑色图像.这是我的代码,将其修改为使用图像而不是视频捕获:
At first, I thought I could do this using
BackgroundSubtractorMOG
, but this is just producing a black image. Here's my code for that, modified to use an image instead of a video capture:
import numpy as np
import cv2
frame = cv2.imread('sample.jpg')
fgbg = cv2.BackgroundSubtractorMOG()
fgmask = fgbg.apply(frame)
cv2.imshow('frame', fgmask)
cv2.waitKey()
接下来,我查看了前景提取图像,但这是交互式的,不适合我需要脚本告诉我一行人有多久的用例.
Next, I looked at foreground extraction on an image, but this is interactive and doesn't suit my use case of needing the script to tell me how long the line of people is.
我是opencv的新手,因此非常感谢您的帮助.我可以根据要求提供任何其他详细信息.
I'm brand new to opencv, so any help is greatly appreciated. I can supply any additional details upon request.
我并不是在寻找可以解决整体问题的人,因为我只是想找出一种将人们与背景隔离开的方法.但是,如果您认为自己有更好的解决方案,我愿意以不同的方式解决这个问题.
I'm not so much looking for someone to solve the overall problem, as I am just trying to figure out a way to separate out the people from the background. However, I am open to approaching the problem a different way if you think you have a better solution.
编辑:这是根据要求提供的示例图片:
Here's a sample image as requested:
推荐答案
我知道了! @QED帮助我到达了那里.基本上,您不能仅使用一张图像来执行此操作.您需要至少2帧进行比较,以便算法可以分辨出不同之处(前景)和相同之处(背景).因此,我拍了2帧,然后遍历它们以训练"算法.这是我的代码:
I figured it out! @QED helped me get there. Basically, you can't do this with just one image. You need AT LEAST 2 frames to compare so the algorithm can tell what's different (foreground) and what's the same (background). So I took 2 frames and looped through them to "train" the algorithm. Here's my code:
import numpy as np
import cv2
i = 1
while(1):
fgbg = cv2.BackgroundSubtractorMOG()
while(i < 3):
print 'img' + `i` + '.jpg'
frame = cv2.imread('img' + `i` + '.jpg')
fgmask = fgbg.apply(frame)
cv2.imshow('frame', fgmask)
i += 1
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cv2.destroyAllWindows()
这是连续2张图像的结果!
And here's the result from 2 consecutive images!
这篇关于使用OpenCV for python从单个帧中提取前景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!