python - IndexError:使用面部识别和opencv列出超出范围的索引
问题描述
import numpy as np
import cv2
import face_recognition as fr
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Could not open webcam")
person1_image = fr.load_image_file("person1.JPG")
person2_image = fr.load_image_file("person2.jpg")
person1_image_encoding = fr.face_encodings(person1_image)
person2_image_encoding = fr.face_encodings(person2_image)
known_face_encodings = [person1_image_encoding, person2_image_encoding]
known_face_names = ["person1", "person2"]
while True:
ret, frame = cap.read()
rgb_frame = frame[:, :, ::-1]
face_locations = fr.face_locations(rgb_frame)
face_encodings = fr.face_encodings(rgb_frame, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = fr.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
face_distances = fr.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
print(best_match_index)
if matches[best_match_index]:
name = known_face_names[best_match_index]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
cv2.imshow('Webcam_facerecognition', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
这一直有效,直到它检测到一张脸,此时它会说:
如果匹配[best_match_index]:IndexError:列表索引超出范围
我打印了匹配索引。似乎它们的数字大于 2,例如 62、120 或类似的数字。
解决方案
你为什么不尝试而不是best_match_index = np.argmin(face_distances)
像
best_match_index = face_distances.index(min(face_distances))
??
推荐阅读
- firebase - 当您知道字段值时,删除 firebase 中的文档
- python - 如何格式化我的文本数据集以进行训练?
- amazon-web-services - AWS execute-api 端点请求超时/拨号 tcp i/o 超时
- python - 神经网络架构推荐
- css - 如何使用 Material UI 和 Flexbox 使播放按钮居中
- powershell - 使用 Powershell 的两个 .csv 文件之间的区别
- c - 在英文 ASCII 字符中转换十六进制数字
- react-native - 从导航堆栈中删除屏幕
- python - Kubeflow Pipeline - 存储(传递)TF.Dataset
- sql - TSQL 使用自定义值将表数据复制到另一个表