Home > Software design >  How to know when the list of faces is empty?
How to know when the list of faces is empty?

Time:12-09

I used this program to detect faces in video taken from my webcam, everything is working fine and a rectangle is showing over any face that appears in the frame. I am using this code to send the x values of the face to an Arduino microcontroller to manipulate a servo. when there are no faces, the x value remains the same as the last time when there was a face. How can I know that there are no faces in a frame so I can tell the servo to remain at the same position?

This is the code

import cv2
import sys

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)

video_capture = cv2.VideoCapture(1)
while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x w, y h), (0, 255, 0), 2)
        if x>=300:
            print("right")
        elif x<=240:
           print("left")
        elif x<300 and x>240:
            print('mid')
        else:
            print('no face detected')
    
    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

I am trying to print "mid" when the face is in the middle of the frame, "left" when it's on the left and "right" when it's on the right. It's working fine but if the face is on the right and disappear, "right" will still be printed and "no faces found" will never be printed. I am expecting something to tell me that there is no faces in the frame.

CodePudding user response:

You iterate over detected faces here

for (x, y, w, h) in faces:

And inside that loop you print "no faces detected", that does not make sense. IF no faces are detected THEN faces is an empty list, so the for loop does NOT get executed at all.

Insert those lines before the for loop:

if len(faces) == 0:
    print("No faces detected!")
  • check if faces is an empty list
  • if that's the case print that no faces are detected
  • Related