用python写人脸识别的代码
时间: 2024-09-19 19:12:57 浏览: 94
在Python中实现人脸识别通常需要使用深度学习库如TensorFlow、Keras或PyTorch,以及一些专为人脸识别设计的模型库,例如Dlib、Face_recognition等。这里给出一个简单的基于预训练模型的面部识别示例:
```python
import face_recognition
# 加载已知的人脸图像
known_faces = []
known_names = []
for i in range(5): # 假设我们有5个人的脸部图片
image_path = f"person_{i}.jpg"
img = face_recognition.load_image_file(image_path)
known_faces.append(img)
known_names.append("Person " + str(i+1))
# 加载待识别的图像
test_image = face_recognition.load_image_file("unknown.jpg")
# 使用face_recognition的compare_faces函数识别人脸
face_locations = face_recognition.face_locations(test_image)
face_encodings = face_recognition.face_encodings(test_image, face_locations)
# 比较测试图像中的人脸编码与已知的人脸
for face_encoding, name in zip(face_encodings, known_names):
results = face_recognition.compare_faces(known_faces, face_encoding)
if True in results:
best_match_index = results.index(True)
print(f"The unknown person is {name}")
break
# 如果没有匹配,可以添加其他处理逻辑
if not results:
print("No match found for the given face.")
阅读全文