pythoncvlib

How to check if these is no face detected using cvlib


cvlib library in python is well established and many people in research community uses it. I noticed that if threr is no face detected the (for) loop stops for exampe, if i have the following code:

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()

as Im printing (faces) the output would be somthing like this

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

However, as soon as I block the camera or move my head away from it, as there is no face detected, the for loop freezes or pauses till it sees a face to detect.

I need an if statement or any other condition to check this freeze or a pause to produce do something else.


Solution

  • I have found the answer to this question if we add an if statement before the for loop as faces is an int produces 1,2,3 depending on how many faces in front of the camera.

    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()