Python+QT停车场车牌识别计费管理系统-升级版

news2024/11/22 15:00:44

程序示例精选

Python+QT停车场车牌识别计费管理系统-升级版

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

前言

这篇博客针对<<Python+QT停车场车牌识别计费管理系统-升级版>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。

主要升级内容如下:

此版本优化了通过秒计算的计费精确度,添加了二维码扫码支付功能,以及车位数量,剩余车位,等信息。


文章目录

一、所需工具软件

二、使用步骤

        1. 引入库

        2. 代码实现

        3. 运行结果

三、在线协助

一、所需工具软件

1. Python,Pycharm

2. OpenCV

二、使用步骤

1.引入库

# coding:utf-8
import sys
import os
import csv
import cv2
import numpy as np

from PIL import Image, ImageTk
from tensorflow import keras
from core import locate_and_correct
from Unet import unet_predict
from CNN import cnn_predict

from untitled import Ui_mainWindow
import record

import photoW
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 login import *
from register import *
import time
import datetime
from datetime import datetime
import pandas as pd
import time

2. 代码实现

代码如下:

class myWin(QtWidgets.QMainWindow, Ui_mainWindow):

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


        self.pushButton_5.clicked.connect(self.carPlateRecogIn)

        self.pushButton_9.clicked.connect(self.carPlatePosition)
        self.pushButton_10.clicked.connect(self.manualOpen)
        self.pushButton_11.clicked.connect(self.CostCalculation)
        self.pushButton_3.clicked.connect(self.open_second_ui)

        self.unet = keras.models.load_model('unet.h5')
        self.cnn = keras.models.load_model('cnn.h5')
        print('正在启动中,请稍等...')
        cnn_predict(self.cnn, [np.zeros((80, 240, 3))])
        print("已启动,开始识别!")

        self.currentNumberInit()
        self.vipNumberInit()
        self.pushButton.clicked.connect(self.totalQttyModify)
        self.pushButton_2.clicked.connect(self.appointmentModify)
        self.pushButton_4.clicked.connect(self.feeModify)
        self.pushButton_12.clicked.connect(self.vipAdd)
        self.pushButton_12.clicked.connect(self.vipAdd)
        self.pushButton_13.clicked.connect(self.clearpN)


        self.pushButton_7.clicked.connect(self.threadRun)
        #self.pushButton_3.clicked.connect(self.threadRun)
        self.pushButton_2.clicked.connect(self.closeEvent)

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

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

        elif self.pushButton_7.text()=="停止模型thread":
            #stop_thread(thread1)
            #stop_thread(threadT)
            threadStop()
            print("tttt6")
            self.pushButton_7.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_8.text() == "开始检测":
            self.timer2.start()
            print("tttt6")
            self.pushButton_8.setText("暂停检测")
        elif self.pushButton_8.text() == "暂停检测":
            self.timer2.stop()
            print("tttt6")
            self.pushButton_8.setText("开始检测")



    def videoRecog2(self):


        # print("im02: ",im02)

        try:
            # 视频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() * 0.8, self.label.height() * 0.6)
            self.label.setPixmap(QPixmap.fromImage(self.q_image))
            #self.label.setScaledContents(True)
            self.update()
            # 视频1结束***********************************************

            # 视频2开始***********************************************
            cv2.imwrite("tempV.jpg",im02)
            self.img_src_path="tempV.jpg"
            print("test")
            img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1)  # 从中文路径读取时用
            print("test")
            h, w = img_src.shape[0], img_src.shape[1]
            print("aa")
            if h * w <= 240 * 80 and 2 <= w / h <= 5:  # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可
                lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3]  # 直接resize为(240,80)
                img_src_copy, Lic_img = img_src, [lic]
            else:  # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别
                img_src, img_mask = unet_predict(self.unet, self.img_src_path)
                img_src_copy, Lic_img = locate_and_correct(img_src, img_mask)  # 利用core.py中的locate_and_correct函数进行车牌定位和矫正
                print("aa")

            Lic_pred = cnn_predict(self.cnn, Lic_img)  # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果)
            if Lic_pred:
                #img = Image.fromarray(img_src_copy[:, :, ::-1])  # img_src_copy[:, :, ::-1]将BGR转为RGB
                # self.img_Tk = ImageTk.PhotoImage(img)
                # self.can_src.delete('all')  # 显示前,先清空画板
                #self.can_src.create_image(258, 258, image=self.img_Tk,anchor='center')  # img_src_copy上绘制出了定位的车牌轮廓,将其显示在画板上

                # 显示相片到label_2
                img = cv2.imread("tempV.jpg")
                frame = cv2.cvtColor(img, 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()


                for i, lic_pred in enumerate(Lic_pred):
                    if i == 0:
                        print("i: ", i)
                        print("lic_pred[1]: ",lic_pred[1])
                        # self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
                    elif i == 1:
                        print("i: ", i)
                        # self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
                    elif i == 2:
                        print("i: ", i)
                        # self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
                    plateNumber=lic_pred[1]
                    print("lic_pred[1]2: ", lic_pred[1])

                    if len(plateNumber)>5:
                        if not os.path.exists("pN.jpg"):
                            cv2.imwrite("pN.jpg",im02)
                            msg_box = QMessageBox(QMessageBox.Warning, '信息', '检测到有车辆到达门口')
                            msg_box.exec_()
        except:
            print("mistake")




    #软件启动后显示数据库中当前剩余车位数量,与总车位数量到界面
    def currentNumberInit(self):
        print("aa")

        if os.path.exists('pN.jpg'):
            os.remove("pN.jpg")

        #得到recordinfo.db中在场车辆总数
        conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
        curr = conn.cursor()
        curr.execute('select name from record_plate')
        result2 = curr.fetchall()
        row = len(result2)
        print("row:", row)
        inSiteNumber = row

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


        conn = sqlite3.connect(databaseName, check_same_thread=False)
        curr = conn.cursor()
        curr.execute("select * from parking_spaces_number")
        # curr.execute("select record_date from {}".format(tableName) )
        results = curr.fetchall()
        print("results",results[0])
        name_list = []
        for i in results:
            i = list(i)
            print(i)
            print(i[1])
            print(i[2])
            print(i[3])
            # print(i[4])
            print(i[5])
            self.lineEdit_2.setText(i[1])
            self.lineEdit_3.setText(str(int(i[1])-int(i[3])-inSiteNumber))
            self.lineEdit_4.setText(i[3])
            self.lineEdit_5.setText(str(inSiteNumber))
            self.lineEdit.setText(i[5])
        conn.commit()
        curr.close()
        conn.close()

    def currentNumberInit2(self):
        print("aa")

        #得到recordinfo.db中在场车辆总数
        conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
        curr = conn.cursor()
        curr.execute('select name from record_plate')
        result2 = curr.fetchall()
        row = len(result2)
        print("row:", row)
        inSiteNumber = row

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


        conn = sqlite3.connect(databaseName, check_same_thread=False)
        curr = conn.cursor()
        curr.execute("select * from parking_spaces_number")
        # curr.execute("select record_date from {}".format(tableName) )
        results = curr.fetchall()
        print("results",results[0])
        name_list = []
        for i in results:
            i = list(i)
            print(i)
            print(i[1])
            print(i[2])
            print(i[3])
            # print(i[4])
            print(i[5])
            self.lineEdit_2.setText(i[1])
            self.lineEdit_3.setText(str(int(i[1])-int(i[3])-inSiteNumber))
            self.lineEdit_4.setText(i[3])
            self.lineEdit_5.setText(str(inSiteNumber))
            self.lineEdit.setText(i[5])
        conn.commit()
        curr.close()
        conn.close()

    #软件启动后显示数据库中vip车辆到界面
    def vipNumberInit(self):
        print("aa")
        try:
            #得到recordinfo.db中在场车辆总数
            conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
            curr = conn.cursor()
            curr.execute('select name from vip')
            result2 = curr.fetchall()
            row = len(result2)
            print("row:", row)
            vipNumber = row

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

            conn = sqlite3.connect(databaseName, check_same_thread=False)
            curr = conn.cursor()
            curr.execute("select * from vip")
            # curr.execute("select record_date from {}".format(tableName) )
            results = curr.fetchall()
            print("results",results[0])
            name_list = []
            for i in results:
                i = list(i)
                print(i)
                print(i[1])
                self.textEdit_4.setPlainText(i[1])

            conn.commit()
            curr.close()
            conn.close()
        except:
            print("mistake")

    #清空pN
    def clearpN(self):
        if os.path.exists('pN.jpg'):
            os.remove("pN.jpg")

    #vip添加
    def vipAdd(self):
        TEXT=self.lineEdit_6.text()

        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 * from vip")
        # curr.execute("select record_date from {}".format(tableName) )
        results = curr.fetchall()

        # 数组包含某个文字判断
        name_list = []
        for i in results:
            i = list(i)
            print(i)
            name_list += i
            # name_list =','.join(i)
            print("name_list2", name_list)
            print("name_list type", type(name_list))

        if TEXT not in name_list:
            print("yes")

            # curr.execute("select name from record_table")
            print("saa1")
            curr.execute('insert into vip values (null, ?, ?, ?, ?, ?)',(TEXT, datetime.now().strftime("%Y%m%d %H:%M:%S"), ' ', ' ', ' '))

            print("saa2")
            conn.commit()
            conn.rollback()
            curr.close()
            conn.close()

        self.vipNumberInit()


    # 界面修改总车位数量写入数据库
    def totalQttyModify(self):
        totalQtty = self.lineEdit_2.text() #总车位数读取
        print("totalQtty",totalQtty)

        conn = sqlite3.connect(databaseName, check_same_thread=False)
        curr = conn.cursor()
        curr.execute('update parking_spaces_number set total_parking_spaces_qtty = "' + str(int(totalQtty)) + '"')
        print("enDone")

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

        msg_box = QMessageBox(QMessageBox.Warning, '信息', '修改成功')
        msg_box.exec_()

    #界面预约车位数量写入数据库
    def appointmentModify(self):
        appointmentQtty = self.lineEdit_4.text()
        print("appointmentQtty", appointmentQtty)

        conn = sqlite3.connect(databaseName, check_same_thread=False)
        curr = conn.cursor()
        curr.execute('update parking_spaces_number set appointment_qtty = "' + str(int(appointmentQtty)) + '"')

        print("enDone")

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

        self.currentNumberInit()

        msg_box = QMessageBox(QMessageBox.Warning, '信息', '预约成功')
        msg_box.exec_()

    #界面预约车位数量写入数据库
    def feeModify(self):
        feeT = self.lineEdit.text()
        print("feeT", feeT)

        conn = sqlite3.connect(databaseName, check_same_thread=False)
        curr = conn.cursor()
        curr.execute('update parking_spaces_number set fee_num = "' + feeT + '"')

        print("enDone")

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

        msg_box = QMessageBox(QMessageBox.Warning, '信息', '每小时计费修改成功')
        msg_box.exec_()


    def displayPlate(self):
        # 显示相片到label_2
        imgName, imgType  = QFileDialog.getOpenFileName(self,"打开文件","./","files(*.*)")
        img = cv2.imread(imgName)
        #img = cv2.imread("test_img/aa.jpg")
        cv2.imwrite('temp.jpg', img)
        height, width, pixels = img.shape
        if width > (self.label.width()):
            rheight = (self.label.width() * height) * width
            rwidth = self.label.width()
        elif height > (self.label.height()):
            rwidth = (self.label.height() * width) / height
            rheight = self.label.height()
        elif ((self.label.height()) - height) < ((self.label.width()) - width):
            rwidth = (self.label.height() * width) / height
            rheight = self.label.height()
        else:
            rheight = height
            rwidth = width
        frame = cv2.resize(img, (int(rwidth), int(rheight)))
        img2 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # opencv读取的bgr格式图片转换成rgb格式
        _image = QtGui.QImage(img2[:], img2.shape[1], img2.shape[0], img2.shape[1] * 3, QtGui.QImage.Format_RGB888)
        jpg_out = QtGui.QPixmap(_image).scaled(rwidth, rheight)  # 设置图片大小
        self.label.setPixmap(jpg_out)  # 设置图片显示

    def carPlatePosition(self):
        self.label_7.clear()
        print("carPlateRecog start")
        self.img_src_path="pN.jpg"
        img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1)  # 从中文路径读取时用
        h, w = img_src.shape[0], img_src.shape[1]
        print("aa")
        if h * w <= 240 * 80 and 2 <= w / h <= 5:  # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可
            lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3]  # 直接resize为(240,80)
            img_src_copy, Lic_img = img_src, [lic]
        else:  # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别
            img_src, img_mask = unet_predict(self.unet, self.img_src_path)
            img_src_copy, Lic_img = locate_and_correct(img_src, img_mask)  # 利用core.py中的locate_and_correct函数进行车牌定位和矫正
            print("aa")


    def carPlateRecogOut(self):
        print("carPlateRecog start")
        # self.label_7.clear()
        self.img_src_path="pN.jpg"
        img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1)  # 从中文路径读取时用
        h, w = img_src.shape[0], img_src.shape[1]
        print("aa")
        if h * w <= 240 * 80 and 2 <= w / h <= 5:  # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可
            lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3]  # 直接resize为(240,80)
            img_src_copy, Lic_img = img_src, [lic]
        else:  # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别
            img_src, img_mask = unet_predict(self.unet, self.img_src_path)
            img_src_copy, Lic_img = locate_and_correct(img_src, img_mask)  # 利用core.py中的locate_and_correct函数进行车牌定位和矫正
            print("aa")

        Lic_pred = cnn_predict(self.cnn, Lic_img)  # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果)
        if Lic_pred:
            # 显示相片到label_2
            img = cv2.imread("pN.jpg")
            self.label_7.setPixmap(QPixmap(""))
            height, width, pixels = img.shape
            if width > (self.label_7.width()):
                rheight = (self.label_7.width() * height) * width
                rwidth = self.label_7.width()
            elif height > (self.label_7.height()):
                rwidth = (self.label_7.height() * width) / height
                rheight = self.label_7.height()
            elif ((self.label_7.height()) - height) < ((self.label_7.width()) - width):
                rwidth = (self.label_7.height() * width) / height
                rheight = self.label_7.height()
            else:
                rheight = height
                rwidth = width
            frame = cv2.resize(img, (int(rwidth), int(rheight)))
            img2 = cv2.cvtColor(img_src_copy, cv2.COLOR_BGR2RGB)  # opencv读取的bgr格式图片转换成rgb格式
            _image = QtGui.QImage(img2[:], img2.shape[1], img2.shape[0], img2.shape[1] * 3, QtGui.QImage.Format_RGB888)
            jpg_out = QtGui.QPixmap(_image).scaled(rwidth, rheight)  # 设置图片大小
            self.label_7.setPixmap(jpg_out)  # 设置图片显示

            for i, lic_pred in enumerate(Lic_pred):
                if i == 0:
                    print("i: ", i)
                    print("lic_pred[1]: ",lic_pred[1])
                    self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
                elif i == 1:
                    print("i: ", i)
                    self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
                elif i == 2:
                    print("i: ", i)
                    self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
                global plateNumber
                plateNumber=lic_pred[1]
                print("lic_pred[1]2: ", lic_pred[1])

                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 name from record_plate")
                # curr.execute('insert into name_table values (null, ?)', [name])
                results = curr.fetchall()
                for i in results:
                    i = list(i)
                    print("i", i)
                    if i == [plateNumber]:
                        print("outTime: ", datetime.now())
                        curr.execute('update record_plate set record_time_out = "' + str(datetime.now().strftime("%Y%m%d %H:%M:%S")
) + '" where name="' + plateNumber + '"')
                        print("outTime2: ", datetime.now())
                        conn.commit()
                        conn.rollback()

                    if os.path.exists("platetemp.txt"):
                        os.remove("platetemp.txt")
                    if not os.path.exists("platetemp.txt"):
                        file2 = open('platetemp.txt', 'w')
                        file2.write(plateNumber)
                        file2.close()


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


                #得到当前数据库中在场车辆数量,更新出的车辆数量到数据库
                conn = sqlite3.connect(databaseName, check_same_thread=False)
                curr = conn.cursor()
                curr.execute("select * from parking_spaces_number")
                # curr.execute("select record_date from {}".format(tableName) )
                results = curr.fetchall()
                print("results", results[0])
                name_list = []
                for i in results:
                    i = list(i)
                    print(i)
                    print(i[4])
                    curr.execute('update parking_spaces_number set enter_qtty = "' + str(int(i[4])-1) + '"')

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



        else:  # Lic_pred为空说明未能识别
            print("无车牌发现")

    def CostCalculation(self):

        try:
            self.carPlateRecogOut()


            global plateNumber
            print("plateNumber",plateNumber)


            #判断是否是vip车辆
            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 * from vip")
            # curr.execute("select record_date from {}".format(tableName) )
            results = curr.fetchall()

            # 数组包含某个文字判断
            name_list = []
            for i in results:
                i = list(i)
                print(i)
                name_list += i
                # name_list =','.join(i)
                print("name_list2", name_list)
                print("name_list type", type(name_list))

            if plateNumber in name_list:
                print("in vip namelist")
                msg_box = QMessageBox(QMessageBox.Warning, '信息', 'vip车辆,门已打开,请出门')
                msg_box.exec_()

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

            elif plateNumber not in name_list:
                print("not in vip namelist")

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

                self.carPlateRecogOut()
                self.currentNumberInit2()

                print("停车费计算")
                import dbase
                import sqlite3
                import datetime

                print("")
                conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
                curr = conn.cursor()
                curr.execute('select record_time from record_plate where name ="' + plateNumber + '"')
                intime = curr.fetchall()
                print("intime:", intime)
                curr.execute('select record_time_out from record_plate where name ="' + plateNumber + '"')
                outtime = curr.fetchall()
                print("outtime:", outtime)
                for i in intime: i = list(i); intime = ','.join(i)
                for i in outtime: i = list(i); outtime = ','.join(i)
                print("intime2:", intime)
                print("outtime3:", outtime)


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


                #Fee = 0.001  # 每秒钟0.001元
                Fee = float(self.lineEdit.text())
                print("Fee",Fee)

                date_time_obj_1 = datetime.datetime.strptime(intime, '%Y%m%d %H:%M:%S')
                date_time_obj_2 = datetime.datetime.strptime(outtime, '%Y%m%d %H:%M:%S')
                dt_time1 = pd.to_datetime(date_time_obj_1)  # 转换日期时间到标准格式
                dt_time2 = pd.to_datetime(date_time_obj_2)  # 转换日期时间到标准格式
                dateTimeInterval = dt_time2 - dt_time1  #得到日期时间差
                print("dateTimeInterval", dateTimeInterval)

                print("date_time_obj_1", date_time_obj_1)
                print("date_time_obj_2", date_time_obj_2)
                print("dt_time1", dt_time1)
                print("dt_time2", dt_time2)

                sec1 = time.mktime(dt_time1.timetuple())  # 转换为sec
                sec2 = time.mktime(dt_time2.timetuple())  # 转换为sec
                print("sec1", sec1)
                print("sec2", sec2)

                timeInterval = sec2 - sec1
                print("timeInterval", timeInterval)

                hourTimeInterval = round((timeInterval / 60 / 60),2)  #妙转换小时
                print("hourTimeInterval", hourTimeInterval)

                Cost = timeInterval * Fee
                print("Cost", Cost)


                #self.textEdit_2.setPlainText("时长:" + str(timeInterval))
                self.textEdit_2.setPlainText("时长:"+str(dateTimeInterval)+"小时   费用:"+str(Cost)+"元")
                global costT
                costT=str(Cost)
                global timeIntervalT
                timeIntervalT=timeInterval

                #更新出场车牌停车费用到数据库
                import dbase
                import sqlite3
                import datetime
                from datetime import datetime
                conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
                curr = conn.cursor()
                curr.execute('update record_plate set fee = "' + str(Cost) + '" where name="' + str(plateNumber) + '"')
                conn.commit()
                conn.rollback()
                curr.close()
                conn.close()

                #打开二维码
                self.open_third_ui()

                #二维码打开付费后,更新数据库付费状态
                import dbase
                import sqlite3
                import datetime
                from datetime import datetime
                conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
                curr = conn.cursor()
                curr.execute('update record_plate set fee_result= "' + ('Paid') + '" where name="' + str(plateNumber) + '"')
                conn.commit()
                conn.rollback()
                curr.close()
                conn.close()

                msg_box = QMessageBox(QMessageBox.Warning, '信息', '门已打开,请出门')
                msg_box.exec_()

                if os.path.exists('pN.jpg'):
                    os.remove("pN.jpg")

                #车出去后删除这个车的数据库记录
                # import dbase
                # import sqlite3
                # conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
                # cur = conn.cursor()
                # curr.execute('delete from record_plate where name="' + plateNumber + '"')  # 删除已经出去的车辆信息
                # conn.commit()
                # conn.rollback()
                # cur.close()
                # conn.close()
            else:
                print("incorrect plate")
        except:
            print("cost def mistake")

    def manualOpen(self):
        msg_box = QMessageBox(QMessageBox.Warning, '信息', '门已打开')
        msg_box.exec_()



    def open_second_ui(self):
        self.second_ui = myRecord()
        self.second_ui.show()


    def open_third_ui(self):
        self.third_ui = photoWin()
        self.third_ui.show()


