142.人工智能-PySide6+FastDeploy实现可视化图像分类预测

在上一篇中,有讲过使用FastDeploy来部署模型,实现目标检测,详情可以参看:141.人工智能——FastDeploy:PPYOLOE模型部署,实现目标检测

本文继续使用FastDeploy来部署模型,实现图像分类检测,并使用PySide6可视化程序界面。


分类模型:MobileNetV3。下载地址:https://bj.bcebos.com/paddlehub/fastdeploy/MobileNetV3_large_x1_0_ssld_infer.tgz。(也可以使用自己的训练模型)

模型

参数文件大小

输入Shape

Top1

Top5

MobileNetV3_large_x1_0_ssld

22MB

224x224

78.96%

94.48%

要实现的功能:打开一个图像文件,输出显示分类结果在窗体上。

一、先看一下运行效果

二、功能实现

1、界面:

可视化界面可以直接使用Qt Designer,在前面一些文章有讲过。本文由于界面组件比较简单,直接使用代码来完成可视化界面的设计。有关窗体代码布局可以参看:135.Python——PySide6:创建三种不同类型窗口

界面设计:定义类,窗体继承QMainWindow

窗体组件:一个标签:用来显示图像预测结果,一个按钮:用来选择图像文件。

2、imagenet1k_label_list.txt文本文件。分类ID与标签名称。

0 tench, Tinca tinca
1 goldfish, Carassius auratus
2 great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias
3 tiger shark, Galeocerdo cuvieri
4 hammerhead, hammerhead shark
5 electric ray, crampfish, numbfish, torpedo
6 stingray
……

3、完整代码:

import sys
from PySide6 import QtWidgets,QtGui,QtCore
import cv2
import fastdeploy as fd
from string import digits

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        
        #获取主屏幕大小,#设置窗口大小,屏幕居中
        screen=QtGui.QGuiApplication.primaryScreen().geometry()
        sw,sh=screen.width(),screen.height()
        #self.setFixedSize(400,300) #窗口大小固定
        w,h=400,300
        self.setGeometry((sw-w)//2,(sh-h)//2,w,h) #窗口大小可调
        self.setWindowTitle("FastDeploy Image")
        
        #定义一个垂直布局
        layout=QtWidgets.QVBoxLayout()
        self.status=self.statusBar()
        self.status.showMessage("图像预测")
        
        #定义一个标签,用来显示图像
        self.lblimg=QtWidgets.QLabel()
        
        #定义一个按钮,用来打开图像文件
        self.btnopen=QtWidgets.QPushButton("Open Image File")
        #信号槽
        self.btnopen.clicked.connect(self.Open)
        #添加组件到layout布局中
        layout.addWidget(self.lblimg)
        layout.addWidget(self.btnopen)
        
        #MainWindow的布局管理方式,用setLayout
        main_frame=QtWidgets.QWidget()
        main_frame.setLayout(layout)
        self.setCentralWidget(main_frame)
    
        #加载预测模型
        model_file="MobileNetV3_large_x1_0_ssld_infer/inference.pdmodel"
        params_file="MobileNetV3_large_x1_0_ssld_infer/inference.pdiparams"
        config_file="MobileNetV3_large_x1_0_ssld_infer/inference_cls.yaml"
        labels_file="MobileNetV3_large_x1_0_ssld_infer/imagenet1k_label_list.txt"
        self.model = fd.vision.classification.PaddleClasModel(
            model_file, params_file, config_file, model_format=fd.Frontend.PADDLE)
        
        #获取分类名称
        self.class_info=self.get_class_info(labels_file)
      
		#槽函数,打开图像,预测并显示
    def Open(self):
        filename,typefile=QtWidgets.QFileDialog.getOpenFileName(self, '选择','', "图像文件(*.jpg *.png)")
        print(filename)
        img=self.predict(filename)
        self.showimg(img)
        
    #读取imagenet1k文件,获取图像分类信息
    def get_class_info(self,file_path):
        class_info =[]
        with open(file_path, 'r') as f:
            for line in f:
                line = line.strip()
                table=line.maketrans("","",digits) #去字符串的数字
                class_info.append(line.translate(table).strip())
        return class_info
    
    #预测结果
    def predict(self, filename):   
        if filename:    
            img = cv2.imread(filename)
            result = self.model.predict(img.copy())  #只显示Top1
            #解析返回的结构体信息,获取ID和score
            result=str(result).split("
")[1:-1]
            print(result)
            label=self.class_info[int(result[0].split(":")[1].strip()[:-1])]
            score=float(result[1].split(":")[1].strip()[:-1])
            #print(label,score)
            cv2.putText(img, label+":"+str(round(score,2)),(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.6,(255,0,0),2)
            self.status.showMessage(filename)
            return img
            
    #显示预测结果
    def showimg(self, img):
        h,w=img.shape[:2] #图像大小
        self.lblimg.setAlignment(QtCore.Qt.AlignCenter) #设置lblimg的对齐方式
        self.lblimg.setFixedSize(self.width(), self.height()-40)
        #BGR转QImage
        qimg=QtGui.QImage(img.data,img.shape[1],img.shape[0],img.shape[1]*3,QtGui.QImage.Format_BGR888)
        #设置图像大小自适应控件大小
        self.lblimg.setPixmap(QtGui.QPixmap.fromImage(qimg).scaled(self.lblimg.width(),self.lblimg.height(),QtCore.Qt.KeepAspectRatio))
        
if __name__=="__main__":
    app=QtWidgets.QApplication(sys.argv)
    mywin=MainWindow()
    mywin.show()
    sys.exit(app.exec())

三、运行结果:

预测结果1

预测结果2

可以看出,FastDeploy非常方便、高效的实现了模型部署,PySide6又为Python图形化界面开发提供了强而有力的保障。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章