QT部署YOLOV5

这篇具有很好参考价值的文章主要介绍了QT部署YOLOV5。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


前言

  这篇文章主要用来记录用pyqt5搭建YOLOV5的检测平台,代码是在yoloV5官方代码上加了个qt模块,目前可以支持GPU/CPU下pt/onnx推理

一、准备工作

1、代码下载

git clone https://github.com/ultralytics/yolov5.git

2、环境安装

根据代码中的requirements.txt进行环境搭建,前提是你已有Python环境

pip install -r requirements.txt

这里需要注意的是,pyqt5需要配置下环境,参考连接为:安装pyqt5,步骤如下:

2.1、安装PyQt5

pip install PyQt5

2.2、安装Qt Designer图形界面开发工具

pip install PyQt5-tools

安装完成后,会在当前环境目录下生成如下文件
QT部署YOLOV5

2.3、pycharm配置

QT部署YOLOV5
QT部署YOLOV5
先配置Qt Designer
QT部署YOLOV5
参数如下:
Name:Qt Designer。方便记忆。实际可以任意取值。

Program:designer.exe程序绝对路径。根据实际安装路径填写,参考路径为安装的xxxx/Lib/sit-packages/qt5_applications\Qt\bin\designer.exe(其中xxxx为虚拟环境目录下)。
Working directory: $ProjectFileDir$。固定取值。

配置PyUIC,该工具是用于将Qt Designer工具开发完成的.ui文件转化为.py文件。配置打开路径同Qt Designer。参数配置说明:
Name:PyUIC。方便记忆。实际可以任意取值。
Program:python.exe程序绝对路径。根据实际安装路径填写。
Parameters:-m PyQt5.uic.pyuic $FileName$ -o $FileNameWithoutExtension$.py。固定取值。
Working directory: $FileDir$。固定取值。

3、模型准备

根据readme.md文件中的地址选择对应的模型下载,如图:

QT部署YOLOV5

本文直接以yolov5s.pt进行示范

二、界面展示

1.界面大致如下

QT部署YOLOV5

代码如下(示例):

