首页 > 解决方案 > 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

这是输出的屏幕截图:

此读数显示 11 人

这个显示 14

有人可以帮忙吗?

标签: pythonopencvimage-processingopticalflow

解决方案


推荐阅读