Linux小程序开发日记-5
哈喽,大家好,好久不见,咱今天,又开始我的小程序开发啦。
然后这几天呢,我开始记录开发这个小程序的视频啦,欢迎大家来康康。
视频链接
linux桌面小程序开发日记-2
最后一篇博客地址:https://blog.csdn.net/Liuchengzhizhi/article/details/123692365
B站视频:https://www.bilibili.com/video/BV1rZ4y1B7t8?share_source=copy_web
源码:https://gitee.com/wx_b915676bb6/yolo-pyqt.git
记得上一次咱们可以将识别的数据显示在旁边的表格中,但是呢还有很多内容没有加上去。所以这一次,咱把这个GUI没有完善的内容咱把他们完善好
今天的任务:
- 将加载UI界面的,单独放在一个python文件内
- 对识别的内容,进行一个排序,能够统计标签的个数
- 对这些识别的标签,进行表格的匹配,显示价格
- 进行一个计价
第一步:重新优化UI代码
这里呢,我单独的将ui代码,放在了我的food_ui文件里面
代码如下:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Ui_MainWindow(object):
'''程序界面布局'''
def set_ui(self):
self.__layout_main = QtWidgets.QGridLayout()
self.__layout_fun_button1 = QtWidgets.QHBoxLayout()
self.__layout_fun_button2 = QtWidgets.QHBoxLayout()
self.__layout_data_show = QtWidgets.QVBoxLayout()
self.__layout_list_show = QtWidgets.QVBoxLayout()
self.button_confirm = QtWidgets.QPushButton('确认')
self.button_settle_accounts = QtWidgets.QPushButton('结账')
self.list_show = QtWidgets.QTableWidget(6,3)
self.label_account = QtWidgets.QLabel("总价:")
'''set butten size '''
self.button_confirm.setMinimumHeight(50)
self.button_settle_accounts.setMinimumHeight(50)
self.label_account.setMinimumHeight(50)
'''设置标签的格式'''
font = QtGui.QFont()
font.setPixelSize(18)
self.label_account.setFont(font)
'''设置表格'''
self.list_show.setHorizontalHeaderLabels(["名称","数量","单价"])
self.list_show.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.list_show.setEditTriggers(QAbstractItemView.EditTrigger(False))
'''信息显示'''
self.label_show_camera = QtWidgets.QLabel()
self.label_show_camera.setFixedSize(641,481)
'''把按键加入到按键布局中'''
self.__layout_fun_button1.addWidget(self.button_confirm)
self.__layout_fun_button2.addWidget(self.button_settle_accounts)
'''把表格加入到表格布局中'''
self.__layout_list_show.addWidget(self.list_show)
self.__layout_list_show.addWidget(self.label_account)
'''把某些控件加入到总布局中'''
self.__layout_main.addLayout(self.__layout_list_show,0,0)
self.__layout_main.addLayout(self.__layout_fun_button1,1,1)
self.__layout_main.addLayout(self.__layout_fun_button2,1,0)
self.__layout_main.addWidget(self.label_show_camera,0,1)
return self.__layout_main
第二步 读取csv文件
我把他放在了price_utils.py里面
代码如下
'''
存放价钱的读函数
'''
import csv
from pip import main
def get_price_info():
price_info = {}
with open('priceInfo.csv', 'r') as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader:
price_info[row[0]] = row[1]
return price_info
第三步 修改我的主文件
修改主文件,将我想要的内容显示在表格上,同时进行一个乘法计算
主文件:
关键代码如下
self.ui = Ui_MainWindow()
self.price_info = price_utils.get_price_info()
layout_main = self.ui.set_ui()
def set_labels(self ,labels ):
self.ui.list_show.clearContents()
labels = pd.value_counts(labels)
total_price = 0
if len(labels.index.values) != 0:
for i in range(len(labels.index.values)):
label_num = str(labels.values[i])
self.ui.list_show.setItem(i,0,QTableWidgetItem(labels.index.values[i]))
self.ui.list_show.setItem(i,1,QTableWidgetItem(label_num))
if labels.index.values[i] in self.price_info :
label_price = str(self.price_info[labels.index.values[i]])
self.ui.list_show.setItem(i,2,QTableWidgetItem(label_price))
total_price = total_price + (float(label_price) * int(label_num))
else :
self.ui.list_show.setItem(i,2,QTableWidgetItem("99"))
total_price = total_price + (float(99) * int(label_num))
account = "总价: "+ str(total_price)
self.ui.label_account.setText(account)
所有代码如下
from cProfile import label
import sys
from unittest import result
import cv2
import time
import argparse
import random
import torch
import numpy as np
import pandas as pd
import torch.backends.cudnn as cudnn
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from utils.torch_utils import select_device
from models.experimental import attempt_load
from utils.general import check_img_size, non_max_suppression, scale_coords
from utils.datasets import letterbox
from utils.plots import plot_one_box2
from utils.torch_utils import select_device, load_classifier, time_synchronized
from ui.food_ui import Ui_MainWindow
from utils import price_utils
class Ui_Logic_Window(QtWidgets.QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.timer_video = QtCore.QTimer()
self.cap = cv2.VideoCapture()
self.ui = Ui_MainWindow()
self.price_info = price_utils.get_price_info()
layout_main = self.ui.set_ui()
'''将总布局作为参数传入下面函数'''
self.setLayout(layout_main)
self.slot_init()
self.num_stop = 1
self.output_folder = 'output/'
self.vid_writer = None
self.openfile_name_model = "./weights/yolov5s.pt"
self.model_init()
self.button_camera_open()
'''初始化所有槽函数'''
def slot_init(self):
self.ui.button_confirm.clicked.connect(self.button_video_stop)
self.timer_video.timeout.connect(self.show_video_frame)
def model_init(self):
parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default='weights/yolov5s6.pt', help='model.pt path(s)')
parser.add_argument('--source', type=str, default='data/images', help='source')
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--view-img', action='store_true', help='display results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--update', action='store_true', help='update all models')
parser.add_argument('--project', default='runs/detect', help='save results to project/name')
parser.add_argument('--name', default='exp', help='save results to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
self.opt = parser.parse_args()
print(self.opt)
source, weights, view_img, save_txt, imgsz = self.opt.source, self.opt.weights, self.opt.view_img, self.opt.save_txt, self.opt.img_size
if self.openfile_name_model:
weights = self.openfile_name_model
print("Using button choose model")
self.device = select_device(self.opt.device)
self.half = self.device.type != 'cpu'
cudnn.benchmark = True
self.model = attempt_load(weights, map_location=self.device)
stride = int(self.model.stride.max())
self.imgsz = check_img_size(imgsz, s=stride)
if self.half:
self.model.half()
classify = False
if classify:
modelc = load_classifier(name='resnet101', n=2)
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=self.device)['model']).to(self.device).eval()
self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
self.colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]
print("model initial done")
QtWidgets.QMessageBox.information(self, u"Notice", u"模型加载完成", buttons=QtWidgets.QMessageBox.Ok,
defaultButton=QtWidgets.QMessageBox.Ok)
def detect(self, name_list, img):
'''
:param name_list: 文件名列表
:param img: 待检测图片
:return: info_show:检测输出的文字信息
'''
showimg = img
with torch.no_grad():
img = letterbox(img, new_shape=self.opt.img_size)[0]
img = img[:, :, ::-1].transpose(2, 0, 1)
img = np.ascontiguousarray(img)
img = torch.from_numpy(img).to(self.device)
img = img.half() if self.half else img.float()
img /= 255.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
pred = self.model(img, augment=self.opt.augment)[0]
pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=self.opt.classes,
agnostic=self.opt.agnostic_nms)
info_show = ""
label_names = ""
for i, det in enumerate(pred):
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], showimg.shape).round()
for *xyxy, conf, cls in reversed(det):
label = '%s %.2f' % (self.names[int(cls)], conf)
name_list.append(self.names[int(cls)])
single_info = plot_one_box2(xyxy, showimg, label=label, color=self.colors[int(cls)], line_thickness=2)
info_show = info_show + single_info + "\n"
label_names = label_names+","+self.names[int(cls)]
label_names = label_names.split(",")
label_names = [i for i in label_names if(len(str(i))!=0)]
return info_show , label_names
def set_video_name_and_path(self):
now = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
fps = self.cap.get(cv2.CAP_PROP_FPS)
w = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
save_path = self.output_folder + 'video_output/' + now + '.mp4'
return fps, w, h, save_path
def button_camera_open(self):
print("Open camera to detect")
camera_num = 0
self.cap = cv2.VideoCapture(camera_num)
bool_open =self.cap.open(camera_num)
if not bool_open:
QtWidgets.QMessageBox.warning(self, u"Warning", u"打开摄像头失败", buttons=QtWidgets.QMessageBox.Ok,
defaultButton=QtWidgets.QMessageBox.Ok)
else:
fps, w, h, save_path = self.set_video_name_and_path()
self.vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
self.timer_video.start(30)
def show_video_frame(self):
name_list = []
flag, img = self.cap.read()
if img is not None:
info_show , label_names = self.detect(name_list, img)
self.vid_writer.write(img)
print(info_show)
self.set_labels(label_names)
show = cv2.resize(img, (640, 480))
self.result = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(self.result.data, self.result.shape[1], self.result.shape[0],
QtGui.QImage.Format_RGB888)
self.ui.label_show_camera.setPixmap(QtGui.QPixmap.fromImage(showImage))
else:
self.timer_video.stop()
self.cap.release()
self.vid_writer.release()
self.ui.label.clear()
self.button_settle_accounts.setDisabled(False)
def button_video_stop(self):
self.timer_video.blockSignals(False)
if self.timer_video.isActive() == True and self.num_stop%2 == 1:
self.ui.button_confirm.setText(u'重新确认')
self.num_stop = self.num_stop + 1
self.timer_video.blockSignals(True)
self.ui.button_settle_accounts.setDisabled(False)
else:
self.num_stop = self.num_stop + 1
self.ui.button_confirm.setText(u'确认')
self.ui.button_settle_accounts.setDisabled(False)
def set_labels(self ,labels ):
self.ui.list_show.clearContents()
labels = pd.value_counts(labels)
total_price = 0
if len(labels.index.values) != 0:
for i in range(len(labels.index.values)):
label_num = str(labels.values[i])
self.ui.list_show.setItem(i,0,QTableWidgetItem(labels.index.values[i]))
self.ui.list_show.setItem(i,1,QTableWidgetItem(label_num))
if labels.index.values[i] in self.price_info :
label_price = str(self.price_info[labels.index.values[i]])
self.ui.list_show.setItem(i,2,QTableWidgetItem(label_price))
total_price = total_price + (float(label_price) * int(label_num))
else :
self.ui.list_show.setItem(i,2,QTableWidgetItem("99"))
total_price = total_price + (float(99) * int(label_num))
account = "总价: "+ str(total_price)
self.ui.label_account.setText(account)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
current_ui =Ui_Logic_Window()
current_ui.show()
sys.exit(app.exec_())
最后
附上一张咱运行后的截图
最后的最后,谢谢叼着骨头的猫,都是在他的项目上,咱修改出来的代码
叼着骨头的猫yyds!!!
|