请写一个python人脸识别代码
时间: 2023-11-04 10:05:45 浏览: 40
好的,以下是一个基于Python的人脸识别代码示例,需要使用OpenCV和face-recognition库:
```python
import cv2
import face_recognition
# 加载已知人脸图片和对应的名字
known_face_encodings = []
known_face_names = []
img_path = "known_faces/"
for filename in os.listdir(img_path):
img = face_recognition.load_image_file(img_path + filename)
face_encoding = face_recognition.face_encodings(img)[0]
known_face_encodings.append(face_encoding)
known_face_names.append(os.path.splitext(filename)[0])
# 打开摄像头
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"
if True in matches:
# 如果有匹配的人脸,则取第一个匹配的人脸对应的名字
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
# 在人脸周围绘制矩形框和名字
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left, bottom + 20), cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255), 1)
# 显示图像
cv2.imshow('Video', frame)
# 按下q键退出程序
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和窗口资源
video_capture.release()
cv2.destroyAllWindows()
```
这段代码通过读取已知人脸的图像并进行编码,然后在摄像头中实时检测人脸并进行识别和绘制矩形框和名字。