python人脸考勤系统代码
时间: 2023-07-23 16:36:05 浏览: 48
以下是一个简单的Python人脸考勤系统代码示例,使用了OpenCV和face_recognition库:
```python
import cv2
import face_recognition
import os
import datetime
# 加载已知人脸图像
known_faces_dir = "known_faces"
known_faces = []
known_names = []
for file in os.listdir(known_faces_dir):
image = face_recognition.load_image_file(os.path.join(known_faces_dir, file))
encoding = face_recognition.face_encodings(image)[0]
known_faces.append(encoding)
known_names.append(file.split(".")[0])
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头帧
ret, frame = cap.read()
# 缩小帧以加快检测速度
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# 将颜色从BGR转换为RGB
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)
# 遍历每个检测到的人脸
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# 比较人脸与已知人脸
matches = face_recognition.compare_faces(known_faces, face_encoding, tolerance=0.5)
name = "Unknown"
if True in matches:
# 找到匹配的人脸
match_index = matches.index(True)
name = known_names[match_index]
# 绘制人脸矩形框和名称
cv2.rectangle(frame, (left*4, top*4), (right*4, bottom*4), (0, 0, 255), 2)
cv2.rectangle(frame, (left*4, bottom*4 - 35), (right*4, bottom*4), (0, 0, 255), cv2.FILLED)
cv2.putText(frame, name, (left*4 + 6, bottom*4 - 6), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1)
# 保存考勤记录
with open("attendance.txt", "a") as f:
f.write(f"{name}, {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
# 显示帧
cv2.imshow('Face Attendance System', frame)
# 按q退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 关闭摄像头和窗口
cap.release()
cv2.destroyAllWindows()
```
注意:这只是一个简单的示例,还有很多需要改进的地方,例如处理异常和错误、优化识别速度等。