python人脸识别全部代码
时间: 2023-09-02 10:14:04 浏览: 38
人脸识别涉及到很多算法和技术,需要用到不同的库和工具。以下是一个基于 Python 的简单人脸识别代码示例,使用 OpenCV 和 face_recognition 库:
```python
import cv2
import face_recognition
# 加载已知人脸图像和对应标签
known_face_encodings = []
known_face_labels = []
# 加载已知人脸图像和对应标签的函数
def load_known_faces():
# 在这里添加代码,用于加载已知人脸图像和对应标签
# 例如:
# image = face_recognition.load_image_file("known_faces/john.jpg")
# encoding = face_recognition.face_encodings(image)[0]
# known_face_encodings.append(encoding)
# known_face_labels.append("John")
# 加载已知人脸图像和对应标签
load_known_faces()
# 设置摄像头
video_capture = cv2.VideoCapture(0)
# 初始化变量
face_locations = []
face_encodings = []
face_labels = []
while True:
# 读取摄像头捕获的图像
ret, frame = video_capture.read()
# 缩小图像以加快处理速度
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# 转换图像格式
rgb_small_frame = small_frame[:, :, ::-1]
# 检测图像中的人脸位置
face_locations = face_recognition.face_locations(rgb_small_frame)
# 提取图像中人脸的特征编码
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
# 初始化标签列表
face_labels = []
# 对于每个检测到的人脸,进行标签识别
for face_encoding in face_encodings:
# 尝试匹配人脸与已知人脸
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
# 初始化标签为 "Unknown"
label = "Unknown"
# 如果找到匹配的已知人脸,则使用该标签
if True in matches:
first_match_index = matches.index(True)
label = known_face_labels[first_match_index]
# 将标签添加到标签列表中
face_labels.append(label)
# 在图像中为每个检测到的人脸添加标签
for (top, right, bottom, left), label in zip(face_locations, face_labels):
# 放大坐标以适应原始图像大小
top *= 4
right *= 4
bottom *= 4
left *= 4
# 在人脸周围画一个矩形
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# 在人脸下方添加标签
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, label, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
# 显示结果图像
cv2.imshow('Video', frame)
# 按 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
video_capture.release()
cv2.destroyAllWindows()
```
在这个示例中,我们使用了 face_recognition 库来检测人脸位置和提取特征编码,然后使用这些编码与已知的人脸进行比较来识别人脸。如果找到匹配的已知人脸,则使用该人脸的标签。最后,我们将标签添加到图像中,并显示结果图像。