当前位置: 首页 > news >正文

C++ Qt / VS2019 +opencv + onnxruntime 部署语义分割模型【经验】

本机环境:
OS:WIN11
CUDA: 11.1
CUDNN:8.0.5
显卡:RTX3080 16G
opencv:3.3.0
onnxruntime:1.8.1

目前C++ 调用onnxruntime的示例主要为图像分类网络,与语义分割网络在后处理部分有很大不同。

  1. pytorch模型转为onnx格式

1.1 安装onnx, 参考官网https://onnxruntime.ai/
1.2 pytorch->onnx

import torch
from nets.unet import Unet
import numpy as np


use_cuda = torch.cuda.is_available()

device = torch.device('cuda:0' if use_cuda else 'cpu')

checkpoints = torch.load("latest.pth")
model = Unet().to(device)
model.load_state_dict(checkpoints)

model.eval()

img_scale = [64, 64]
input_shape = (1, 3, img_scale[1], img_scale[0])
rng = np.random.RandomState(0)
dummy_input = torch.rand(1, 3, 64, 64).to(device)
imgs = rng.rand(*input_shape)
output_file = "latest.onnx"

dynamic_axes = {
                'input': {
                    0: 'batch',
                    2: 'height',
                    3: 'width'
                },
                'output': {
                    1: 'batch',
                    2: 'height',
                    3: 'width'
                }
            }

with torch.no_grad():
    torch.onnx.export(
        model, dummy_input,
        output_file,
        input_names=['input'],
        output_names=['output'],
        export_params=True,
        keep_initializers_as_inputs=False,
        opset_version=11,
        dynamic_axes=dynamic_axes)
    print(f'Successfully exported ONNX model: {output_file}')

由于网络中包含upsample上采样层,出现以下问题:

TypeError: 'NoneType' object is not subscriptable 
(Occurred when translating upsample_bilinear2d).

查到有两种解决方案:

  1. 重写上采样层
  2. 【推荐】 修改参数:opset_version=11
    torch.onnx.export(model, input, onnx_path, verbose=True, input_names=input_names, output_names=output_names, opset_version=11)

检查模型是否正确

import onnx
# Load the ONNX model
onnx_model = onnx.load("latest.onnx") 
try: 
    onnx.checker.check_model(onnx_model) 
except Exception: 
    print("Model incorrect") 
else: 
    print("Model correct")

# Print a human readable representation of the graph
print(onnx.helper.printable_graph(model.graph))

python 调用onnxruntime

import onnx
import torch
import cv2
import numpy as np
import onnxruntime as ort
import torch.nn.functional as F
import matplotlib.pyplot as plt



def predict_one_img(img_path):
    img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), 1)
    img = cv2.resize(img, (64, 64))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 把图片BGR变成RGB
    print(img.shape)

    img = np.transpose(img,(2,0,1))
    
    img = img.astype(np.float32)
    img /= 255
    # img = (img - 0.5) / 0.5
    mean = [0.485, 0.456, 0.406]
    std = [0.229, 0.224, 0.225]
    for i in range(3):
        img[i,:,:] = (img[i,:,:] - mean[i]) / std[i]
    print(img.shape)

    img = np.expand_dims(img, 0)

    outputs = ort_session.run(
        None,
        {"input": img.astype(np.float32)},
    )
    print(np.max(outputs[0]))
    # print(np.argmax(outputs[0]))
    

    out = torch.tensor(outputs[0],dtype=torch.float64)
    out = F.softmax(out, dim=1)

    out = torch.squeeze(out).cpu().numpy()

    print(out.shape)
    pr = np.argmax(out, axis=0)
    
    # # out = out.argmax(axis=-1)
    # pr = F.softmax(out[0].permute(1, 2, 0), dim=-1).cpu().numpy()
    
    # pr = pr.argmax(axis=-1)
    # img = img.squeeze(0)
    # new_img = np.transpose(img, (1, 2, 0))
    new_img = pr * 255
    plt.imshow(new_img)
   
    plt.show()

if __name__ == '__main__':

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    img_path = "0007.png"
    model_path = ".latest.onnx"
    ort_session = ort.InferenceSession(model_path, providers=['CUDAExecutionProvider'])
    predict_one_img(img_path)
  1. 下载Onnxruntime