class Ui_Form(QtWidgets.QWidget):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1130, 730)
        self.stride=64
        #检测结果展示区
        self.label2 = QtWidgets.QLabel(Form)
        self.label2.setGeometry(QtCore.QRect(650, 410, 300, 300))
        self.label2.setAlignment(QtCore.Qt.AlignCenter)
        self.label2.setStyleSheet("border: 1px solid black;")
        self.label2.setObjectName("label2")

        #图片或视频路径选择
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(50, 310, 160, 30))
        self.pushButton.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton.setChecked(False)  # 设置开始时的状态为未选中
        self.pushButton.clicked.connect(lambda :self.select_file())
        self.pushButton.setObjectName("pushButton")  #图片选择按钮

        #模式选择
        self.comboBox = QtWidgets.QComboBox(Form)
        self.comboBox.setGeometry(QtCore.QRect(50, 260, 160, 30))
        self.comboBox.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.comboBox.setPlaceholderText("")
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.currentIndexChanged.connect(lambda :self.select_mode())

        #开始检测按钮
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(190, 610, 100, 70))
        self.pushButton_2.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setChecked(False)
        self.pushButton_2.clicked.connect(lambda :self.vim_show())

        self.pushButton_3 = QtWidgets.QPushButton(Form)
        self.pushButton_3.setGeometry(QtCore.QRect(50, 210, 160, 30))
        self.pushButton_3.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.setChecked(False) # 设置开始时的状态为未选中
        self.pushButton_3.clicked.connect(lambda :self.select_modelfile())

        self.pushButton_7 = QtWidgets.QPushButton(Form)
        self.pushButton_7.setGeometry(QtCore.QRect(50, 550, 160, 30))
        self.pushButton_7.setStyleSheet("font: 15pt \"宋体\";\n"
                                        "border:1px solid black;\n"
                                        "background-color:#e1e1e1;")
        self.pushButton_7.setObjectName("pushButton_7")

        self.lineEdit_2=QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(230, 550, 220, 30))
        self.lineEdit_2.setStyleSheet("border: 1px solid black;")
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.label1=QtWidgets.QLabel(Form)
        self.label1.setGeometry(QtCore.QRect(650, 100, 300, 300))
        self.label2.setAlignment(QtCore.Qt.AlignCenter)
        self.label1.setStyleSheet("border: 1px solid black;")
        self.label1.setObjectName("label1")

        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(600, 100, 40, 300))
        self.textEdit.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.textEdit.setStyleSheet("border: 1px solid black;\n"
"font: 15pt \"宋体\";")

        self.textEdit.setObjectName("textEdit")

        self.textEdit_2 = QtWidgets.QTextEdit(Form)
        self.textEdit_2.setGeometry(QtCore.QRect(600, 410, 40, 300))
        self.textEdit_2.setStyleSheet("border: 1px solid black;\n"
"font: 15pt \"宋体\";")
        self.textEdit_2.setAlignment(QtCore.Qt.AlignHCenter)
        self.textEdit_2.setObjectName("textEdit_2")

        self.tableWidget = QtWidgets.QTableWidget(Form)
        self.tableWidget.setGeometry(QtCore.QRect(230, 370, 221, 170))
        self.tableWidget.setStyleSheet("font: 15pt \"宋体\";\n"
"")
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(1)
        self.tableWidget.setRowCount(4)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(100)
        self.tableWidget.horizontalHeader().setMinimumSectionSize(100)
        self.tableWidget.verticalHeader().setDefaultSectionSize(30)

        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setGeometry(QtCore.QRect(230, 210, 220, 30))
        self.lineEdit_3.setStyleSheet("border: 1px solid black;")
        self.lineEdit_3.setObjectName("lineEdit_3")

        self.lineEdit_4 = QtWidgets.QLineEdit(Form)
        self.lineEdit_4.setGeometry(QtCore.QRect(230, 260, 220, 30))
        self.lineEdit_4.setStyleSheet("border: 1px solid black;")
        self.lineEdit_4.setObjectName("lineEdit_4")

        self.widget_3 = QtWidgets.QWidget(Form)
        self.widget_3.setGeometry(QtCore.QRect(20, 30, 460, 690))
        self.widget_3.setStyleSheet("border : 1px solid black;")
        self.widget_3.setObjectName("widget_3")

        self.lineEdit_5 = QtWidgets.QLineEdit(self.widget_3)
        self.lineEdit_5.setGeometry(QtCore.QRect(90, 20, 261, 51))
        self.lineEdit_5.setStyleSheet("font: 16pt \"宋体\";")
        self.lineEdit_5.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit_5.setObjectName("lineEdit_5")

        self.lineEdit_7 = QtWidgets.QLineEdit(self.widget_3)
        self.lineEdit_7.setGeometry(QtCore.QRect(210, 280, 220, 30))
        self.lineEdit_7.setStyleSheet("border: 1px solid black;")
        self.lineEdit_7.setObjectName("lineEdit_7")

        self.pushButton_4 = QtWidgets.QPushButton(self.widget_3)
        self.pushButton_4.setGeometry(QtCore.QRect(30, 410, 160, 61))
        self.pushButton_4.setStyleSheet("font: 15pt \"宋体\";\n"
"background-color:#e1e1e1;")
        self.pushButton_4.setObjectName("pushButton_4")

        #参数确认按钮
        self.pushButton_5 = QtWidgets.QPushButton(Form)
        self.pushButton_5.setGeometry(QtCore.QRect(50, 610, 100, 70))
        self.pushButton_5.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_5.setChecked(False)
        self.pushButton_5.clicked.connect(lambda: self.param_show())

        #结束检测按钮
        self.pushButton_6 = QtWidgets.QPushButton(Form)
        self.pushButton_6.setGeometry(QtCore.QRect(330, 610, 100, 70))
        self.pushButton_6.setStyleSheet("font: 15pt \"宋体\";\n"
                                        "border:1px solid black;\n"
                                        "background-color:#e1e1e1;")
        self.pushButton_6.setObjectName("pushButton_6")
        self.pushButton_6.setChecked(False)
        self.pushButton_6.clicked.connect(lambda: self.end_detect())




        self.lineEdit_8 = QtWidgets.QLineEdit(self.widget_3)
        self.lineEdit_8.setGeometry(QtCore.QRect(210, 120, 220, 30))
        self.lineEdit_8.setStyleSheet("border: 1px solid black;")
        self.lineEdit_8.setObjectName("lineEdit_8")

        self.comboBox_2 = QtWidgets.QComboBox(self.widget_3)
        self.comboBox_2.setGeometry(QtCore.QRect(30, 120, 160, 30))
        self.comboBox_2.setStyleSheet("font: 15pt \"宋体\";\n"
"background-color:#e1e1e1;")
        self.comboBox_2.setPlaceholderText("")
        self.comboBox_2.setObjectName("comboBox_2")
        self.comboBox_2.currentIndexChanged.connect(lambda : self.select_device())
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")

        self.lineEdit_5.raise_()
        self.lineEdit_7.raise_()
        self.lineEdit_8.raise_()
        self.comboBox_2.raise_()

        self.pushButton_4.raise_()
        self.widget_4 = QtWidgets.QWidget(Form)
        self.widget_4.setGeometry(QtCore.QRect(530, 30, 510, 690))
        self.widget_4.setStyleSheet("border:1px solid black;")
        self.widget_4.setObjectName("widget_4")

        self.lineEdit_6 = QtWidgets.QLineEdit(self.widget_4)
        self.lineEdit_6.setGeometry(QtCore.QRect(70, 10, 350, 50))
        self.lineEdit_6.setStyleSheet("font: 16pt \"宋体\";")
        self.lineEdit_6.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit_6.setObjectName("lineEdit_6")

        self.widget_4.raise_()
        self.widget_3.raise_()
        self.label2.raise_()
        self.pushButton.raise_()
        self.comboBox.raise_()
        self.pushButton_3.raise_()
        self.label1.raise_()
        self.textEdit.raise_()
        self.textEdit_2.raise_()
        self.tableWidget.raise_()
        self.lineEdit_3.raise_()
        self.lineEdit_4.raise_()
        self.pushButton_2.raise_()
        self.pushButton_5.raise_()
        self.pushButton_6.raise_()
        self.pushButton_7.raise_()
        self.lineEdit_2.raise_()

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)


    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "YOLOV5检测"))
        self.pushButton.setText(_translate("Form", "选择文件"))
        self.pushButton_7.setText(_translate("Form", "是否结束"))
        self.comboBox.setItemText(0, _translate("Form", "检测方式"))
        self.comboBox.setItemText(1, _translate("Form", "图片检测"))
        self.comboBox.setItemText(2, _translate("Form", "视频检测"))
        self.comboBox.setItemText(3, _translate("Form", "摄像头检测"))
        self.pushButton_2.setText(_translate("Form", "开始检测"))
        self.pushButton_5.setText(_translate("Form", "确定"))
        self.pushButton_6.setText(_translate("Form", "结束程序"))
        self.pushButton_3.setText(_translate("Form", "模型路径"))
        self.textEdit.setText(_translate("Form", "\n原\n始\n图\n片\n/\n视\n频"))
        self.textEdit_2.setText(_translate("Form", "\n\n\n测\n试\n结\n果"))
        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(_translate("Form", "imgsize"))
        item = self.tableWidget.verticalHeaderItem(1)
        item.setText(_translate("Form", "conf"))
        item = self.tableWidget.verticalHeaderItem(2)
        item.setText(_translate("Form", "iou"))
        item = self.tableWidget.verticalHeaderItem(3)
        item.setText(_translate("Form", "dnn"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("Form", "数值"))
        self.tableWidget.setItem(0,0,QtWidgets.QTableWidgetItem("640")) #图片大小默认值
        self.tableWidget.setItem(0,1,QtWidgets.QTableWidgetItem("0.25")) #置信度阈值默认值
        self.tableWidget.setItem(0,2,QtWidgets.QTableWidgetItem("0.45")) #IOU阈值默认值
        self.tableWidget.setItem(0,3,QtWidgets.QTableWidgetItem("False")) #IOU阈值默认值

        self.lineEdit_3.setPlaceholderText(_translate("Form", "模型的路径"))
        self.lineEdit_4.setPlaceholderText(_translate("Form", "图片或视频检测及摄像头检测"))
        self.lineEdit_5.setText(_translate("Form", "参数设置及可视化"))
        self.lineEdit_7.setPlaceholderText(_translate("Form", "图片或视频路径"))
        self.pushButton_4.setText(_translate("Form", "其他参数"))
        self.lineEdit_8.setPlaceholderText(_translate("Form", "运行设备(CPU或GPU)"))
        self.comboBox_2.setItemText(0, _translate("Form", "设备选择"))
        self.comboBox_2.setItemText(1, _translate("Form", "CPU"))
        self.comboBox_2.setItemText(2, _translate("Form", "GPU"))
        self.lineEdit_6.setText(_translate("Form", "图片及测试结果可视化"))
        self.lineEdit_2.setPlaceholderText(_translate("Form", "是否关闭视频或者摄像头"))

三、效果展示

1、图片效果展示如下:

QT部署YOLOV5

2、摄像头或视频检测

QT部署YOLOV5

四、整体代码:

若界面太大或太小,就自己添加些代码,将界面自适应电脑,或者手动修改代码33行。

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'det.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

import sys
import os
root_path=os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
sys.path.append(root_path)

from PyQt5 import QtCore, QtGui, QtWidgets
import torch
import cv2
from PIL import Image,ImageQt
import numpy as np
from utils.general import non_max_suppression
from utils.general import check_img_size,scale_coords
from utils.augmentations import letterbox
import os
from pathlib import Path
from utils.plots import Annotator,colors
from models.experimental import attempt_load


class Ui_Form(QtWidgets.QWidget):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1130, 730)
        self.stride=64
        #检测结果展示区
        self.label2 = QtWidgets.QLabel(Form)
        self.label2.setGeometry(QtCore.QRect(650, 410, 300, 300))
        self.label2.setAlignment(QtCore.Qt.AlignCenter)
        self.label2.setStyleSheet("border: 1px solid black;")
        self.label2.setObjectName("label2")

        #图片或视频路径选择
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(50, 310, 160, 30))
        self.pushButton.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton.setChecked(False)  # 设置开始时的状态为未选中
        self.pushButton.clicked.connect(lambda :self.select_file())
        self.pushButton.setObjectName("pushButton")  #图片选择按钮

        #模式选择
        self.comboBox = QtWidgets.QComboBox(Form)
        self.comboBox.setGeometry(QtCore.QRect(50, 260, 160, 30))
        self.comboBox.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.comboBox.setPlaceholderText("")
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.currentIndexChanged.connect(lambda :self.select_mode())

        #开始检测按钮
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(190, 610, 100, 70))
        self.pushButton_2.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setChecked(False)
        self.pushButton_2.clicked.connect(lambda :self.vim_show())

        self.pushButton_3 = QtWidgets.QPushButton(Form)
        self.pushButton_3.setGeometry(QtCore.QRect(50, 210, 160, 30))
        self.pushButton_3.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.setChecked(False) # 设置开始时的状态为未选中
        self.pushButton_3.clicked.connect(lambda :self.select_modelfile())

        self.pushButton_7 = QtWidgets.QPushButton(Form)
        self.pushButton_7.setGeometry(QtCore.QRect(50, 550, 160, 30))
        self.pushButton_7.setStyleSheet("font: 15pt \"宋体\";\n"
                                        "border:1px solid black;\n"
                                        "background-color:#e1e1e1;")
        self.pushButton_7.setObjectName("pushButton_7")

        self.lineEdit_2=QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(230, 550, 220, 30))
        self.lineEdit_2.setStyleSheet("border: 1px solid black;")
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.label1=QtWidgets.QLabel(Form)
        self.label1.setGeometry(QtCore.QRect(650, 100, 300, 300))
        self.label2.setAlignment(QtCore.Qt.AlignCenter)
        self.label1.setStyleSheet("border: 1px solid black;")
        self.label1.setObjectName("label1")

        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(600, 100, 40, 300))
        self.textEdit.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.textEdit.setStyleSheet("border: 1px solid black;\n"
"font: 15pt \"宋体\";")

        self.textEdit.setObjectName("textEdit")

        self.textEdit_2 = QtWidgets.QTextEdit(Form)
        self.textEdit_2.setGeometry(QtCore.QRect(600, 410, 40, 300))
        self.textEdit_2.setStyleSheet("border: 1px solid black;\n"
"font: 15pt \"宋体\";")
        self.textEdit_2.setAlignment(QtCore.Qt.AlignHCenter)
        self.textEdit_2.setObjectName("textEdit_2")

        self.tableWidget = QtWidgets.QTableWidget(Form)
        self.tableWidget.setGeometry(QtCore.QRect(230, 370, 221, 170))
        self.tableWidget.setStyleSheet("font: 15pt \"宋体\";\n"
"")
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(1)
        self.tableWidget.setRowCount(4)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(100)
        self.tableWidget.horizontalHeader().setMinimumSectionSize(100)
        self.tableWidget.verticalHeader().setDefaultSectionSize(30)

        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setGeometry(QtCore.QRect(230, 210, 220, 30))
        self.lineEdit_3.setStyleSheet("border: 1px solid black;")
        self.lineEdit_3.setObjectName("lineEdit_3")

        self.lineEdit_4 = QtWidgets.QLineEdit(Form)
        self.lineEdit_4.setGeometry(QtCore.QRect(230, 260, 220, 30))
        self.lineEdit_4.setStyleSheet("border: 1px solid black;")
        self.lineEdit_4.setObjectName("lineEdit_4")

        self.widget_3 = QtWidgets.QWidget(Form)
        self.widget_3.setGeometry(QtCore.QRect(20, 30, 460, 690))
        self.widget_3.setStyleSheet("border : 1px solid black;")
        self.widget_3.setObjectName("widget_3")

        self.lineEdit_5 = QtWidgets.QLineEdit(self.widget_3)
        self.lineEdit_5.setGeometry(QtCore.QRect(90, 20, 261, 51))
        self.lineEdit_5.setStyleSheet("font: 16pt \"宋体\";")
        self.lineEdit_5.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit_5.setObjectName("lineEdit_5")

        self.lineEdit_7 = QtWidgets.QLineEdit(self.widget_3)
        self.lineEdit_7.setGeometry(QtCore.QRect(210, 280, 220, 30))
        self.lineEdit_7.setStyleSheet("border: 1px solid black;")
        self.lineEdit_7.setObjectName("lineEdit_7")

        self.pushButton_4 = QtWidgets.QPushButton(self.widget_3)
        self.pushButton_4.setGeometry(QtCore.QRect(30, 410, 160, 61))
        self.pushButton_4.setStyleSheet("font: 15pt \"宋体\";\n"
"background-color:#e1e1e1;")
        self.pushButton_4.setObjectName("pushButton_4")

        #参数确认按钮
        self.pushButton_5 = QtWidgets.QPushButton(Form)
        self.pushButton_5.setGeometry(QtCore.QRect(50, 610, 100, 70))
        self.pushButton_5.setStyleSheet("font: 15pt \"宋体\";\n"
"border:1px solid black;\n"
"background-color:#e1e1e1;")
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_5.setChecked(False)
        self.pushButton_5.clicked.connect(lambda: self.param_show())

        #结束检测按钮
        self.pushButton_6 = QtWidgets.QPushButton(Form)
        self.pushButton_6.setGeometry(QtCore.QRect(330, 610, 100, 70))
        self.pushButton_6.setStyleSheet("font: 15pt \"宋体\";\n"
                                        "border:1px solid black;\n"
                                        "background-color:#e1e1e1;")
        self.pushButton_6.setObjectName("pushButton_6")
        self.pushButton_6.setChecked(False)
        self.pushButton_6.clicked.connect(lambda: self.end_detect())




        self.lineEdit_8 = QtWidgets.QLineEdit(self.widget_3)
        self.lineEdit_8.setGeometry(QtCore.QRect(210, 120, 220, 30))
        self.lineEdit_8.setStyleSheet("border: 1px solid black;")
        self.lineEdit_8.setObjectName("lineEdit_8")

        self.comboBox_2 = QtWidgets.QComboBox(self.widget_3)
        self.comboBox_2.setGeometry(QtCore.QRect(30, 120, 160, 30))
        self.comboBox_2.setStyleSheet("font: 15pt \"宋体\";\n"
"background-color:#e1e1e1;")
        self.comboBox_2.setPlaceholderText("")
        self.comboBox_2.setObjectName("comboBox_2")
        self.comboBox_2.currentIndexChanged.connect(lambda : self.select_device())
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")

        self.lineEdit_5.raise_()
        self.lineEdit_7.raise_()
        self.lineEdit_8.raise_()
        self.comboBox_2.raise_()

        self.pushButton_4.raise_()
        self.widget_4 = QtWidgets.QWidget(Form)
        self.widget_4.setGeometry(QtCore.QRect(530, 30, 510, 690))
        self.widget_4.setStyleSheet("border:1px solid black;")
        self.widget_4.setObjectName("widget_4")

        self.lineEdit_6 = QtWidgets.QLineEdit(self.widget_4)
        self.lineEdit_6.setGeometry(QtCore.QRect(70, 10, 350, 50))
        self.lineEdit_6.setStyleSheet("font: 16pt \"宋体\";")
        self.lineEdit_6.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit_6.setObjectName("lineEdit_6")

        self.widget_4.raise_()
        self.widget_3.raise_()
        self.label2.raise_()
        self.pushButton.raise_()
        self.comboBox.raise_()
        self.pushButton_3.raise_()
        self.label1.raise_()
        self.textEdit.raise_()
        self.textEdit_2.raise_()
        self.tableWidget.raise_()
        self.lineEdit_3.raise_()
        self.lineEdit_4.raise_()
        self.pushButton_2.raise_()
        self.pushButton_5.raise_()
        self.pushButton_6.raise_()
        self.pushButton_7.raise_()
        self.lineEdit_2.raise_()

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)


    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "YOLOV5检测"))
        self.pushButton.setText(_translate("Form", "选择文件"))
        self.pushButton_7.setText(_translate("Form", "是否结束"))
        self.comboBox.setItemText(0, _translate("Form", "检测方式"))
        self.comboBox.setItemText(1, _translate("Form", "图片检测"))
        self.comboBox.setItemText(2, _translate("Form", "视频检测"))
        self.comboBox.setItemText(3, _translate("Form", "摄像头检测"))
        self.pushButton_2.setText(_translate("Form", "开始检测"))
        self.pushButton_5.setText(_translate("Form", "确定"))
        self.pushButton_6.setText(_translate("Form", "结束程序"))
        self.pushButton_3.setText(_translate("Form", "模型路径"))
        self.textEdit.setText(_translate("Form", "\n原\n始\n图\n片\n/\n视\n频"))
        self.textEdit_2.setText(_translate("Form", "\n\n\n测\n试\n结\n果"))
        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(_translate("Form", "imgsize"))
        item = self.tableWidget.verticalHeaderItem(1)
        item.setText(_translate("Form", "conf"))
        item = self.tableWidget.verticalHeaderItem(2)
        item.setText(_translate("Form", "iou"))
        item = self.tableWidget.verticalHeaderItem(3)
        item.setText(_translate("Form", "dnn"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("Form", "数值"))
        self.tableWidget.setItem(0,0,QtWidgets.QTableWidgetItem("640")) #图片大小默认值
        self.tableWidget.setItem(0,1,QtWidgets.QTableWidgetItem("0.25")) #置信度阈值默认值
        self.tableWidget.setItem(0,2,QtWidgets.QTableWidgetItem("0.45")) #IOU阈值默认值
        self.tableWidget.setItem(0,3,QtWidgets.QTableWidgetItem("False")) #IOU阈值默认值

        self.lineEdit_3.setPlaceholderText(_translate("Form", "模型的路径"))
        self.lineEdit_4.setPlaceholderText(_translate("Form", "图片或视频检测及摄像头检测"))
        self.lineEdit_5.setText(_translate("Form", "参数设置及可视化"))
        self.lineEdit_7.setPlaceholderText(_translate("Form", "图片或视频路径"))
        self.pushButton_4.setText(_translate("Form", "其他参数"))
        self.lineEdit_8.setPlaceholderText(_translate("Form", "运行设备(CPU或GPU)"))
        self.comboBox_2.setItemText(0, _translate("Form", "设备选择"))
        self.comboBox_2.setItemText(1, _translate("Form", "CPU"))
        self.comboBox_2.setItemText(2, _translate("Form", "GPU"))
        self.lineEdit_6.setText(_translate("Form", "图片及测试结果可视化"))
        self.lineEdit_2.setPlaceholderText(_translate("Form", "是否关闭视频或者摄像头"))
    #选择图片或视频路径
    def select_file(self):
        file,_=QtWidgets.QFileDialog.getOpenFileName(None,"选择文件",os.getcwd(),"All Files(*.jpg;*.png;*.jpeg;*.mp4;*.flv;*.avi;);;Text Files (*.txt)")
        self.lineEdit_7.setText(file)

    #选择模型路径
    def select_modelfile(self):
        file,_=QtWidgets.QFileDialog.getOpenFileName(None,"选择文件",os.getcwd(),"All Files(*.pt;*.onnx;*.pth);;")
        self.lineEdit_3.setText(file)

    #设备选择
    def select_device(self):
        device=self.comboBox_2.currentText() #获取下拉框的信息
        self.lineEdit_8.setText(device)

    #模式选择
    def select_mode(self):
        mode=self.comboBox.currentText()
        self.lineEdit_4.setText(mode)

    #模型初始化
    def param_show(self):
        device = torch.device("cpu" if self.lineEdit_8.text()=="CPU" else "cuda") #设备
        modelpath = self.lineEdit_3.text() #模型路径

        self.suffix = Path(modelpath).suffix[1:]
        if self.suffix == "pt":
            self.flag=True
            self.model = attempt_load(modelpath if isinstance(modelpath, list) else modelpath,
                                 map_location=device)
            self.stride = int(self.model.stride.max())  # model stride
            self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names  # get class names
            if self.lineEdit_8.text() == "GPU":
                self.model.half()

        elif self.suffix == "onnx":
            self.dnn = False
            self.flag=False
            if self.dnn:
                # check_requirements(('opencv-python>=4.5.4',))
                self.model = cv2.dnn.readNetFromONNX(modelpath)
            else:
                # check_requirements(('onnx', 'onnxruntime-gpu' if torch.has_cuda else 'onnxruntime'))
                import onnxruntime
                self.model = onnxruntime.InferenceSession(modelpath, None)

        # 后两项分别为按钮(以|隔开,共有7种按钮类型,见示例后)、默认按钮(省略则默认为第一个按钮)
        msg=QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning,"消息框", "模型初始化完成,请开始检测")
        msg.exec_()

    #检测
    def vim_show(self):
        filepath=self.lineEdit_7.text() #文件路径
        detect_mode=self.lineEdit_4.text()#检测模式
        imgsize = int(self.tableWidget.item(0, 0).text())  # 图片尺寸
        conf_thres = float(self.tableWidget.item(1, 0).text())  # 置信度阈值
        iou_thres = float(self.tableWidget.item(2, 0).text())  # iou阈值
        device = self.lineEdit_8.text()  # 设备

        if detect_mode=="图片检测":
            #opencv读图展示
            origin_img=cv2.imread(filepath)
            if origin_img.shape[0] > origin_img.shape[1]:  # h>w
                orgin_img1 = cv2.resize(origin_img, (int(origin_img.shape[1] * (300 / origin_img.shape[0])-1), 300),
                                 cv2.INTER_LINEAR)
            else:  # w>=h
                orgin_img1 = cv2.resize(origin_img, (300, int(origin_img.shape[0] * (300 / origin_img.shape[1]))-1),
                                 cv2.INTER_LINEAR)

            #图片预处理
            input_img=self.process_img(origin_img,device,imgsize)
            #推理
            result=self.process_inference(origin_img,input_img,conf_thres,iou_thres)
            #结果展示
            if result.shape[0] > result.shape[1]:  # h>w
                img1 = cv2.resize(result, (int(result.shape[1] * (300 / result.shape[0]))-1, 300),
                                 cv2.INTER_LINEAR)
            else:  # w>=h
                img1 = cv2.resize(result, (300, int(result.shape[0] * (300 / result.shape[1]))-1),
                                 cv2.INTER_LINEAR)


            #原图展示
            rgb_img = cv2.cvtColor(orgin_img1, cv2.COLOR_BGR2RGB)
            qimg = QtGui.QImage(rgb_img.data, rgb_img.shape[1], rgb_img.shape[0], QtGui.QImage.Format_RGB888)
            self.label1.setPixmap(QtGui.QPixmap.fromImage(qimg))

            #结果展示
            rgb_img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
            qimg1 = QtGui.QImage(rgb_img1.data, rgb_img1.shape[1], rgb_img1.shape[0], QtGui.QImage.Format_RGB888)
            self.label2.setPixmap(QtGui.QPixmap.fromImage(qimg1))


        elif detect_mode=="视频检测":
            cap = cv2.VideoCapture(filepath)
            count = 1
            while cap.isOpened():
                if count % 2 == 0:
                    ret, frame = cap.read()
                    if ret:
                        if frame.shape[0] > frame.shape[1]:  # h>w
                            img = cv2.resize(frame, (int(frame.shape[1] * (300 / frame.shape[0])), 300),
                                             cv2.INTER_LINEAR)
                        else:  # w>=h
                            img = cv2.resize(frame, (300, int(frame.shape[0] * (300 / frame.shape[1]))),
                                             cv2.INTER_LINEAR)

                        input_img = self.process_img(frame, device, imgsize)
                        result = self.process_inference(frame, input_img, conf_thres, iou_thres)
                        if result.shape[0] > result.shape[1]:  # h>w
                            img1 = cv2.resize(result, (int(result.shape[1] * (300 / result.shape[0])) - 1, 300),
                                              cv2.INTER_LINEAR)
                        else:  # h<=w
                            img1 = cv2.resize(result, (300, int(result.shape[0] * (300 / result.shape[1])) - 1),
                                              cv2.INTER_LINEAR)

                        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
                        cv2.waitKey(1)
                        qimg = QtGui.QImage(img.data, img.shape[1], img.shape[0], QtGui.QImage.Format_RGB888)
                        self.label1.setPixmap(QtGui.QPixmap.fromImage(qimg))

                        # 结果展示
                        rgb1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
                        qimg1 = QtGui.QImage(rgb1.data, rgb1.shape[1], rgb1.shape[0], QtGui.QImage.Format_RGB888)
                        self.label2.setPixmap(QtGui.QPixmap.fromImage(qimg1))
                    else:

                        break

                    count=1
                else:
                    count += 1
            cap.release()
            cv2.destroyAllWindows()
        else:
            self.cap = cv2.VideoCapture(0)
            count = 1
            while True:
                if count % 2 == 0:
                    ret, frame = self.cap.read()
                    if ret:
                        if frame.shape[0] > frame.shape[1]:  # h>w
                            img = cv2.resize(frame, (int(frame.shape[1] * (300 / frame.shape[0])), 300),
                                             cv2.INTER_LINEAR)
                        else:  # w>=h
                            img = cv2.resize(frame, (300, int(frame.shape[0] * (300 / frame.shape[1]))),
                                             cv2.INTER_LINEAR)


                        input_img=self.process_img(frame,device,imgsize)
                        result=self.process_inference(frame,input_img,conf_thres,iou_thres)
                        if result.shape[0]>result.shape[1]: #h>w
                            img1=cv2.resize(result,(int(result.shape[1]*(300/result.shape[0]))-1,300),cv2.INTER_LINEAR)
                        else: #h<=w
                            img1=cv2.resize(result,(300,int(result.shape[0]*(300/result.shape[1]))-1),
                                            cv2.INTER_LINEAR)

                        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
                        cv2.waitKey(1)
                        qimg = QtGui.QImage(img.data, img.shape[1], img.shape[0], QtGui.QImage.Format_RGB888)
                        self.label1.setPixmap(QtGui.QPixmap.fromImage(qimg))

                        #结果展示
                        rgb1=cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)
                        qimg1=QtGui.QImage(rgb1.data,rgb1.shape[1],rgb1.shape[0],QtGui.QImage.Format_RGB888)
                        self.label2.setPixmap(QtGui.QPixmap.fromImage(qimg1))
                    #复位
                    count=1
                    if self.lineEdit_2.text()=="是":
                        break

                else:
                    count += 1
            self.cap.release()
            cv2.destroyAllWindows()

    #退出程序
    def end_detect(self):
       sys.exit(1)



    #图片处理
    def process_img(self,org_img,device,imgsize):
        '''
        Args:
            org_img: 原图
            device: 设备
            imgsize: 图片尺寸

        Returns:

        '''
        # 查看图片尺寸是否能别stride整除
        imgsz = check_img_size(imgsize, s=self.stride)
        # resize_padding
        img = letterbox(org_img, imgsz, self.stride, auto=self.flag)[0]
        img = img.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB
        img = np.ascontiguousarray(img)
        if self.suffix == "onnx":
            img = img.astype("float32")
        else:
            img = torch.from_numpy(img).to(device.lower())
            # 设置是否为半精度测试
            if device == "GPU":
                img = img.half()
            else:
                img=img.float()

        img /= 255.0  # 归一化
        if len(img.shape) == 3:
            img = img[None]

        return img

    #推理进程
    def process_inference(self,org_img,img,conf_thres,iou_thres):
        '''
        Args:
            org_img: 原图
            img: 缩放后的图
            conf_thres: 置信度阈值
            iou_thres: IOU阈值

        Returns:

        '''
        if self.suffix == "pt":
            pred = self.model(img)[0]
        elif self.suffix == "onnx":
            if self.dnn:
                self.model.setInput(img)
                pred = torch.tensor(self.model.forward())
            else:
                pred = torch.tensor(self.model.run([self.model.get_outputs()[0].name], {self.model.get_inputs()[0].name: img}))
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes=None, agnostic=False, max_det=1000)
        dt, seen = [0.0, 0.0, 0.0], 0
        for i, det in enumerate(pred):
            seen += 1
            im0 = org_img.copy()
            # 绘制预测框
            annotator = Annotator(im0, line_width=3, example=str(1))
            # 检测到目标时
            if len(det):
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
                # 写结果
                for *xyxy, conf, cls in reversed(det):
                    c = int(cls)
                    # label = f'{conf:.2f}'
                    label = f'{self.names[c]} {conf:.2f}'
                    annotator.box_label(xyxy, label, color=colors(c, True))

            im0 = annotator.result()


            # cv2.imwrite(save_path + os.sep + Path(img_path).name, im0)
        return im0


