Python+Qt人脸识别门禁管理系统

程序示例精选

Python+Qt人脸识别门禁管理系统

如需安装运行环境或远程调试,见文章底部个人QQ名片,由专业技术人员远程协助!

前言

这篇博客针对<<Python+Qt人脸识别门禁管理系统>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。


文章目录

一、所需工具软件

二、使用步骤

        1. 引入库

        2. 代码实现

       3. 运行结果

三、在线协助

一、所需工具软件

1. Python

2. Qt, OpenCV

二、使用步骤

1.引入库

## coding:utf-8
import sys
import os
import csv
import cv2
from untitled import Ui_mainWindow
import record
import name
from dbase import Record2
from PyQt5 import QtWidgets

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QPixmap,QPainter

2. 代码实现

代码如下:

class myWin(QtWidgets.QMainWindow, Ui_mainWindow):

    def __init__(self):
        super(myWin, self).__init__()
        self.setupUi(self)

        self.pushButton_4.clicked.connect(self.onVideo) #
        self.open_flag = False  #
        self.painter = QPainter(self)  #

        self.pushButton.clicked.connect(self.openFileButton)
        self.pushButton_2.clicked.connect(self.open_name_ui)
        self.pushButton_7.clicked.connect(self.train)
        #self.pushButton_6.clicked.connect(self.faceRecog)
        self.pushButton_3.clicked.connect(self.open_second_ui)

        self.pushButton_5.clicked.connect(self.threadRun)
        self.pushButton_6.clicked.connect(self.switch_video)
        self.timer2 = VideoTimer()
        self.timer2.timeSignal.signal[str].connect(self.videoRecog2)

        self.pushButton_8.clicked.connect(self.recogConform)
        self.pushButton.hide()
        self.pushButton_4.hide()


    def threadRun(self):
        # thread1.start()
        if self.pushButton_5.text() == "模型初始化thread":
            threadSetup()
            # thread1.start()
            self.pushButton_5.setText("停止模型thread")

        elif self.pushButton_5.text() == "停止模型thread":
            # stop_thread(thread1)
            # stop_thread(threadT)
            threadStop()
            print("tttt6")
            self.pushButton_5.setText("模型初始化thread")


    # # 退出系统窗口 X 绑定函数事件
    def closeEvent(self, event):
        # print("test")
        self.box = QMessageBox(QMessageBox.Warning, "系统提示信息", "是否退出系统?")
        qyes = self.box.addButton(self.tr("是"), QMessageBox.YesRole)
        qno = self.box.addButton(self.tr("否"), QMessageBox.NoRole)
        self.box.exec_()
        if self.box.clickedButton() == qyes:
            try:
                threadStop()
            except:
                print("abnormal")
            event.accept()
            QtWidgets.QWidget.closeEvent(self, event)
            sys.exit().accept()
        else:
            event.ignore()

    def switch_video(self):
        # self.timer2.start()
        if self.pushButton_6.text() == "开始检测":
            self.timer2.start()
            print("tttt6")
            self.pushButton_6.setText("暂停检测")
        elif self.pushButton_6.text() == "暂停检测":
            self.timer2.stop()
            print("tttt6")
            self.pushButton_6.setText("开始检测")

    def videoRecog2(self):

        # print("im02: ",im02)
        import cv2
        import numpy as np
        count = 0
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        recognizer.read('face_trainer/trainer.yml')
        cascadePath = "haarcascade_frontalface_default.xml"
        faceCascade = cv2.CascadeClassifier(cascadePath)
        font = cv2.FONT_HERSHEY_SIMPLEX
        print("11")



        gray = cv2.cvtColor(im02, cv2.COLOR_BGR2GRAY)
        faces = faceCascade.detectMultiScale(
            gray,
            scaleFactor=1.2,
            minNeighbors=5,

        )

        if len(faces) == 0:
            print("len(faces)", len(faces))

            frame = cv2.cvtColor(im02, cv2.COLOR_BGR2RGB)
            height, width, bytesPerComponent = frame.shape
            bytesPerLine = bytesPerComponent * width

            self.q_image = QtGui.QImage(frame.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888).scaled(self.label.height() * 1.5, self.label.height())
            self.label.setPixmap(QPixmap.fromImage(self.q_image))
            self.update()  # 

        if len(faces) == 1:
            for (x, y, w, h) in faces:
                idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])
                print("confidence", confidence)
                print("idnum", idnum)


                # cv2.putText(img, str(username), (x + 5, y - 5), font, 1, (0, 0, 255), 1)
                confidence2 = round(160 - confidence)
                if confidence2 > 80:
                    cv2.rectangle(im02, (x, y), (x + w, y + h), (0, 255, 0), 3)
                    cv2.putText(im02, str(confidence2) + "%", (x + 5, y + h - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (37, 46, 6), 1)

                if confidence2 <= 80:
                    cv2.rectangle(im02, (x, y), (x + w, y + h), (255, 0, 0), 3)
                    cv2.putText(im02, "unknow", (x + 5, y + h - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (37, 46, 6), 1)

                frame = cv2.cvtColor(im02, cv2.COLOR_BGR2RGB)
                height, width, bytesPerComponent = frame.shape
                bytesPerLine = bytesPerComponent * width

                self.q_image = QtGui.QImage(frame.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) \
                    .scaled(self.label.height() * 1.5, self.label.height())
                self.label.setPixmap(QPixmap.fromImage(self.q_image))
                self.update()  # 

            if confidence2 > 80:
                print("confidence2", confidence2)
                global usernamedb
                global chinese_name
                global idnumberNum


                import dbase
                import sqlite3
                import datetime
                from datetime import datetime
                conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
                curr = conn.cursor()
                curr.execute("select idnumber from name_table")
                # curr.execute('insert into name_table values (null, ?)', [name])
                results = curr.fetchall()
                name_list = []
                for i in results:
                    i = list(i)
                    name_list += i
                print("name_list", name_list)
                print("idnum", idnum)
                usernamedb = name_list[idnum]
                print("usernamedb", usernamedb)

                curr.execute("select chinese_name from name_table")
                results2 = curr.fetchall()
                name_list2 = []
                for i in results2:
                    i = list(i)
                    name_list2 += i
                print(name_list2)
                CHusernamedb = name_list2[idnum]
                print("CHusernamedb", CHusernamedb)
                chinese_name = CHusernamedb
                result = 'Ok'

                curr.execute("select idnumber from name_table")
                results3 = curr.fetchall()
                name_list3 = []
                for i in results3:
                    i = list(i)
                    name_list3 += i
                print(name_list3)
                idnumber = name_list3[idnum]
                print("idnumber", idnumber)
                idnumberNum = idnumber

                # curr.execute('insert into record_table values (null, ?, ?, ?,?,?)',
                #              (usernamedb, datetime.now(), chinese_name, 'Ok', idnumberNum))
                conn.commit()
                conn.rollback()
                curr.close()
                conn.close()

                self.textEdit.setPlainText("姓名" + ' ' + chinese_name + ' ' + "识别成功,门已打开")

                #self.recogConform() #模拟开门暂时不保存识别数据到数据库,以免人没离开摄像头重复保存多的数据到数据库,暂时用界面上识别手动确认保存识别信息到数据库

                # msg_box = QMessageBox(QMessageBox.Warning, '信息', '人脸识别成功')
                # msg_box.exec_()




        # frame = cv2.cvtColor(im02, cv2.COLOR_BGR2RGB)
        # height, width, bytesPerComponent = frame.shape
        # bytesPerLine = bytesPerComponent * width
        #
        # self.q_image = QtGui.QImage(frame.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) \
        #     .scaled(self.label.height() * 0.8, self.label.height() * 0.6)
        # self.label.setPixmap(QPixmap.fromImage(self.q_image))
        # self.update()

    def recogConform(self):
        global usernamedb
        global chinese_name
        global idnumberNum

        import dbase
        import sqlite3
        import datetime
        from datetime import datetime
        conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
        curr = conn.cursor()
        curr.execute('insert into record_table values (null, ?, ?, ?,?,?)',
                     (usernamedb, datetime.now(), chinese_name, 'Ok', idnumberNum))

        conn.commit()
        conn.rollback()
        curr.close()
        conn.close()

        self.textEdit.append("识别保存成功")

        # msg_box = QMessageBox(QMessageBox.Warning, '信息', '识别保存成功')
        # msg_box.exec_()

    def openFileButton(self):
        #imgName, imgType  = QFileDialog.getOpenFileName(self,"打开文件","./","files(*.*)")
        self.cap = cv2.VideoCapture(0)
        self.pushButton_4.clicked.connect(self.onVideo) #
        self.open_flag = True  #
        self.painter = QPainter(self)  #
    def onVideo(self):
        print("self.open_flag: ", self.open_flag)
        if self.open_flag:
            self.pushButton_4.setText('Open')
            print("change1")
        else:
            self.pushButton_4.setText('Close')
            print("change2")
        self.open_flag = bool(1-self.open_flag)
        print("change3")

3. 运行结果

 

三、在线协助:

如需安装运行环境或远程调试,见文章底部个人 QQ 名片,由专业技术人员远程协助!
1)远程安装运行环境,代码调试
2)Qt, C++, Python入门指导
3)界面美化
4)软件制作

