首页 > 解决方案 > 为什么在 python 中使用 face_recognition 库时出现列表索引超出范围错误?

问题描述

我正在用 python 编写一个程序,该程序输入具有人的图像,将其与目录中的图像进行比较,然后将 face_recognition 为真的图像复制到另一个目录。当只有 10 个要比较的图像时,它似乎工作正常,但是当我将图像与目录中几乎等于 1000 的图像进行比较时,我得到列表索引超出范围错误。为什么会这样?代码如下

import face_recognition
import os
from shutil import copy

person = input("Enter the photo location of person to be found (eg. users/rishabh/my_photo.jpg) : ")
photos = input("Enter the photos folder location (eg. users/photo_folder) : ")
dest = input("Enter the location of folder to copy items into (eg. users/destination_folder) : ")
for filename in os.listdir(photos):
    if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png") or filename.endswith(".JPG"): 
    print(filename)
    files = photos + '/' + filename

    known_image = face_recognition.load_image_file(person)
    unknown_image = face_recognition.load_image_file(files)
    biden_encoding = face_recognition.face_encodings(known_image)[0]
    unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

    results = face_recognition.compare_faces([biden_encoding], unknown_encoding)
    if(results[0]==True):
        src = photos+'/'+str(filename)
        copy(src, dest)

在此处输入图像描述

标签: pythonruntime-error

解决方案


图像(没有人脸的图像)可能没有任何人脸编码。

在这种情况下,您将在执行face_recognition.face_encodings.

对空列表进行索引将引发异常 (a=[]; a[0])。

因此,我在您的代码中添加了一行来检查列表是否具有值。

尝试运行以下代码并检查

import face_recognition
import os
from shutil import copy

person = input("Enter the photo location of person to be found (eg. users/rishabh/my_photo.jpg) : ")
photos = input("Enter the photos folder location (eg. users/photo_folder) : ")
dest = input("Enter the location of folder to copy items into (eg. users/destination_folder) : ")

known_image = face_recognition.load_image_file(person)
biden_encoding = face_recognition.face_encodings(known_image)

for filename in os.listdir(photos):
    if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png") or filename.endswith(".JPG"):
        print(filename)
        f = os.path.join(photos, filename)

        unknown_image = face_recognition.load_image_file(f)
        unknown_encoding = face_recognition.face_encodings(unknown_image)
        if not len(unknown_encoding):
            print(filename, "can't be encoded")
            continue

        results = face_recognition.compare_faces(biden_encoding, unknown_encoding[0])
        if(results[0]==True):
            copy(f, dest)

推荐阅读