简体   繁体   English

在 Python OpenCV 中检查检测到的人脸?

[英]Check for a detected face in Python OpenCV?

I want to check if a face has been detected.我想检查是否检测到人脸。

I have the variable face_detect and when a face is detected I want to turn this variable to True however I don't know how to check for a detected face.我有变量face_detect ,当检测到人脸时,我想将此变量设置为True但是我不知道如何检查检测到的人脸。 I tried using faces.size() to check if it was greater than zero but it said我尝试使用faces.size()检查它是否大于零,但它说

AttributeError: 'tuple' object has no attribute 'size' AttributeError: 'tuple' object 没有属性 'size'

So I don't know why that is not working.所以我不知道为什么这不起作用。

import cv2
import numpy as np
import winsound

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

face_detect = False

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

    cv2.imshow('img', img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

I've slightly modified your code to update the face_detect variable to True whenever a face is detected.我稍微修改了您的代码,以便在检测到人脸时将face_detect变量更新为 True。

import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

face_detect = False

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
    if len(faces) > 0:
        face_detect = True
    else:
        face_detect = False
    print(face_detect)

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

    cv2.imshow('img', img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM