在实时视频中统计人数

Har*_*aki 6 python webcam opencv face-detection

我使用以下代码从早到晚计算实时网络摄像头的人数

people_list = []

while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(gray, 1.3, 5)

    detections = faceCascade.detectMultiScale(gray, 1.15, 5)

    for i in range(len(detections)):
        face_i = detections[i]
        x, y, w, h = face_i

        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 222, 0), 1)
        font = cv2.FONT_HERSHEY_SIMPLEX
        people_list.insert(len(people_list)+1,i)

        cv2.putText(frame, "id: "+str ( people_list[i]), (x, y), font, 2, (255, 255, 255), 2, cv2.LINE_AA)

    # Display the resulting frame
    cv2.imshow('Video', frame)
Run Code Online (Sandbox Code Playgroud)

每次检测到新面孔时,people_list计数都会增加.但是,每个帧而不是每个新面都会增加people_list计数.我怎样才能解决这个问题?

Joe*_*don 0

不需要清单...

首先,由于您没有IDs人员,因此存储在列表中看到的人员是没有意义的,因此您应该只使用存储以下内容的变量int

people_count = 0
Run Code Online (Sandbox Code Playgroud)

然后代替这个:

people_list.insert(len(people_list)+1,i)
Run Code Online (Sandbox Code Playgroud)

您需要检查当前帧中的人数是否大于上一帧中的人数,如果是则people_count增加the number of people in the current frame- the number of people in the last frame。因此,如果4最后一帧有人,并且有6这一帧,则增加2

因此,不要执行上面的行,而是执行以下操作:

if len(detections) > last_count:
   people_count += len(detections - last_count)

last_count = len(detection)
Run Code Online (Sandbox Code Playgroud)

假设您在代码开头last_count声明为,这应该对您有用......0

然而,正如评论中提到的,如果您不能唯一地识别面孔,那么您的程序中将会存在很大的障碍。

地板是,如果person A进入房间,people_count将增加,然后如果person B也进入,people_count现在将是2。如果person A现在离开,它仍然在2(因为有人2)。但现在如果person A返回,它会增加错误的计数,3因为你只看到了2人。

此外,如果您仅错过一张脸一帧,那么计数就会增加,因为当该人离开并且有新人进入房间时,计数将会增加。

ps 作为旁注,当添加到列表末尾时,您不应该使用.insert(len(lst), val),而是应该使用,.append(val)因为这样更整洁:)