python 读取当前 face 文件夹下所有人脸图片,并显示所有人脸识别结果的程序示例
时间: 2023-06-02 16:07:45 浏览: 201
好的,以下是示例程序:
```python
import face_recognition
import os
# 读取所有图片文件名
image_files = os.listdir('face')
# 加载所有图片的人脸编码和标签
known_faces = []
known_labels = []
for filename in image_files:
image = face_recognition.load_image_file(f'face/{filename}')
face_encoding = face_recognition.face_encodings(image)[0]
label = os.path.splitext(filename)[0]
known_faces.append(face_encoding)
known_labels.append(label)
# 加载待识别图片
unknown_image = face_recognition.load_image_file('unknown.jpg')
# 识别所有人脸
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
face_labels = []
for face_encoding in face_encodings:
# 比对待识别人脸和已知人脸
matches = face_recognition.compare_faces(known_faces, face_encoding)
label = 'Unknown'
# 找到匹配的标签
if True in matches:
match_index = matches.index(True)
label = known_labels[match_index]
face_labels.append(label)
# 显示识别结果
import cv2
for (top, right, bottom, left), label in zip(face_locations, face_labels):
cv2.rectangle(unknown_image, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(unknown_image, label, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.imshow('Face recognition result', unknown_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
希望能对你有所帮助!
阅读全文