【问题标题】:How to check if these is no face detected using cvlib如何检查这些是否没有使用 cvlib 检测到人脸
【发布时间】:2020-04-08 22:05:12
【问题描述】:

python 中的 cvlib 库非常成熟,研究界的许多人都在使用它。我注意到,如果 threr 没有检测到人脸,则(for)循环停止,例如,如果我有以下代码:

cap = cv2.VideoCapture(0)
if not (cap.isOpened()):
    print('Could not open video device')
#To set the resolution
vid_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
vid_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
while(True):
    ret, frame = cap.read()
    if not ret:
        continue
    faces, confidences = cv.detect_face(frame)
    # loop through detected faces and add bounding box
    for face in faces:
        (startX,startY) = face[0],face[1]
        (endX,endY) = face[2],face[3]
        cv2.rectangle(frame, (startX,startY), (endX,endY), (0,255,0), 2)
        crop_img = frame[startY-5:endY-5, startX-5:endX-5]```
        print(faces)
        cv2.imshow('object detected',frame)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

当我打印(面对)时,输出会是这样的

[[392, 256, 480, 369]]
[[392, 256, 478, 369]]
[[392, 255, 478, 370]]
.
.
.
[[392, 255, 478, 370]]

但是,一旦我挡住相机或将头从相机上移开,因为没有检测到人脸,for 循环会冻结或暂停,直到它看到要检测的人脸。

我需要一个 if 语句或任何其他条件来检查此冻结或暂停以执行其他操作。

【问题讨论】:

    标签: python cvlib


    【解决方案1】:

    您只显示检测到人脸的帧。如果未检测到人脸,您将看到检测到人脸的最后一帧,直到下一次在接下来的帧中检测到人脸。

    imshow 移出for 循环。例如,

    # loop through detected faces and add bounding box
    for face in faces:
        (startX,startY) = face[0],face[1]
        (endX,endY) = face[2],face[3]
        cv2.rectangle(frame, (startX,startY), (endX,endY), (0,255,0), 2)
        crop_img = frame[startY-5:endY-5, startX-5:endX-5]
        print(faces)
    
    cv2.imshow('object detected',frame)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
    

    查看完整示例 here

    【讨论】:

    • 嗨@Arun Ponnusamy,我很高兴你回答了我的问题,这是一个错字,在我的实际代码中,它写在循环之外,问题是我怎么能说这些是一张脸还是没有,因为当我用手挡住相机时,一切都停止了,没有结果出现。如果 len(faces) == 0:
    【解决方案2】:

    如果我们在 for 循环之前添加一个 if 语句,因为 faces 是一个 int,我已经找到了这个问题的答案,这取决于相机前面有多少个面。

    if len(faces) == 0:
       print('no faces')
       print(faces) # going to print 0
    else:
       for face in faces:
           (startX,startY) = face[0],face[1]
           (endX,endY) = face[2],face[3]
           crop_img = frame[startY-5:endY-5, startX-5:endX-5]
           cv2.rectangle(frame, (startX,startY), (endX,endY), (0,255,0), 2)
        cv2.imshow('object detected',frame)
    
        k = cv2.waitKey(30) & 0xff
        if k == 27:
            break
    cap.release()
    cv2.destroyAllWindows()
    

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 2013-09-24
      • 2022-06-24
      • 2020-06-28
      • 2016-11-18
      • 1970-01-01
      • 2017-07-30
      • 2019-12-01
      • 2021-08-27
      相关资源
      最近更新 更多