帮我用python中的face-recognition写一段人脸识别的代码,要求能从指定的图像中认识人脸,并将图像名称作为该人员的姓名,并在其他给定的图片中识别出人脸,并用框与文字表明该人的身份
时间: 2023-05-11 19:02:13 浏览: 102
python实现人脸识别代码
5星 · 资源好评率100%
好的,以下是使用 face-recognition 库进行人脸识别的 Python 代码:
```python
import face_recognition
import os
# 加载已知人脸图像
known_faces = []
known_names = []
for file in os.listdir("known_faces"):
image = face_recognition.load_image_file("known_faces/" + file)
encoding = face_recognition.face_encodings(image)[0]
known_faces.append(encoding)
known_names.append(os.path.splitext(file)[0])
# 加载待识别图像
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)
# 标记人脸并输出结果
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = "Unknown"
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
# 在图像中标记人脸
cv2.rectangle(unknown_image, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(unknown_image, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
# 显示结果
cv2.imshow("Result", unknown_image)
cv2.waitKey(0)
```
这段代码可以从指定的图像中识别人脸,并将图像名称作为该人员的姓名,并在其他给定的图片中识别出人脸,并用框与文字表明该人的身份。请注意,这段代码需要 face-recognition 库的支持,你需要先安装该库。
阅读全文