#记录显示****************************************************************************//
class myRecord(QtWidgets.QWidget, record.Ui_Frame):

    def __init__(self):
        super(myRecord, self).__init__()
        self.setupUi(self)
        self.resize(900, 500)



        self.pushButton_6.clicked.connect(self.ExportAllData)

    def checkDataView(self):
        try:
            import dbase
            import sqlite3
            conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
            cur = conn.cursor()
            cur.execute("select * from record_plate")
            rows = cur.fetchall()
            row = len(rows)  # 取得记录个数,用于设置表格的行数
            print("row",row)
            vol = len(rows[0])  # 取得字段数,用于设置表格的列数
            print("vol", vol)
            cur.close()
            conn.close()

            self.tableWidget.setRowCount(row)
            self.tableWidget.setColumnCount(vol)


            for i in range(row):
                for j in range(vol):
                    temp_data=rows[i][j]  #临时记录,不能直接插入表格
                    data=QTableWidgetItem(str(temp_data)) #转换后可插入表格
                    if j != row:
                        data.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)  #居中显示
                    self.tableWidget.setItem(i,j,data)
                    self.tableWidget.verticalHeader().setVisible(False)  #竖直序列号不可见
                    # 表头字体加粗
                    font = self.tableWidget.horizontalHeader().font()
                    font.setBold(True)
                    self.tableWidget.horizontalHeader().setFont(font)
        except (ValueError, ArithmeticError):
            print(" ")
        except:
            print(" ")

    def ExportAllData(self):
        import dbase
        import sqlite3

        conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
        cur = conn.cursor()
        cur.execute("select * from record_plate")
        rows = cur.fetchall()
        row = len(rows)  # 取得记录个数,用于设置表格的行数
        print("row",row)
        vol = len(rows[0])  # 取得字段数,用于设置表格的列数
        print("vol", vol)
        cur.close()
        conn.close()
        print("导出记录")

        if (os.path.isfile("ExportAllData.csv")):
            os.remove("ExportAllData.csv")

        with open('ExportAllData.csv', 'a') as file3:
            file3.write("ID, 英文名, 日期时间, 中文名, 打卡记录, 编号;")
            file3.close()


        for i in range(row):
            for j in range(vol):
                temp_data=rows[i][j]  #临时记录,不能直接插入表格
                data2 = str(temp_data)
                print("temp_data: ",temp_data)

                with open('ExportAllData.csv', 'a') as file2:
                    if j==5:
                        file2.write(data2 + ", " + "\n")
                        file2.close()
                    else:
                        file2.write(data2)
                        file2.write(", ")
                        file2.close()
        msg_box = QMessageBox(QMessageBox.Warning, '信息', '保存成功')
        msg_box.exec_()

        file5 = open("ExportAllData.csv", 'rt')
        contents = file5.read()  # 读取txt
        data = contents.replace(";", ";\n") #找到特殊字符进行替换

        fin = open('ExportAllData2.csv', "wt") #打开新的txt,上面替换的数据写到这里!
        fin.write(data)  #将处理好的结果再写进前面的txt内。
        fin.close()


    def deleteClicked(self):

        button = self.sender()
        try:
            if button:
                row = self.tableWidget.indexAt(button.pos()).row()
                #row2 = self.tableWidget.selectedItems()[0].row()  # 获取选中文本所在的行
                #column = self.tableWidget.selectedItems()[0].column()  # 获取选中文本所在的列
                contents = self.tableWidget.selectedItems()[0].text()  # 获取选中文本内容
                print("contents",contents)
                self.tableWidget.removeRow(row)


                import dbase
                import sqlite3
                conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
                cur = conn.cursor()

                print("contents", contents)
                cur.execute('delete from record_plate where id = '+contents)
                conn.commit()
                conn.rollback()
                cur.close()
                conn.close()

                self.checkDataView()
                msg_box = QMessageBox(QMessageBox.Warning, '信息', '删除成功')
                msg_box.exec_()
        except (ValueError, ArithmeticError):
            self.checkDataView()
            msg_box = QMessageBox(QMessageBox.Warning, '信息', '请鼠标点击选择需要删除的序号,或未知异常')
            msg_box.exec_()
        except:
            print(" ")


