用Python写一个人脸识别考勤签到的程序
时间: 2023-05-22 19:05:39 浏览: 195
可以使用Python中的OpenCV库和人脸识别算法来实现人脸识别考勤签到程序。该程序可以通过摄像头捕获学生/员工的照片,检测并识别脸部,将脸部特征保存到数据库中,并在签到时对照数据库中的脸部特征进行身份验证。下面是一个示例代码:
```
import cv2
import numpy as np
import os
def face_recognition(directory):
recognizer = cv2.face.LBPHFaceRecognizer_create() #使用LBPH算法创建人脸识别器
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")#使用Haar级联分类器检测人脸
image_paths = [os.path.join(directory, f) for f in os.listdir(directory)]
faces = []
labels = []
for image_path in image_paths:
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_rects = detector.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
for (x, y, w, h) in face_rects:
faces.append(gray[y:y+h, x:x+w])
labels.append(int(os.path.split(image_path)[1].split(".")[0]))
recognizer.train(faces, np.array(labels)) #训练识别器
return recognizer
def attendence_recognition(recognizer):
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) #使用摄像头获取图像
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_rects = detector.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
for (x, y, w, h) in face_rects:
face = gray[y:y+h, x:x+w]
label, confidence = recognizer.predict(face)
if confidence < 50: # 50是可调整的置信度阈值
cv2.putText(frame, "Identified: " + str(confidence) + "%", (x, y-10), font, 1, (0, 255, 0), 2)
else:
cv2.putText(frame, "Unidentified", (x, y-10), font, 1, (0, 0, 255), 2)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Real-time capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
directory = "att_faces"
recognizer = face_recognition(directory)
attendence_recognition(recognizer)
```
当用户运行程序时,会使用“att_faces”目录下的单独的图像来训练分类器。该程序作为一个实时视频捕捉器运行,并将训练数据与程序捕捉的视频帧中发现的人脸数据库进行比对。如果发现人的脸并且可以在数据库中匹配,程序将显示匹配的姓名,并将该人员标记为“签到成功”;否则,将显示“签到失败”。
阅读全文