【发布时间】:2021-08-09 17:07:36
【问题描述】:
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 或类似的数字。
【问题讨论】:
-
您的问题解决了吗?有什么反馈吗?
标签: python opencv face-recognition