class photoWin(QtWidgets.QWidget, photoW.Ui_Frame):

    def __init__(self):
        super(photoWin, self).__init__()
        self.setupUi(self)
        self.resize(400, 500)

        self.frame.setStyleSheet(open('style/style_frame.css').read())
        self.textEdit.setPlainText("时长:" + str(timeIntervalT) + "   费用:" + costT)




#封装pyqtSignal信号
class Communicate(QObject):
    signal=pyqtSignal(str)

class VideoTimer(QThread):
    def __init__(self):
        QThread.__init__(self)
        self.timeSignal=Communicate()
        self.mutex = QMutex()
        print("tttt5")
    def run(self):
        with QMutexLocker(self.mutex):
            self.stopped = False
        while True:
            if self.stopped == True:
                return
            #发送信号给视频要求更新,emit发送信号
            print("ttttrun")
            self.timeSignal.signal.emit("1")
            #时间延迟
            time.sleep(0.8)
    def stop(self):
        with QMutexLocker(self.mutex):
            self.stopped = True

if __name__=="__main__":
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app=QtWidgets.QApplication(sys.argv)

    # 设置登录窗口
    login_ui = LoginDialog()
    register_ui = RegisterDialog()

    # 校验是否验证通过
    while login_ui.exec_() == QDialog.Accepted:
        if login_ui.isRisterButtonClicked==True:
            login_ui.registerdlg=RegisterDialog()
            if login_ui.registerdlg.exec_()==QDialog.Accepted:
                if login_ui.registerdlg.isLoginButtonClicked ==True:
                    continue
                else:
                    Widget = myWin()
                    Widget.showMaximized();
                    Widget.show()
            sys.exit(app.exec_())

        Widget=myWin()
        Widget.showMaximized();
        Widget.show()
        sys.exit(app.exec_())

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++,网页领域博主

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/631120.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

