使用python实现人脸识别
时间: 2023-12-04 11:58:32 浏览: 123
人脸识别是一种广泛应用于生物识别的技术,它可以通过图像处理技术自动识别人脸,并进行身份验证或者身份识别。在Python中,有很多开源的库可以用来实现人脸识别,比如OpenCV、Dlib、Face_recognition等。
下面是一个使用Face_recognition库实现人脸识别的示例代码:
1. 安装Face_recognition库
```
pip install face_recognition
```
2. 导入必要的库
```python
import face_recognition
import cv2
import numpy as np
```
3. 加载已知人脸图像
```python
# 加载已知人脸图像
known_face_encodings = []
known_face_names = []
# 加载第一个人脸图像
image = face_recognition.load_image_file("person1.jpg")
face_encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(face_encoding)
known_face_names.append("person1")
# 加载第二个人脸图像
image = face_recognition.load_image_file("person2.jpg")
face_encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(face_encoding)
known_face_names.append("person2")
```
4. 开始识别人脸
```python
# 打开摄像头
video_capture = cv2.VideoCapture(0)
while True:
# 读取一帧视频
ret, frame = video_capture.read()
# 将图像从BGR颜色空间转换成RGB颜色空间
rgb_frame = frame[:, :, ::-1]
# 检测人脸
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
# 遍历每个人脸
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# 对比已知人脸
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# 找到最佳匹配的人脸
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
# 在图像上标记人脸
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
# 显示结果
cv2.imshow('Video', frame)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头
video_capture.release()
cv2.destroyAllWindows()
```
以上代码实现了一个简单的人脸识别程序,它可以从摄像头读取视频,并检测其中的人脸。如果检测到的人脸与已知人脸库中的某个人脸匹配,则在视频中标记出该人脸,并显示其姓名。如果检测到的人脸与已知人脸库中的所有人脸都不匹配,则将其标记为Unknown。
阅读全文
相关推荐
















