人脸识别校园门禁python代码
时间: 2023-08-20 08:06:20 浏览: 63
以下是一个简单的使用Python进行人脸识别的校园门禁代码示例:
```python
import cv2
import numpy as np
import face_recognition
# 加载已知人脸图像和标签
known_face_encodings = []
known_face_labels = []
# 添加已知人脸图像和标签
known_face_encodings.append(face_recognition.face_encodings(known_image)[0])
known_face_labels.append("张三")
# 初始化摄像头
video_capture = cv2.VideoCapture(0)
while True:
# 读取摄像头帧
ret, frame = video_capture.read()
# 转换为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_labels[first_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()
```
请注意,此代码仅为示例,你需要根据你的实际需求进行适当的修改。此代码使用OpenCV和face_recognition库,你需要先安装这些库才能运行此代码。同时,你还需要提供已知人脸图像,并将其编码添加到`known_face_encodings`列表中,并为每个已知人脸提供相应的标签。