博主推荐文章:python人脸识别统计人数qt窗体-CSDN博客

博主推荐文章:Python Yolov5火焰烟雾识别源码分享-CSDN博客

                         Python OpenCV识别行人入口进出人数统计_python识别人数-CSDN博客

个人博客主页:alicema1111的博客_CSDN博客-Python,C++,网页领域博主

博主所有文章点这里:alicema1111的博客_CSDN博客-Python,C++,网页领域博主

  • 0
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
很高兴回答你关于PythonOpenCV人脸识别门禁系统的问题!要实现这样的系统,你需要使用OpenCV库中的人脸识别功能和Python编程语言。 首先,你需要安装OpenCV库。你可以使用以下命令在Python环境中安装它: ``` pip install opencv-python ``` 安装完成后,你可以导入OpenCV库并使用其人脸识别功能。以下是一个简单的示例代码: ```python import cv2 # 加载人脸识别器 face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # 打开摄像头 cap = cv2.VideoCapture(0) while True: # 读取摄像头图像 ret, frame = cap.read() # 将图像转换为灰度图 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 使用人脸识别器检测人脸 faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # 在图像上标记检测到的人脸 for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) # 显示图像 cv2.imshow('Face Recognition', frame) # 按下 'q' 键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放摄像头和关闭窗口 cap.release() cv2.destroyAllWindows() ``` 这段代码使用摄像头读取图像,并通过人脸识别器检测人脸。检测到的人脸会在图像上用绿色矩形标记出来。按下 'q' 键可以退出程序。 你可以根据你的需求进一步扩展这个基本的示例,例如添加身份验证功能、与门禁系统的集成等。 希望这个示例对你有所帮助!如果还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荷塘月色2

您的鼓励将是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值