if __name__ == '__main__':
    import sys
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)  # 解决了Qtdesigner设计的界面与实际运行界面不一致的问题
    app = QtWidgets.QApplication(sys.argv)
    widget = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(widget)
    widget.show()
    sys.exit(app.exec_())

总结

以上就是本篇文章的全部内容,欢迎评论区指正错误,也可加入QQ群:995760755交流。文章来源地址https://www.toymoban.com/news/detail-453821.html

到了这里,关于QT部署YOLOV5的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • yolov5-6.0项目部署+自用Pytorch模型转换rknn模型并在RK3568 linux(Debian)平台上使用qt部署使用NPU推理加速摄像头目标识别详细新手教程

    1 我们打开yolov的官网,Tags选择6.0版本 2. 下载该压缩包并解压到工程目录下 3. 我们这里使用pycharm,专门针对python的IDE,用起来非常方便,下载方式就是官网直接下载,用的是社区版 4. 我们需要安装环境,这里我推荐安装Anaconda在电脑上,这是一个非常方便的包管理工具,可

    2024年02月05日
    浏览(68)
  • QT+Opencv+yolov5实现监测

    功能说明:使用QT+Opencv+yolov5实现监测 =============================== 仓库链接:https://gitee.com/wangyoujie11/qt_yolov5.git git本仓库到本地 一、环境配置 1.opencv配置 将OpenCV-MinGW-Build-OpenCV-4.5.2-x64文件夹放在自己的一个目录下,如我的路径: 编辑系统环境变量【配置完成之后,要 确定 】

    2024年04月11日
    浏览(41)
  • yolov5目标检测多线程Qt界面

    上一篇文章:yolov5目标检测多线程C++部署 mainwindow.h mainwindow.cpp 这里引入的第三方库moodycamel::ConcurrentQueue是一个用C++11实现的多生产者、多消费者无锁队列。 程序输出: 界面效果: 可以看到,上面的程序实现了两个模型的多线程推理,但由于不同模型推理速度有差异,导致画

    2024年02月13日
    浏览(47)
  • YOLOv5+QT5界面应用开发

    YOLOv5+QT5的UI界面开发 最终界面图: 本文章基于python3.7的Annaconda中虚拟环境开发: 1.1 配置YOLOv5环境 https://github.com/ultralytics/yolov5 下载yolov5程序后,虚拟环境下运行: activate v5 pip install -r requirements.txt 1.2 配置QT环境 pip install pyqt5 pyqt5-tools 使用pyqt5自带的图形界面设计工具:de

    2023年04月19日
    浏览(45)
  • 【YOLOv5】LabVIEW+TensorRT的yolov5部署实战(含源码)

    ‍‍🏡博客主页: virobotics的CSDN博客:LabVIEW深度学习、人工智能博主 🎄所属专栏:『LabVIEW深度学习实战』 🍻上期文章: 手把手教你使用LabVIEW TensorRT实现图像分类实战(含源码) 📰如觉得博主文章写的不错或对你有所帮助的话,还望大家多多支持呀! 欢迎大家✌关注、

    2024年02月14日
    浏览(36)
  • 【目标检测算法实现之yolov5】 一、YOLOv5环境配置,将yolov5部署到远程服务器上

    在官网:https://github.com/ultralytics/yolov5上下载yolov5源代码 下载成功如下: 在配置基础环境之前,提前压缩自己的代码文件,并通过winscp传输给linux端,传输之后,解压该文件。解压前,先创建一个文件夹,再解压。 winscp下载使用教程参考上一篇博客:使用WinSCP下载和文件传输

    2024年01月15日
    浏览(55)
  • Docker部署yolov5

    Ubuntu:22.10 Docker:24.0.0 这里我下载了6.0版本的,想要别的版本的自己修改,但dockerfile可能目录不同,可以通过find指令查询 这里要等待很长时间,构建大概20g的镜像 具体错误详情: 这是因为版本不匹配的问题,Dockerfile中只限制了opencv-python的版本大于4.1.2并没有限制最高版本,

    2024年02月08日
    浏览(39)
  • 树莓派部署YOLOv5模型

    本文章是关于树莓派部署YOLOv5s模型,实际测试效果的FPS仅有0.15,不够满足实际检测需要,各位大佬可以参考参考。 1、在树莓派中安装opencv(默认安装好python3) 2、导出onnx模型 从YOLOv5官网下载源代码和YOLOv5s.pt文件 YOLOv5官网 YOLOv5s.pt下载 按照作者提示安装环境,使用它自带

    2024年02月11日
    浏览(46)
  • yolov5安卓(鸿蒙)手机部署

    本篇文章主要是针对yolov5s在安卓(鸿蒙)手机部署过程进行记录。 有关YOLOv5其他资料可以参考我以下文章进行学习: C++版tensorrt YOLOv5推理 如何通过YAML文件修改YOLOv5网络 YOLOv5通道剪枝 YOLOv5图像分割代码详解1 YOLOv5图像分割之NMS YOLOv5+霍夫变换之车道线检测 YOLOv5损失函数详解

    2024年02月09日
    浏览(40)
  • YOLOv5原理分析及部署教程

    本文是nano自动驾驶小车开发系列中关于环境感知部分的分享,介绍目标检测中的yolo算法。 我分别使用了OAK-D-Lite和普通USB摄像头这两种硬件在windows10下实现了yolov 5的复现。如果使用OAK的话,需要首先配置好OAK-SDK再使用。 ​​​​​​​   硬件:OAK-D-Lite、普通USB摄像头 软件

    2024年02月03日
    浏览(47)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包