OpenMMlab导出mobilenet-v2的onnx模型并推理

这篇具有很好参考价值的文章主要介绍了OpenMMlab导出mobilenet-v2的onnx模型并推理。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

导出onnx文件

使用mmpretrain导出mobilenet-v2的onnx模型:

import torch
from mmpretrain import get_model


model = get_model('mobilenet-v2_8xb32_in1k',pretrained='mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth', device='cpu') 
input = torch.zeros(1, 3, 224, 224)
out = model(input)
torch.onnx.export(model, input, "mobilenet-v2.onnx", opset_version=11)

安装有mmdeploy的话可以通过如下方法导出:

from mmdeploy.apis import torch2onnx
from mmdeploy.backend.sdk.export_info import export2SDK


img = 'goldfish.jpg'
work_dir = './work_dir/onnx/mobilenet_v2'
save_file = './end2end.onnx'
deploy_cfg = 'mmdeploy/configs/mmpretrain/classification_onnxruntime_static.py'
model_cfg = 'mmpretrain/configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py'
model_checkpoint = './checkpoints/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth'
device = 'cpu'

# 1. convert model to onnx
torch2onnx(img, work_dir, save_file, deploy_cfg, model_cfg, model_checkpoint, device)

# 2. extract pipeline info for sdk use (dump-info)
export2SDK(deploy_cfg, model_cfg, work_dir, pth=model_checkpoint, device=device)

onnxruntime推理

通过onnxruntime进行推理:

import cv2
import numpy as np
import onnxruntime


if __name__ == '__main__':
    img = cv2.imread('goldfish.jpg')
    if img.shape[0] < img.shape[1]: #h<w
        img = cv2.resize(img, (int(256*img.shape[1]/img.shape[0]), 256))
    else:
        img = cv2.resize(img, (256, int(256*img.shape[0]/img.shape[1])))

    crop_size = min(img.shape[0], img.shape[1])
    left = int((img.shape[1]-crop_size)/2)
    top = int((img.shape[0]-crop_size)/2)
    img_crop = img[top:top+crop_size, left:left+crop_size]
    img_crop = cv2.resize(img_crop, (224,224))

    img_crop = img_crop[:,:,::-1].transpose(2,0,1).astype(np.float32)   #BGR2RGB和HWC2CHW
    img_crop[0,:] = (img_crop[0,:] - 123.675) / 58.395   
    img_crop[1,:] = (img_crop[1,:] - 116.28) / 57.12
    img_crop[2,:] = (img_crop[2,:] - 103.53) / 57.375
    input = np.expand_dims(img_crop, axis=0)  

    onnx_session = onnxruntime.InferenceSession("mobilenet_v2.onnx", providers=['CPUExecutionProvider'])

    input_name=[]
    for node in onnx_session.get_inputs():
        input_name.append(node.name)

    output_name=[]
    for node in onnx_session.get_outputs():
        output_name.append(node.name)

    input_feed={}
    for name in input_name:
        input_feed[name] = input

    pred = onnx_session.run(None, input_feed)
    print(np.argmax(pred))

使用mmdeploy推理:

from mmdeploy.apis import inference_model

model
_cfg = 'mmpretrain/configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py'    
deploy_cfg = 'mmdeploy/configs/mmpretrain/classification_onnxruntime_static.py'
img = 'goldfish.jpg'
backend_files = ['work_dir/onnx/mobilenet_v2/end2end.onnx']
device = 'cpu'

result = inference_model(model_cfg, deploy_cfg, backend_files, img, device)
print(result)

或者

import cv2
from mmdeploy_runtime import Classifier


img = cv2.imread('goldfish.jpg')
classifier = Classifier(model_path='work_dir/onnx/mobilenet_v2', device_name='cpu')
result = classifier(img)
for label_id, score in result:
    print(label_id, score)

导出engine文件

这里通过trtexec转换onnx文件,LZ的版本是TensorRT-8.2.1.8。

./trtexec.exe --onnx=mobilenet_v2.onnx --saveEngine=mobilenet_v2.engine

tensorrt推理

