python - Opencv“len(contour)”返回错误值
问题描述
我正在使用 OpenCV 库进行人群计数。首先,我使用“findContours()”方法找到轮廓,该方法基本上将这些轮廓放在一个数组中。当我试图获取场景中的人数时,我使用 len() 函数来读取包含轮廓的数组的长度。
但是,我得到了错误的读数,我不知道为什么可能是由于阈值,但我是 python 和图像处理的新手,所以我无法真正确定问题所在,甚至无法为我的背景选择合适的阈值。
这是我的代码,我将附上一些图片来显示错误读数的样子:
from cv2 import cv2
import time
video= cv2.VideoCapture('vtest.avi')
frameTime = 30 # time of each frame in ms, you can add logic to change this value.
first_frame=None
while True:
check,frame=video.read()
font = cv2.FONT_HERSHEY_SIMPLEX
if cv2.waitKey(frameTime) & 0xFF == ord('q'):
break
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray=cv2.GaussianBlur(gray,(21,21),0)
if first_frame is None:
first_frame=gray
continue
delta_frame=cv2.absdiff(first_frame,gray)
threshold_frame=cv2.threshold(delta_frame,50,255,cv2.THRESH_BINARY)[1]
threshold_frame=cv2.dilate(threshold_frame,None,iterations=2)
(cntr,_)=cv2.findContours(threshold_frame.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
number = 0
for contour in cntr:
if cv2.contourArea(contour)<1000:
continue
(x,y,w,h)=cv2.boundingRect(contour)
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3)
number_of_objects_in_image= len(cntr)
NumberToString = str(number_of_objects_in_image)
cv2.putText(frame,
'number of people:'+NumberToString,
(50, 50),
font, 1,
(0, 255, 255),
2,
cv2.LINE_4)
cv2.imshow("vtest.avi",frame)
key=cv2.waitKey(1)
if key==ord('q'):
break
video.release()
cv2.destroyAllWindows
这是输出的屏幕截图:
有人可以帮忙吗?
解决方案
推荐阅读
- java - 应用程序服务器一直在 docker 容器中运行,无法使用 postgresql dirver。连接被拒绝
- javascript - 'syntaxError: Unexpected end of input' 在 javascript 中编码不和谐机器人时
- sql - EF Core:在没有事务的情况下将多个不相关的行添加到数据库中的有效方法?
- .net - 错误 NU1605 检测到包降级:log4net 从 2.0.11 到 2.0.3
- c - 使用 scanf- 小数读取双精度会导致换行问题
- python - 如何使用“姓氏”制作搜索表单
- django - ImportError:无法从“django.forms.fields”导入名称“EMPTY_VALUES”
- javascript - 在 React 中只运行一次函数
- tensorflow - 在启用了 Eager 模式的情况下构造 `Model` 实例时,不支持在图形模式下调用 `Model.predict`
- reactjs - 根据打开的父 Popper 组件有条件地显示 Tooltip