裁剪来自网络摄像头的实时视频输入以进行面部识别

时间:2019-09-10 21:38:18

标签: python opencv facial-identification

我正在使用Python中的OpenCV进行面部识别,并且我想从网络摄像头中裁剪实时视频以仅输出其可以识别的面部。

我尝试使用ROI,但是我不知道如何正确实施它。

import cv2
import sys

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "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)
        roi = frame[y:y+h, x:x+w]
        cropped = frame[roi]


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


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

Traceback (most recent call last):
  File "C:/Users/Ben/Desktop/facerecog/facerecog2.py", line 31, in <module>
    cv2.imshow('Face', cropped)
cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\array.cpp:2492: error: (-206:Bad flag (parameter or structure field)) Unrecognized or unsupported array type in function 'cvGetMat'

1 个答案:

答案 0 :(得分:0)

您将使用

裁剪图像
cropped = frame[y:y+h, x:x+w]

然后您可以显示它。


但是有时框架上没有面孔,并且不会创建cropped,并且您可能会出错。最好在for之前创建此variabel,然后在for之后检查它

cropped = None

for (x, y, w, h) in faces:
    cropped = frame[y:y+h, x:x+w]

if cropped is not None:
    cv2.imshow('Face', cropped)
#else:
#    cv2.imshow('Face', frame)

if faces:
    (x, y, w, h) = faces[0]
    cropped = frame[y:y+h, x:x+w]
    cv2.imshow('Face', cropped)

如果框架上有很多人脸,我不知道该怎么办。