简介:本文深入解析基于Pyqt5、MySQL与Opencv的人脸识别智能考勤系统实现,涵盖技术选型、人脸检测、数据库设计、界面开发及优化策略,为企业提供高效、安全的考勤解决方案。
传统考勤方式(如指纹打卡、IC卡)存在代打卡、设备损耗等问题,而基于人脸识别的智能考勤系统通过生物特征识别技术,实现了非接触式、高准确率的考勤管理。本系统以Pyqt5作为前端界面开发框架,MySQL作为数据存储后端,Opencv作为人脸识别核心库,构建了一套完整的考勤解决方案。
系统采用分层架构:
使用Opencv的DNN模块加载预训练的Caffe模型(如opencv_face_detector_uint8.pb),通过以下代码实现人脸框检测:
import cv2def detect_faces(image_path):# 加载模型net = cv2.dnn.readNetFromCaffe("deploy.prototxt", "opencv_face_detector_uint8.pb")# 读取图像并预处理img = cv2.imread(image_path)(h, w) = img.shape[:2]blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))# 前向传播net.setInput(blob)detections = net.forward()# 解析检测结果faces = []for i in range(0, detections.shape[2]):confidence = detections[0, 0, i, 2]if confidence > 0.7: # 置信度阈值box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])(startX, startY, endX, endY) = box.astype("int")faces.append((startX, startY, endX, endY))return faces
采用Opencv的LBPH(Local Binary Patterns Histograms)算法提取人脸特征,通过计算汉明距离实现比对:
recognizer = cv2.face.LBPHFaceRecognizer_create()recognizer.train(images, labels) # images: 人脸图像数组, labels: 对应IDdef recognize_face(image):gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)label, confidence = recognizer.predict(gray)return label if confidence < 50 else -1 # 阈值50
import pymysqldef save_attendance(user_id, status):conn = pymysql.connect(host="localhost", user="root", password="123456", database="attendance")cursor = conn.cursor()sql = "INSERT INTO attendance (user_id, status, time) VALUES (%s, %s, NOW())"cursor.execute(sql, (user_id, status))conn.commit()conn.close()
使用QMainWindow作为主窗口,包含以下控件:
QLabel显示实时视频流。QPushButton触发人脸采集、考勤操作。QTableWidget展示历史考勤数据。
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabelfrom PyQt5.QtCore import QTimerimport cv2import numpy as npclass CameraWidget(QLabel):def __init__(self):super().__init__()self.cap = cv2.VideoCapture(0)self.timer = QTimer()self.timer.timeout.connect(self.update_frame)self.timer.start(30) # 30ms更新一帧def update_frame(self):ret, frame = self.cap.read()if ret:frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)h, w, ch = frame.shapebytes_per_line = ch * wq_img = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)self.setPixmap(QPixmap.fromImage(q_img))
users.user_id和attendance.user_id上创建索引,提升查询速度。
pip install pyqt5 opencv-python pymysql numpy
本系统通过Pyqt5+MySQL+Opencv的组合,实现了高效、安全的人脸识别考勤管理。未来可进一步集成AI算法(如情绪识别),或与HR系统对接,形成完整的员工管理生态。对于开发者而言,掌握此类跨技术栈的开发能力,将显著提升职场竞争力。