可以直接下载编译好的文件,我选用的是gpu版本
https://github.com/microsoft/onnxruntime/releases/tag/v1.8.1添加链接描述
尝试使用cmake重新编译onnxruntime,感觉是个弯路
3. vs2019 配置onnxruntime
新建空项目
右击选择属性,
VC++目录 ——包含目录——include文件夹
链接器——常规——附加库目录——lib文件夹
链接器——输入——附加依赖项 llib文件
在这里插入图片描述

将onnxruntime.dll 复制到debug目录下

  1. qt配置onnxruntime

在pro文件最后加入

include("opencv.pri")
include("onnx.pri")

DISTFILES += \
    opencv.pri \
    onnx.pri

opencv.pri

INCLUDEPATH += C:/opencv/build/include
INCLUDEPATH += C:/opencv/build/include/opencv2
INCLUDEPATH += C:/opencv/build/include/opencv

LIBS += -L"C:/opencv/build/x64/vc14/lib"\
        -lopencv_world330\
        -lopencv_world330d

onnx.pri

INCLUDEPATH += C:/onnxruntime1.8.1/include


LIBS += -L"C:/onnxruntime1.8.1/lib"\
        -lonnxruntime \

Onnx模型在线查看器:https://netron.app/

Ref
[1] C++/CV/推理部署资料整理

相关文章:

  • 如何查看线程死锁
  • 代码源每日一题div2 可重排列
  • 【原创】基于Jsp+Servlet的仓库管理系统
  • 堡垒机部署
  • linux的man命令
  • 10 项目沟通管理
  • 三分钟了解JVM的垃圾回收和三色标记
  • MapStruct简单入门
  • Redis介绍、安装与初体验
  • 第七章Redis_Jedis_测试
  • 部署keepalived+LVS
  • C++ 三大特性之继承(二)重点:菱形虚拟继承
  • 来写个贪吃蛇小游戏吧(TypeScript版本)
  • 【ASM】字节码操作 Label 如何使用 生成 if 语句
  • 【云原生】五年博主教你用阿里云Serverless免费额度搭建个人应用服务, 还不赶快上车。
  • 网络传输文件的问题
  • 【跃迁之路】【477天】刻意练习系列236(2018.05.28)
  • Angularjs之国际化
  • el-input获取焦点 input输入框为空时高亮 el-input值非法时
  • happypack两次报错的问题
  • js正则,这点儿就够用了
  • PyCharm搭建GO开发环境(GO语言学习第1课)
  • Python 使用 Tornado 框架实现 WebHook 自动部署 Git 项目
  • SpiderData 2019年2月23日 DApp数据排行榜
  • SQLServer插入数据
  • UMLCHINA 首席专家潘加宇鼎力推荐
  • Vue小说阅读器(仿追书神器)
  • 编写符合Python风格的对象
  • 技术发展面试
  • 每天一个设计模式之命令模式
  • 如何用Ubuntu和Xen来设置Kubernetes?
  • 我看到的前端
  • 小而合理的前端理论:rscss和rsjs
  • 协程
  • 新书推荐|Windows黑客编程技术详解
  • ​卜东波研究员:高观点下的少儿计算思维
  • # centos7下FFmpeg环境部署记录
  • #ubuntu# #git# repository git config --global --add safe.directory
  • #设计模式#4.6 Flyweight(享元) 对象结构型模式
  • $分析了六十多年间100万字的政府工作报告,我看到了这样的变迁
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (附源码)python旅游推荐系统 毕业设计 250623
  • (四)linux文件内容查看
  • (学习日记)2024.04.04:UCOSIII第三十二节:计数信号量实验
  • (原創) X61用戶,小心你的上蓋!! (NB) (ThinkPad) (X61)
  • (转)JVM内存分配 -Xms128m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .NET CF命令行调试器MDbg入门(二) 设备模拟器
  • .net mvc部分视图
  • .net遍历html中全部的中文,ASP.NET中遍历页面的所有button控件
  • .net开源工作流引擎ccflow表单数据返回值Pop分组模式和表格模式对比
  • .net之微信企业号开发(一) 所使用的环境与工具以及准备工作
  • [2009][note]构成理想导体超材料的有源THz欺骗表面等离子激元开关——
  • [Angular] 笔记 8:list/detail 页面以及@Input
  • [C#]无法获取源 https://api.nuge t.org/v3-index存储签名信息解决方法