使用 python 和 opencv 计算人脸

count faces with python and opencv

我在 python 中有使用 opencv2 检测人脸的脚本。我在网络摄像头中拍摄视频并使用 Haar Cascade 检测人脸。我想摆脱一帧中检测到的人脸数量。我知道这可以通过在找到一张脸时计算矩形来完成。怎么做?如何计算一帧中的矩形?

import cv2
import sys

faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

video_capture = cv2.VideoCapture(0)


while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()

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

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

    # 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)



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


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

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

简单使用len(faces)应该return面数