RabbitMQ入门案例之Direct模式

前言 RabbitMQ的Direct模式是一种可以根据指定路由key&#xff0c;Exchang将消息发送到具有该路由key下的Queue下进行存储。也就类似于将数据写进指定数据库表中。这个路由Key可以类比为SQL语句中的&#xff1a;where routeKey … 官方文档地址&#xff1a;https://www.rabbi…

DragGAN部署全流程

写在前面 看了DragGAN 官方&#xff0c;并没有找到软件&#xff0c;或者程序&#xff0c;github上也没有程序&#xff0c;如果大佬们能找到&#xff0c;可以评论通知下。不过也有技术大佬已经提前开发出来了&#xff0c;我们抢先体验下。 这里本地部署了 DragGAN。经历了报错&…

【LeetCode】HOT 100(5)

题单介绍&#xff1a; 精选 100 道力扣&#xff08;LeetCode&#xff09;上最热门的题目&#xff0c;适合初识算法与数据结构的新手和想要在短时间内高效提升的人&#xff0c;熟练掌握这 100 道题&#xff0c;你就已经具备了在代码世界通行的基本能力。 目录 题单介绍&#…

CTFShow-WEB入门篇--命令执行详细Wp

WEB入门篇--命令执行详细Wp 命令执行&#xff1a;Web29&#xff1a;Web30&#xff1a;Web31&#xff1a;web32&#xff1a;web33&#xff1a;web34&#xff1a;web35&#xff1a;web36&#xff1a;web37&#xff1a;web38&#xff1a; CTFShow 平台&#xff1a;https://ctf.sho…

