python - 为什么在 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)
解决方案
图像(没有人脸的图像)可能没有任何人脸编码。
在这种情况下,您将在执行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)
推荐阅读
- javascript - 在 Angular 中拉取和订阅 firebase 数据
- laravel - 如何在laravel中上传超过3张图片
- python - 我可以从消息的上下文中获得哪些其他对象
- javascript - 谷歌自定义搜索 JSON API 调用时不断刷新
- sql - 如何正确使用if语句postgresql
- python-3.x - 输入变量未定义?
- docker - 无法在 Google Cloud Run 上部署 Ubuntu 20.04 Docker 容器
- android - Android Studio 在奇怪的文件中自动创建 JNI 函数
- javascript - 表单提交后的多个警报变体
- dataweave - Mule 4:XML 模块:如何使用 XPATH 从具有名称空间字段的 XML 消息中检索值?