0

我正在使用 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'
4

1 回答 1

0

你得到裁剪的图像

cropped = frame[y:y+h, x:x+w]

然后你可以显示它。


但有时框架上没有人脸,它不会创建cropped,你可能会出错。最好在之前创建这个变量for并在之后检查它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)

如果框架上有很多面孔,我不知道你想做什么。

于 2019-09-10T22:33:38.397 回答