用pycharm实现人脸识别代码
时间: 2023-07-18 16:13:51 浏览: 79
以下是一个基本的Python代码示例,用于在PyCharm中实现人脸识别:
```python
import cv2
import face_recognition
# 加载数据集
known_face_encoding = []
known_face_name = []
# 加载本地图片并将其编码为人脸识别模型使用的格式
image = face_recognition.load_image_file("path_to_image")
face_encoding = face_recognition.face_encodings(image)[0]
# 将编码后的人脸特征向量添加到已知的人脸编码向量列表中
known_face_encoding.append(face_encoding)
known_face_name.append("person_name")
# 加载测试图像
test_image = cv2.imread("path_to_test_image")
rgb_test_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2RGB)
# 使用人脸识别模型识别测试图像中的人脸
face_locations = face_recognition.face_locations(rgb_test_image)
face_encodings = face_recognition.face_encodings(rgb_test_image, face_locations)
# 遍历测试图像中的每个人脸并进行识别
for face_encoding, face_location in zip(face_encodings, face_locations):
# 将测试图像中的人脸编码与已知的人脸编码进行比较,以识别人脸
matches = face_recognition.compare_faces(known_face_encoding, face_encoding)
name = "Unknown"
# 如果找到匹配的人脸,则将其名称设置为已知的人脸名称
if True in matches:
first_match_index = matches.index(True)
name = known_face_name[first_match_index]
# 在测试图像中绘制人脸位置和名称
top, right, bottom, left = face_location
cv2.rectangle(test_image, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(test_image, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# 显示测试图像
cv2.imshow("Test Image", test_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先加载了一个数据集,其中包含已知的人脸图像和它们的名称。然后,我们加载了一个测试图像,使用face_recognition库进行人脸检测和编码。最后,我们使用已知的人脸编码向量与测试图像中的人脸编码向量进行比较,以识别人脸并将其名称添加到测试图像中。