import cv2
import numpy as np
import tensorrt as trt
import pycuda.autoinit  #负责数据初始化,内存管理,销毁等
import pycuda.driver as cuda  #GPU CPU之间的数据传输


if __name__ == '__main__':
    # 创建logger:日志记录器
    logger = trt.Logger(trt.Logger.WARNING)
    # 创建runtime并反序列化生成engine
    with open("mobilenet_v2.engine", "rb") as f, trt.Runtime(logger) as runtime:
        engine = runtime.deserialize_cuda_engine(f.read())
    context = engine.create_execution_context()
    # 分配CPU锁页内存和GPU显存
    h_input = cuda.pagelocked_empty(trt.volume(context.get_binding_shape(0)), dtype=np.float32)
    h_output = cuda.pagelocked_empty(trt.volume(context.get_binding_shape(1)), dtype=np.float32)
    d_input = cuda.mem_alloc(h_input.nbytes)
    d_output = cuda.mem_alloc(h_output.nbytes)
    # 创建cuda流
    stream = cuda.Stream()

    img = cv2.imread('goldfish.jpg')
    if img.shape[0] < img.shape[1]: #h<w
        img = cv2.resize(img, (int(256*img.shape[1]/img.shape[0]), 256))
    else:
        img = cv2.resize(img, (256, int(256*img.shape[0]/img.shape[1])))
    
    crop_size = min(img.shape[0], img.shape[1])
    left = int((img.shape[1]-crop_size)/2)
    top = int((img.shape[0]-crop_size)/2)
    img_crop = img[top:top+crop_size, left:left+crop_size]
    img_crop = cv2.resize(img_crop, (224,224))
    
    img_crop = img_crop[:,:,::-1].transpose(2,0,1).astype(np.float32)  #BGR2RGB和HWC2CHW
    img_crop[0,:] = (img_crop[0,:] - 123.675) / 58.395   
    img_crop[1,:] = (img_crop[1,:] - 116.28) / 57.12
    img_crop[2,:] = (img_crop[2,:] - 103.53) / 57.375
    input = np.expand_dims(img_crop, axis=0)   
    
    np.copyto(h_input, input.ravel())

    # 创建context并进行推理
    with engine.create_execution_context() as context:
        # Transfer input data to the GPU.
        cuda.memcpy_htod_async(d_input, h_input, stream)
        # Run inference.
        context.execute_async_v2(bindings=[int(d_input), int(d_output)], stream_handle=stream.handle)
        # Transfer predictions back from the GPU.
        cuda.memcpy_dtoh_async(h_output, d_output, stream)
        # Synchronize the stream
        stream.synchronize()
        # Return the host output. 该数据等同于原始模型的输出数据
        pred = np.argmax(h_output)
        print(pred)

使用mmdeploy推理:

from mmdeploy.apis import inference_model


model_cfg = 'mmpretrain/configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py'
deploy_cfg = 'mmdeploy/configs/mmpretrain/classification_tensorrt_static-224x224.py'
backend_files = ['work_dir/trt/mobilenet_v2/end2end.engine']
img = 'goldfish.jpg'
device = 'cuda'

result = inference_model(model_cfg, deploy_cfg, backend_files, img, device)
print(result)

或者文章来源地址https://www.toymoban.com/news/detail-744067.html

import cv2
from mmdeploy_runtime import Classifier


img = cv2.imread('goldfish.jpg')
classifier = Classifier(model_path='work_dir/onnx/mobilenet_v2', device_name='cpu')

result = classifier(img)
for label_id, score in result:
    print(label_id, score)