【Kubernetes资源篇】Service四层代理入门实战详解

文章目录 一、Service四层代理概念、原理1、Service四层代理概念2、Service工作原理3、Service原理解读4、Service四种类型 二、Service四层代理三种类型案例1、创建ClusterIP类型Service2、创建NodePort类型Service3、创建ExternalName类型Service 三、拓展1、Service域名解析…

Nvidia AGX Orin MAX9296 GMSL 载板设计要点

因为项目的需求&#xff0c;我们设计了Nvidia AGX Orin MAX9296 GMSL 载板(绿板&#xff09;&#xff0c;项目完成&#xff0c;总结以下。需要参考原理图的&#xff0c;可以微我&#xff0c;索取。共同交流。 Jetson AGX Orin建立在NVIDIA Ampere架构之上&#xff0c;全新Jets…

AUTOSAR-BSW EEPROM模块解读

参考文件 AUTOSAR_SWS_EEPROMDriver&#xff08;4.3.0&#xff09; AUTOSAR_SWS_BSWGeneral&#xff08;4.3.0&#xff09; EEPROM Module 文件结构 如上图所示 EEPROM Module应该主要包含Eep.c,Eep.h,Eep_Cfg.c,Eep_MemMmap.h,Eep_Lcfg.c和Eep_PBcfg.c文件&#xff0c;如果使…

