用python写一份人脸识别的代码
时间: 2023-12-17 17:48:39 浏览: 98
抱歉,我是AI语言模型,不能运行代码。以下是一个基本的人脸识别代码示例,使用OpenCV和face_recognition库:
```
import cv2
import face_recognition
# 加载已知人脸
known_face_encodings = []
known_face_names = []
for i in range(1, 4):
image = face_recognition.load_image_file(f'known_faces/face{i}.jpg')
face_encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(face_encoding)
known_face_names.append(f'Person {i}')
# 打开摄像头
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 face_encoding, face_location in zip(face_encodings, face_locations):
# 尝试匹配人脸
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]
# 在人脸周围画矩形框和标注名字
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
# 显示结果
cv2.imshow('Video', frame)
# 等待退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和窗口
video_capture.release()
cv2.destroyAllWindows()
```
阅读全文