到了这里,关于OpenMMlab导出mobilenet-v2的onnx模型并推理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • VS c++ onnxruntime 环境配置、onnx教程、部署推理模型、sklearn pkl模型转onnx、问题汇总

    目录 一、初步认识ONNX 二、pkl转ONNX+可视化模型 三、ONNX Runtime运行时 3.1 相关介绍(了解此运行时): 3.2 VS、c++部署onnxruntime 3.3 头文件引用的一些问题 四、问题汇总: 1. 类没有成员 2. 版本兼容问题 3. 3.“GetInputName“: 不是 “Ort::Session“ 的成员 官网: ONNX Runtime | Home GitHub

    2024年04月09日
    浏览(33)
  • 使用Tools for AI封装onnx模型并推理

    进行这一步之前,请确保已正确安装配置了Visual Studio 2017 和 Microsoft Visual Studio Tools for AI环境。 项目的代码也可以在这里找到,下面的步骤是带着大家从头到尾做一遍。 创建Windows窗体应用(.NET Framework)项目,这里给项目起名ClassifyBear。 注意,项目路径不要包含中文。 在解决

    2024年02月20日
    浏览(33)
  • onnx模型转engine并进行推理全过程解析

    深度学习模型在训练好以后,下一步就是部署到不同的设备进行测试,不同设备之间的转换一般可以通过中间件ONNX进行转换,以达到不同平台的通用。本文以模型转为ONNX为起点,分析介绍ONNX转为TensorRT Engine并进行推理的整个流程链路。 ONNX序列化为TRT模型的整个流程可以用

    2024年02月06日
    浏览(29)
  • OpenCV DNN模块推理YOLOv5 ONNX模型方法

    本文档主要描述 python 平台,使用 opencv-python 深度神经网络模块 dnn ,推理 YOLOv5 模型的方法。 文档主要包含以下内容: opencv-python 模块的安装 YOLOv5 模型格式的说明 ONNX 格式模型的加载 图片数据的预处理 模型推理 推理结果后处理,包括 NMS , cxcywh 坐标转换为 xyxy 坐标等 关键方

    2024年02月16日
    浏览(40)
  • C++使用onnxruntime/opencv对onnx模型进行推理(附代码)

    结果: current image classification : French bulldog, possible : 16.17 对两张图片同时进行推理 current image classification : French bulldog, possible : 16.17 current image class ification : hare, possible : 8.47 https://download.csdn.net/download/qq_44747572/87810859 https://blog.csdn.net/qq_44747572/article/details/131631153

    2024年02月05日
    浏览(42)
  • Mxnet导出onnx模型

    requirements mxnet==1.9.1 python3.8+ onnxsim 导出模型

    2024年01月22日
    浏览(30)
  • YOLOX目标检测实战:LabVIEW+YOLOX ONNX模型实现推理检测(含源码)

    目录 前言 一、什么是YOLOX 二、环境搭建 1、部署本项目时所用环境: 2、LabVIEW工具包下载及安装: 三、模型的获取与转化【推荐方式一】 1、方式一:直接在官网下载yolox的onnx模型 2、方式二:将标准模型pth转化为onnx(较为复杂) 3、获取onnx模型总结 四、LabVIEW实现YOLOX ONN

    2024年02月15日
    浏览(29)
  • Torch 模型 onnx 文件的导出和调用

    Open Neural Network Exchange (ONNX,开放神经网络交换) 格式,是一个用于表示深度学习模型的标准,可使模型在不同框架之间进行转移 Torch 所定义的模型为动态图,其前向传播是由类方法定义和实现的 但是 Python 代码的效率是比较底下的,试想把动态图转化为静态图,模型的推理速

    2024年02月02日
    浏览(27)
  • 导出LLaMA等LLM模型为onnx

    通过onnx模型可以在支持onnx推理的推理引擎上进行推理,从而可以将LLM部署在更加广泛的平台上面。此外还可以具有避免pytorch依赖,获得更好的性能等优势。 这篇博客(大模型LLaMa及周边项目(二) - 知乎)进行了llama导出onnx的开创性的工作,但是依赖于侵入式修改transform

    2024年02月14日
    浏览(57)
  • yolov5 pt 模型 导出 onnx

    在训练好的yolov5 pt 模型 可以 通过 export.py 进行导出 onnx 导出流程 在 export.py 设置模型和数据源的yaml 在官方的文档中 说明了可以导出的具体的类型。 在 --include 添加导出的类型, 不同的 类型的 环境要求不一样,建议虚拟环境,比如onnx 和 openvino 的numpy 版本要求不一只,一

    2024年02月11日
    浏览(33)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包