图像分类模型嵌入flask中开发PythonWeb项目

图像分类模型嵌入flask中开发PythonWeb项目 图像分类是一种常见的计算机视觉任务&#xff0c;它的目的是将输入的图像分配到预定义的类别中&#xff0c;如猫、狗、花等。图像分类模型是一种基于深度学习的模型&#xff0c;它可以利用大量的图像数据来学习图像的特征和类别之间…

华为OD机试之找终点

找终点 题目描述 给定一个正整数数组&#xff0c;设为nums&#xff0c;最大为100个成员&#xff0c;求从第一个成员开始&#xff0c;正好走到数组最后一个成员&#xff0c;所使用的最少步骤数。 要求&#xff1a; 第一步必须从第一元素开始&#xff0c;且1<第一步的步长<…

100天精通Golang(基础入门篇)——第3天:Go语言的执行原理及常用命令、编码规范和常用工具

&#x1f337; 博主 libin9iOak带您 Go to Golang Language.✨ &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &#x1f30a; 《I…

java进阶—线程间通信(通俗易懂等待唤醒机制)

今天我们来看一看&#xff0c;线程之间的通信&#xff0c;也就是我们所说的等待唤醒机制 先来看三个关键方法: wait(); 当线程执行这个方法&#xff0c;它就会进入阻塞状态&#xff0c;并且释放同步监视器 notify(); 英文翻译 唤醒&#xff0c;就是说会唤醒wait的线程&…

