用Python编一段可以实现人脸识别的代码
时间: 2024-05-09 07:20:48 浏览: 17
为了实现人脸识别,我们需要使用一些 Python 库和模块。其中包括 OpenCV、dlib 和 face_recognition 库。
以下是一个简单的人脸识别代码示例:
```python
import cv2
import dlib
import face_recognition
# 加载图像
image = cv2.imread("faces.jpg")
# 使用dlib获取人脸检测器
detector = dlib.get_frontal_face_detector()
# 使用dlib获取68点特征提取器
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 使用face_recognition库获取人脸编码
known_face_encodings = []
known_face_names = []
# 加载已知人脸的图像
image1 = face_recognition.load_image_file("person1.jpg")
image2 = face_recognition.load_image_file("person2.jpg")
# 获取人脸编码
person1_face_encoding = face_recognition.face_encodings(image1)[0]
person2_face_encoding = face_recognition.face_encodings(image2)[0]
# 将人脸编码和名字添加到列表中
known_face_encodings.append(person1_face_encoding)
known_face_encodings.append(person2_face_encoding)
known_face_names.append("Person 1")
known_face_names.append("Person 2")
# 检测图像中的人脸并进行识别
faces = detector(image, 1)
for face in faces:
# 获取人脸68点坐标
landmarks = predictor(image, face)
# 将68点坐标转换为numpy数组
landmarks = face_recognition.face_utils.shape_to_np(landmarks)
# 获取人脸编码
face_encoding = face_recognition.face_encodings(image, [face])[0]
# 进行人脸匹配
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# 找到匹配的人脸
if True in matches:
match_index = matches.index(True)
name = known_face_names[match_index]
# 在图像中标记人脸并显示名字
cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (0, 0, 255), 2)
cv2.putText(image, name, (face.left(), face.top() - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
# 显示结果图像
cv2.imshow("Face Recognition", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个代码首先加载一张图像,然后使用 dlib 库获取人脸检测器和 68 点特征提取器。接着,它使用 face_recognition 库获取已知人脸的编码并将其添加到列表中。最后,它在图像中检测人脸并进行识别,标记人脸并显示名字。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)