无法识别人脸时如何触发警告?

时间:2019-04-10 06:47:35

标签: python opencv-python

这是用于检测人脸的代码。

我希望每当识别出面部时,在面部图像上显示一个矩形,这很好,但是,每当未识别出面部时,在面部图像上都没有显示矩形,并且打印一些消息。

import cv2
face_cascade = cv2.CascadeClassifier('C:/Users/320052863/PycharmProjects/trial/venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:/Users/320052863/PycharmProjects/trial/venv/Lib/site-packages/cv2/data/haarcascade_eye.xml')
cap = cv2.VideoCapture(0)

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: 
        re = cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)
        if 're' in locals():
            print('abhishek')
        else:
            print('gupta')
        roi_gray = gray[y:y+h, x:x+w] 
        roi_color = img[y:y+h, x:x+w]
    cv2.imshow('Abhishek',img)

    # Wait for Esc key to stop
    k = cv2.waitKey(30)
    if k == 13:
        break
cap.release()
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:0)

看来,如果在您的脚本中,在您的行之后:

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

您插入以下行,如果未检测到脸部,它将发出警告:

if len(faces) == 0:
    print "No faces found"