没有检测到人脸时cv2人脸检测问题

时间:2020-09-30 09:12:23

标签: python opencv flask

我有一个应用程序,我尝试检测人脸并打印嗨!当检测到脸部时。我的问题是,即使面孔(人)从可见区域移开,消息也不会改变。在这种情况下,我想打印“找不到面孔”。

在未检测到人脸的情况下如何采取行动,无论是打印声音还是以声音形式发出其他通知。

我到目前为止编写的代码:

import cv2
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
cap = cv2.VideoCapture(0)

while 1:

    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, 1.3, 5)
    if len(faces) == 0:
        print
        "No faces found"
    for (x,y,w,h) in faces:
        re = cv2.rectangle(img,(x,y),(x+w,y+h),(200,200,0),2)
        if 're' in locals():
            print('Hi')
        else:
            print('No faces found')
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
    cv2.imshow('Hi',img)

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

2 个答案:

答案 0 :(得分:1)

我建议检查this example以了解应如何检测面部,您的条件if 're' in locals():检查变量locals()中是否存在变量,但是您在此处创建了变量,而是想检查面部,然后可能将它们放在正方形中并向他们问好,一旦您进入for循环,那里就会有面部检测。

满足您需求的简约代码:

import cv2
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, 1.3, 5)
    title = "Hi!"
    if len(faces) == 0:
        title = "No faces found!" 
        #or do something else here if no faces were found...
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(200,200,0),2)
        cv2.putText(frame,'Hi!',(x + sx,y + sy), 1, 1, (0, 255, 0), 1)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
    cv2.imshow(title,img)

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

答案 1 :(得分:1)

这是一个非常简单的错误

print
"No faces found"

是导致错误的原因,请尝试将其更改为

print("No faces found")

您正在做的是调用打印函数,只是定义一个字符串而不使用它。

要播放声音,您可以GitHub repository with working Rocket v0.4 microservice using Elasticsearch