基于Python的人脸识别课堂系统(毕设)——附录上

本文章承接《基于Python的人脸识别课堂考勤系统(毕设)》,填坑上篇文章遗留的代码部分。因为项目分的模块比较多,再加上本人能力有限,所以代码过于臃肿还存在许多优化的地方。同样本篇文章也仅适用于小白,零基础人群。

PS:每个文件之中代码都已经区分开来,可以对照左侧目录部分实现快速预览!

       由于代码过于多我这里分成上,下两个部分来发布吧!

一、主文件

import os
import sys
import random
import pymysql
import cv2
import numpy as np
from math import pi
from matplotlib import pyplot as plt
from PIL import Image
from decimal import Decimal
from cv2 import CascadeClassifier,face
from PyQt5.QtWidgets import QLineEdit, QMessageBox
from ui_1jinru import Ui_MainWindow as jinru_Ui
from ui_2SingIn import Ui_MainWindow as singin_ui
from ui_3register import Ui_MainWindow as registerone_ui
from ui_4regsiter import Ui_MainWindow as registertwo_ui
from ui_5main import Ui_MainWindow as main_ui
from ui_6punch_the_clock import Ui_MainWindow as punch_ui
from ui_7collection import Ui_MainWindow as collection_ui
from ui_8feedback import Ui_MainWindow as feedback_ui
from ui_9random import Ui_MainWindow as random_ui
from ui_10_useguide import Ui_MainWindow as use_ui
from ui_11financialmedia import Ui_MainWindow as financialmedia_ui
from ui_12financialmedia import Ui_MainWindow as financialmediatwo_ui
from ui_13datawarehousing import Ui_MainWindow as data_ui
from ui_14accountwarehousing import Ui_MainWindow as caccount_ui
from ui_15dataanalysis import Ui_MainWindow as dataanalysis_ui
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QTimer,QDateTime
id_face = []
checklist = []
check_tlist = []
# 进入窗口
class jinruWindow(QtWidgets.QMainWindow,  jinru_Ui):
    # 登录页面跳转信号
    switch_singin = QtCore.pyqtSignal()
    def __init__(self):
        super(jinruWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("睿课人脸识别课堂考勤系统v2.0")
        self.setWindowIcon(QIcon('picture/Logo_2Max.png'))
        self.staraButton.clicked.connect(self.gosingin)
    def gosingin(self):
        self.switch_singin.emit()

# 登录窗口
class singinWindow(QtWidgets.QMainWindow,  singin_ui):
    switch_main = QtCore.pyqtSignal()  # 主界面跳转信号
    switch_registerone = QtCore.pyqtSignal()  # 注册页面_1跳转信号
    def __init__(self):
        super(singinWindow, self).__init__()
        self.setupUi(self)
        self.initUI()
        self.setWindowTitle("睿课人脸识别课堂考勤系统v2.0")
        self.setWindowIcon(QIcon('picture/Logo_2Max.png'))
        self.regButton.clicked.connect(self.goregisterone)

    def initUI(self):
        self.usernametext.setFocus()
        self.usernametext.setPlaceholderText("请输入账户名")  # 提示信息
        self.posswordtext.setPlaceholderText("请输入密码")
        self.posswordtext.setEchoMode(QLineEdit.Password)  # 密码隐藏
        self.loginButton.clicked.connect(self.Check)

    def Check(self):
        user = str(self.usernametext.text())
        pwd = str(self.posswordtext.text())
        db = pymysql.connect(host='localhost', port=3306, user='root', password="369852147", database="facerecognition")
        cursor = db.cursor()
        sql = 'SELECT t_user,t_pwd FROM teacher'
        cursor.execute(sql)
        data = cursor.fetchall()
        cursor.close()
        db.close()
        i=0
        if user == "" or pwd == "":
              QMessageBox.information(self, "睿课", "Tips:账户与密钥不能为空,请仔细核对!")
              return
        elif user != "" and pwd != "":
               while i < int(len(data)):
                   if str(data[i][0]) == user and str(data[i][1]) == pwd:
                       QMessageBox.information(self, "睿课", "账户与密钥匹配成功,即将跳转至主页面!")
                       self.switch_main.emit()
                       return
                   i += 1
               QMessageBox.information(self, "睿课", "error:账户与密钥不匹配,请仔细核对!")
    def goregisterone(self):
        self.switch_registerone.emit()

# 注册窗口_1
class registeroneWindow(QtWidgets.QMainWindow,  registerone_ui):
    switch_registertwo = QtCore.pyqtSignal()  # 注册页面_2跳转信号
    switch_singin = QtCore.pyqtSignal()
    def __init__(self):
        super(registeroneWindow, self).__init__()
        self.setupUi(self)
        self.initUI()
        self.setWindowTitle("睿课人脸识别课堂考勤系统v2.0")
        self.setWindowIcon(QIcon('picture/Logo_2Max.png'))
        self.propose_pushButton.clicked.connect(self.gosingin)
        self.propose_pushButton.clicked.connect(self.close)

    def initUI(self):
        self.number_lineEdit.setFocus()  # 鼠标焦点
        self.number_lineEdit.setPlaceholderText("请设置账户")  # 提示信息
        self.password_lineEdit.setPlaceholderText("密码大于六位(含)")
        self.password_lineEdit.setEchoMode(QLineEdit.Password)#密码隐藏
        self.next_pushButton.clicked.connect(self.emit_next_Button)  # 下一页按钮,检测账户与密码是否合规

    def emit_next_Button (self):
        config = {
            "host": "localhost",
            "user": "root",
            "password": "369852147",
            "database": "facerecognition"
        }
        db = pymysql.connect(**config)
        cursor = db.cursor()
        sql = 'SELECT t_user,t_pwd FROM teacher'
        cursor.execute(sql)
        data = cursor.fetchall()
        t_user = str(self.number_lineEdit.text())
        t_pwd = str(self.password_lineEdit.text())
        t_id = ''
        t_name = ''
        t_sex = ''
        t_school = ''
        t_college = ''
        t_protect = '2'
        i=0
        if t_user == "" or t_pwd == "":
            QMessageBox.information(self, "睿课", "白小泽检查后发现账户或者密钥为空,补填空项!")
        else:
            while i < int(len(data)):
                if str(data[i][0]) == t_user:
                    QMessageBox.information(self, "睿课", "白小泽查阅后发现这个账户名已经被注册了,账户名已被使用!")
                    return
                else:
                    sql = "insert into teacher values('{}', '{}','{}','{}','{}','{}','{}','{}')".format(t_user, t_pwd, \
                     t_id, t_name, t_sex,t_school, t_college, t_protect)
                    cursor.execute(sql)
                    db.commit()  # 提交数据
                    cursor.close()
                    db.close()
                    QMessageBox.information(self, "睿课", "白小泽提示您账号密码设置完成,请完善个人信息!")
                    self.switch_registertwo.emit()
                    return

    def gosingin(self):
        self.switch_singin.emit()

# 注册窗口_2
class registertwoWindow(QtWidgets.QMainWindow,  registertwo_ui):
    switch_singin = QtCore.pyqtSignal()
    def __init__(self):
        super(registertwoWindow, self).__init__()
        self.setupUi(self)
        self.initUI()
        self.setWindowTitle("睿课人脸识别课堂考勤系统v2.0")
        self.setWindowIcon(QIcon('picture/Logo_2Max.png'))
        self.register_pushButton.clicked.connect(self.gosingin)
        self.propose_pushButton.clicked.connect(self.close)

    def initUI(self):
        self.id_lineEdit.setFocus()  # 鼠标焦点
        self.user_lineEdit.setPlaceholderText("重复账户")  # 提示信息
        self.pwd_lineEdit.setPlaceholderText("重复密钥")
        self.pwd_lineEdit.setEchoMode(QLineEdit.Password)  # 密码隐藏

    def gosingin(self):
        db = pymysql.connect(host='localhost', port=3306, user='root', password="369852147", database="facerecognition")
        cursor = db.cursor()
        sql1 = "SELECT * FROM teacher WHERE t_protect=2"
        cursor.execute(sql1)
        data = cursor.fetchall()
        print(data)
        t_user = str(self.user_lineEdit.text())
        t_pwd = str(self.pwd_lineEdit.text())
        t_id = str(self.id_lineEdit.text())
        t_name = str(self.name_lineEdit.text())
        t_sex = str(self.sex_comboBox.currentText())
        t_school = str(self.university_lineEdit.text())
        t_college = str(self.college_lineEdit.text())
        t_protect = '0'
        i = 0
        if t_id == "":
            QMessageBox.information(self, "error", "教职工ID不可以为空,此项为必填信息!")
        elif t_name == "" or t_sex == "" or t_school == "" or t_college == "":
            QMessageBox.information(self, "error", "个人信息表单中有空项,请仔细核对,补填信息!")
        elif t_user == "" or t_pwd == "":
              QMessageBox.information(self, "睿课", "Tips:账户与密钥不能为空,请重新输入!")
              return
        else:
            while i<int(len(data)):
                print("1")
                if str(data[i][0]) == t_user and str(data[i][1]) == t_pwd:
                    sql2 = "DELETE FROM teacher WHERE t_protect=2"
                    cursor.execute(sql2)
                    sql = "insert into teacher values('{}', '{}','{}','{}','{}','{}','{}','{}')".format(data[0][0],\
                                                        data[0][1],t_id, t_name,t_sex,t_school,t_college, t_protect)
                    cursor.execute(sql)
                    db.commit()  # 提交数据
                    cursor.close()
                    db.close()
                    QMessageBox.information(self, "睿课", "注册完成,个人信息已经写入数据库保存!")
                    self.switch_singin.emit()
                    self.close()
                    return
                else:
                    QMessageBox.information(self, "睿课", "error:校验失败,没有找到您输入的账户与密钥!")
                    return

# 主窗口
class mainWindow(QtWidgets.QMainWindow,  main_ui):
    switch_punch = QtCore.pyqtSignal()  # 考勤页面跳转信号
    switch_collection = QtCore.pyqtSignal()  # 信息采集页面跳转信号
    switch_feedback = QtCore.pyqtSignal()  # 意见反馈页面跳转信号
    switch_random = QtCore.pyqtSignal()  # 随机抽检页面跳转信号
    switch_use = QtCore.pyqtSignal()  # 使用指南页面跳转信号
    switch_financialmedia = QtCore.pyqtSignal()  # 融媒体_1页面跳转信号
    switch_financialmediatwo = QtCore.pyqtSignal()  # 融媒体_2页面跳转信号
    switch_datawarehousing = QtCore.pyqtSignal()  # 数据仓储页面跳转信号
    switch_accountwarehousing = QtCore.pyqtSignal()  # 账户仓储页面跳转信号
    switch_dataanalysis = QtCore.pyqtSignal()  # 数据分析页面跳转信号
    def __init__(self):
        super(mainWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("睿课人脸识别课堂考勤系统v2.0")
        self.setWindowIcon(QIcon('picture/Logo_2Max.png'))
        self.pushButton_1.clicked.connect(self.gopunch)
        self.pushButton_2.clicked.connect(self.gocollection)
        self.pushButton_5.clicked.connect(self.gofeedback)
        self.pushButton_6.clicked.connect(self.close)
        self.pushButton_10.clicked.connect(self.gorandom)
        self.pushButton_4.clicked.connect(self.gouse)
        self.pushButton_8.clicked.connect(self.gofinancialmedia)
        self.pushButton_9.clicked.connect(self.gofinancialmediatwo)
        self.pushButton.clicked.connect(self.godatawarehousing)
        self.pushButton_7.clicked.connect(self.goaccountwarehousing)
        self.pushButton_3.clicked.connect(self.godataanalysis)

    def gopunch(self):
        self.switch_punch.emit()
    def gocollection(self):
        self.switch_collection.emit()
    def gofeedback(self):
        self.switch_feedback.emit()
    def gorandom(self):
        self.switch_random.emit()
    def gouse(self):
        self.switch_use.emit()
    def gofinancialmedia(self):
        self.switch_financialmedia.emit()
    def gofinancialmediatwo(self):
        self.switch_financialmediatwo.emit()
    def godatawarehousing(self):
        self.switch_datawarehousing.emit()
    def goaccountwarehousing(self):
        self.switch_accountwarehousing.emit()
    def godataanalysis(self):
        self.switch_dataanalysis.emit()
# 考勤窗口
class punchWindow(QtWidgets.QMainWindow,  punch_ui):
    switch_homemain = QtCore.pyqtSignal()  # 回主页面跳转信号
    recogizer = cv2.face.LBPHFaceRecognizer_create()
    recogizer.read('D:/Face Recognition/pythonProject/Trainingmodel/train.yml')

    def __init__(self):
        super(punchWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("睿课人脸识别课堂考勤系统v2.0")
        self.setWindowIcon(QIcon('picture/Logo_2Max.png'))
        self.statusShowTime()
        self.homeButton.clicked.connect(self.gohomemain)
        self.homeButton.clicked.connect(self.close)
        self.videoButton.clicked.connect(self.Openattendance)
        self.videoButton.clicked.connect(self.datastatistics)
        self.rootButton.clicked.connect(self.rootstate)
        self.exportButton.clicked.connect(self.expordata)

    def expordata(self):
        QMessageBox.information(self, "睿课", "Tips:白小泽正在努力开发中,暂时不支持数据导出功能哦~~~")


    def rootstate(self):
        db = pymysql.connect(host='localhost', port=3306, user='root', password="369852147", database="facerecognition")
        cursor = db.cursor()
        reply = QMessageBox.question(self,
                        "睿课",
                    "重置后所有的学生的状态将变更成未出勤状态,是否修改?",
        QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            sql = "update  punch set state = '0'"
            cursor.execute(sql)
            sql1 = "update  record set record=record-1"
            cursor.execute(sql1)
            db.commit()
            cursor.close()
            db.close()
            QMessageBox.information(self, "睿课", "Tips:白小泽已经将所有学生的考勤状态变更为0,重置成功!")

    def datastatistics(self):
        face = list()
        for s in id_face:
            if s not in face:
                face.append(s)
        db = pymysql.connect(host='localhost', port=3306, user='root', password="369852147", database="facerecognition")
        cursor = db.cursor()
        sql3 = "UPDATE punch SET state='0' "
        sql4 = "UPDATE record SET record=record+1"
        cursor.execute(sql3)
        cursor.execute(sql4)
        db.commit()
        sql = 'SELECT id FROM punch'
        cursor.execute(sql)
        data = cursor.fetchall()
        sql1 = 'SELECT count(id) FROM punch'
        cursor.execute(sql1)
        sum = cursor.fetchall()
        self.sumlabel.setText(str(sum[0][0])+'人')
        i = 0
        num = 0
        print(data)
        while i < int(len(data)):
            j = 0
            while j < int(len(face)):
               if str(data[i][0])==str(face[j]):
                   print(face[j])
                   sql5 = "UPDATE punch SET state='1' WHERE id="+face[j]
                   cursor.execute(sql5)
                   sql6 = "UPDATE student SET attendance=attendance+1 WHERE id="+face[j]
                   cursor.execute(sql6)
                   db.commit()
                   num += 1
               j += 1
            i += 1
        self.comelabel.setText(str(num) + '人')
        self.nolabel.setText(str((sum[0][0])-num) + '人')
        self.latelabel.setText("----")
        cursor.close()
        db.close()
        QMessageBox.information(self, "睿课", "考勤已经结束,出勤信息已经汇总完成!")

    def Openattendance(self):
        cap = cv2.VideoCapture(0)
        while True:
            flag, frame = cap.read()
            self = frame
            if not flag:
                 break
            if ord(' ') == cv2.waitKey(10):
                break
            recogizer = cv2.face.LBPHFaceRecognizer_create()
            recogizer.read('D:/Face Recognition/pythonProject/Trainingmodel/train.yml')
            path = 'D:/Face Recognition/pythonProject/FaceDatabase/'
            names = []
            imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
            for imagePath in imagePaths:
                name = str(os.path.split(imagePath)[1].split('.', 2)[1])
                names.append(name)
            gray = cv2.cvtColor(self, cv2.COLOR_BGR2GRAY)  # 转换为灰度
            face_detector = cv2.CascadeClassifier(
                'D:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
            face = face_detector.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (300, 300))
            for x, y, w, h in face:
                cv2.rectangle(self, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
                cv2.circle(self, center=(x + w // 2, y + h // 2), radius=w // 2, color=(0, 255, 0), thickness=1)
                # 人脸识别
                ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
                if confidence > 80:
                    cv2.putText(self, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
                else:
                    cv2.putText(self, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
                    identity = str(names[ids - 1])
                    id_face.append(identity)
            cv2.imshow('In attendance', self)
        cap.release()
        cv2.destroyAllWindows()

    def statusShowTime(self):
        self.Timer = QTimer()  # 自定义QTimer类
        self.Timer.start(1000)  # 每1s运行一次
        self.Timer.timeout.connect(self.updateTime)  # 与updateTime函数连接

    def updateTime(self):
        #获取系统时间,设置显示样式,将获取数据传送给控件
        time=QDateTime.currentDateTime()
        timeplay=time.toString('MM-dd hh:mm:ss dddd')
        self.timelabel.setText(timeplay)

    def gohomemain(self):
        self.switch_homemain.emit()

# 信息采集窗口
class collectionWindow(QtWidgets.QMainWindow,  collection_ui):
    switch_homemain = QtCore.pyqtSignal()  # 回主页面跳转信号
    def __init__(self):
        super(collectionWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("睿课人脸识别课堂考勤系统v2.0")
        self.setWindowIcon(QIcon('picture/Logo_2Max.png'))
        self.collectionButton.clicked.connect(self.collection)
        self.okButton.clicked.connect(self.ok)
        self.noButton.clicked.connect(self.no)
        self.homeButton.clicked.connect(self.gohomemain)
        self.homeButton_2.clicked.connect(self. Ttainingmodel)
        self.homeButton.clicked.connect(self.close)

    def collection(self):
        id = str(self.sidlineEdit.text())
        db = pymysql.connect(host='loc
  • 6
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值