【 图像分割 2022 ECCV】CP2

【 图像分割 2022 ECCV】CP2 论文题目&#xff1a;CP2: Copy-Paste Contrastive Pretraining for Semantic Segmentation 中文题目&#xff1a;CP2:语义分割的复制粘贴对比预训练 论文链接&#xff1a;https://arxiv.org/abs/2203.11709 论文代码&#xff1a;https://github.co…

Python3+Selenium框架搭建

Webdriver概述 Webdriver (Selenium2&#xff09;是一种用于Web应用程序的自动测试工具&#xff0c; Thoughtworks公司一个强大的基于浏览器的开源自动化测试工具&#xff0c;通常用来编写web应用的自动化测试。 Selenium 是一个用于Web应用程序测试的工具。 Selenium测试直…

异常数据检测 | Python实现支持向量机(SVM)的异常数据检测

文章目录 文章概述模型描述源码分享学习小结参考资料文章概述 SVM通常应用于监督式学习,但OneClassSVM算法可用于将异常检测这样的无监督式学习,它学习一个用于异常检测的决策函数其主要功能将新数据分类为与训练集相似的正常值或不相似的异常值。 模型描述 OneClassSVM的思…

Flink 1.17.0集群搭建

集群角色分配 HostnameIPRolehadoop01192.168.126.132 JobManager TaskManager hadoop02192.168.126.133TaskManagerhadoop03192.168.126.134TaskManager 下载flink安装包 https://archive.apache.org/dist/flink/flink-1.17.0/ 上传至hadoop01并解压&#xff1a; 修改conf/…

微软MFC技术简明介绍

我是荔园微风&#xff0c;作为一名在IT界整整25年的老兵&#xff0c;今天来看一下微软MFC技术简明介绍 Visual C 与 MFC 微软公司于1992年上半年推出了C/C 7.0 产品时初次向世人介绍了MFC 1.0&#xff0c;这个产品包含了20,000行C原始代码&#xff0c;60个以上的Windows相关类…

【Leetcode】贪心问题合集 | 摆动序列、K次取反最大和、加油站、分发糖果、柠檬水找零、根据身高重建队列、单调递增的数字

贪心问题感觉还是挺不好想的&#xff0c;因为每一题有每一题的策略&#xff0c;感觉只能尽量做过的记住了。 376 摆动序列 注意&#xff1a;是序列&#xff0c;而不是数组。 求最大摆动序列的长度&#xff0c;即求谷 / 峰的个数。 若走势不为一条直线。 起始count 2&…

LED显示屏静电防护指南

LED显示屏是一种电子设备&#xff0c;对静电敏感。静电放电可能会对LED显示屏的电子元件造成损坏&#xff0c;因此需要采取静电防护措施。以下是LED显示屏静电防护的一些建议和指南&#xff1a; 环境控制&#xff1a;在LED显示屏周围创建适宜的环境条件。控制湿度和温度&#x…

Yolov5(tag v7.0)网络结构解读,以yolov5s为例

最近yolov5用的多&#xff0c;发现确实好用&#xff0c;于是较深入学了一下。下面按照训练的流程梳理一下网络的结构&#xff0c;同时也是自己记一下便于后面查阅。 同时&#xff0c;我也查了一些关于yolov5网络结构介绍的资料&#xff0c;发现大多是v5.0&#xff0c;少数v6.0的…

Linux驱动IO篇——阻塞/非阻塞IO

文章目录 非阻塞IO阻塞IO等待队列等待队列变体 非阻塞IO 在应用程序中&#xff0c;使用open函数打开一个/dev目录下的一个设备文件时&#xff0c;默认是以阻塞的方式打开。 所谓阻塞&#xff0c;就是当我们请求的资源不可用时&#xff08;资源被占用&#xff0c;没有数据到达等…