0

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 语句或任何其他条件来检查此冻结或暂停以执行其他操作。

4

2 回答 2

0

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

移出循环imshowfor例如,

# 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

在此处查看完整示例。

于 2020-04-09T06:10:17.413 回答
0

如果我们在 for 循环之前添加一个 if 语句,我已经找到了这个问题的答案,因为 faces is an int 会产生 1,2,3,具体取决于相机前面有多少个面。

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()
于 2020-04-09T11:09:50.287 回答