![](/img/trans.png)
[英]IndexError: list index out of range with face recognition and opencv
[英]IndexError: list index out of range, face_recognition
我同时使用开放式简历和人脸识别,但是这行代码:
biden_encoding = face_recognition.face_encodings(known_image)[0]
给我以下错误:
IndexError: list index out of range
我已经阅读了这个错误并且大多数人认为这意味着 face_recognition 没有检测到框架中的任何人脸。 但是,open cv 正在同一帧内检测人脸,所以我不确定 face_recognition 是否确实没有检测到任何人脸,或者由于其他原因我收到了 IndexError?
了解问题背景所需的所有代码:
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
这意味着, dlib
人脸检测器无法检测到您传入的图像中的人脸。您可以添加一个 try 异常块,如下所示:
try:
image_to_be_matched_encoded = face_recognition.face_encodings(known_image)[0]
except IndexError as e:
print(e)
sys.exit(1) # stops code execution in my case you could handle it differently
更多信息可以在这里找到: https ://github.com/ageitgey/face_recognition/issues/100#issuecomment-307590846
我通过将图像更改为 jpeg 来解决该问题,这意味着您应该使用 jpeg 类型包含此类图像的干净质量,问候
这意味着face_recognition
模块在图像中找不到任何人脸。 face_recognition.face_encodings(known_image)
基本上返回照片中找到的所有面孔的列表。 现在,您正在使用索引[0]
来获取第一个找到的人脸。 但是,当图像中没有人脸时,您会尝试获取不存在的索引,因此会出现IndexError
。
唯一真正的解决方案是使用新图像。 face_recognition
无法找到任何人脸,因此您可以制定自己的算法来查找人脸,我强烈不建议这样做,或者您使用不同的图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.