如何使用python计算openCV在实时视频中检测到的人脸数量?

时间:2017-03-25 12:39:11

标签: python opencv

我需要计算从网络摄像头拍摄的视频中的面部数量。例如,如果我站在摄像机前面然后计数= 1,现在如果检测到任何其他人则计数= 2,如果检测到另一个人则计数应为3.

我在python中使用opencv的frontal_face_haarcascade.xml。我可以检测帧中的面部然后增加计数,但是发生的是计数随着帧数的增加而增加。因此,即使1个人被发现站立10秒,它也会被视为“67”和“67”。

我该如何克服这个问题?

这是代码:

import cv2

import sys

cascPath = sys.argv[1]

faceCascade = cv2.CascadeClassifier(cascPath)


video_capture = cv2.VideoCapture(0)
ret, frame = video_capture.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30)
)

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)


if cv2.waitKey(1) & 0xFF == ord('q'):
    break

# Display the resulting frame
cv2.imshow('Video', frame)


video_capture.release()

cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:-1)

idx=0
while(True):
  ret, frame = video_capture.read()

  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30)
  )

  # Draw a rectangle around the faces
  for (x, y, w, h) in faces:
      cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
      idx += 1
      print (idx)


  if cv2.waitKey(1) & 0xFF == ord('q'):
      break

  # Display the resulting frame
  cv2.imshow('Video', frame)

答案 1 :(得分:-1)

import numpy as np
import cv2
faceCascade = cv2.CascadeClassifier(cascPath)

video_capture  =cv2.VideoCapture(0)
while(True):
    idx=0

    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )
    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        idx += 1
        print (idx)
        cv2.putText(frame,str(idx),(x,y+h),cv2.FONT_HERSHEY_SIMPLEX,.7,(150,150,0),2)


    cv2.imshow('img',frame)
    if(cv2.waitKey(1)==ord('q')):
        break

frame.release()
cv2.destroyAllWindows()