[Python] IndexError: list index out of range, face_recognition

Discussão em 'Python' iniciado por Stack, Maio 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am using open cv and face recognition together, however this line of code:

    biden_encoding = face_recognition.face_encodings(known_image)[0]


    is giving me the following error:

    IndexError: list index out of range


    I have read up on this error and most conclude that it means that face_recognition is not detecting any faces in the frame. However, open cv is detecting faces within that same frame, so I am not sure if face_recognition is indeed not detecting any faces or I am receiving an IndexError for some other reason?

    all the code needed to get a background of the issue:

    check, frame = video.read()
    faceCascade = cv2.CascadeClassifier(
    'C:\\Users\\Astroid\\Desktop\\face detection software\\data\\haarcascade_frontalface_alt.xml')

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

    faces = faceCascade.detectMultiScale(
    frame,
    scaleFactor=1.2,
    minNeighbors=5,
    )

    for x, y, w, h in faces:
    img = cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 1)

    if len(os.listdir("C:\\Users\\Astroid\\Desktop\\face detection software\\saved faces\\")) == 0:

    cv2.imwrite(
    "C:\\Users\\Astroid\\Desktop\\face detection software\\saved faces\\" + "1 faces.jpg", cropped)
    else:
    cv2.imwrite(
    "C:\\Users\\Astroid\Desktop\\face detection software\\unknown faces\\" + " unknown_faces.jpg", cropped)

    known_image = face_recognition.load_image_file(
    "C:\\Users\\Astroid\\Desktop\\face detection software\\saved faces\\" + "1 faces.jpg")

    unknown_image = face_recognition.load_image_file(
    "C:\\Users\\Astroid\Desktop\\face detection software\\unknown faces\\" + " unknown_faces.jpg"

    biden_encoding = face_recognition.face_encodings(known_image)[0]
    print(biden_encoding)#

    unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
    print(unknown_encoding)#

    results = face_recognition.compare_faces([biden_encoding], [unknown_encoding])

    if results >= (60):
    shutil.move(
    "C:\\Users\\Astroid\Desktop\\face detection software\\unknown faces\\" + " unknown_faces.jpg",
    "C:\\Users\\Astroid\\Desktop\\face detection software\\saved faces\\" + (face_num) + (" faces.jpg"))
    else:
    pass

    Continue reading...

Compartilhe esta Página