onnxruntime模型部署流程

 

一、将训练好的模型转换格式为ONNX格式
例如pytorch模型转换:

def torch5onnx(model, save_path):
    """
    :param model:
    :param save_path:  XXX/XXX.onnx
    :return:
    """
    model.eval()
    data = torch.rand(1, 3, 224, 224)
    input_names = ["input"]  
    output_names = ["out"]  
    torch.onnx._export(model, data, save_path, export_params=True, opset_version=11, input_names=input_names, output_names=output_names)
    print("torch5onnx finish.")

 

支持动态形状的输入和输出:

def torch5onnx_dynamic(model, save_path):
    """
    :param model:
    :param save_path:  XXX/XXX.onnx
    :return:
    """
    model.eval()
    data = torch.rand(1, 3, 224, 224)
    input_names = ["input"]  # ncnn需要
    output_names = ["out"]  # ncnn需要
    torch.onnx._export(model, data, save_path, export_params=True, opset_version=11, input_names=input_names,
                       output_names=output_names, dynamic_axes={'input': [2, 3], 'out': [2, 3]})
    print("torch5onnx finish.")

 

二、安装onnxruntime
注意:onnxruntime-gpu版本在0.4以上时需要CUDA 10

pip install onnxruntime
pip install onnxruntime-gpu

 

onnxruntime帮助文档:

https://microsoft.github.io/onnxruntime/python/tutorial.html

 

三、onnxruntime使用方法
加载模型:

session = onnxruntime.InferenceSession("./dmnet.onnx")

 

加载图片:

img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
tensor = transforms.ToTensor()(img)
tensor = tensor.unsqueeze_(0)

 

执行推理:
注意:这里的"input"是和转onnx格式时的名字对应的。

result = session.run([], {"input": tensor.cpu().numpy()})

 

最新回复(0)
/jishu2FXnvHqo1EFv_2FGKU_2ByqHmY8nVv_2BMYBX9_2FV26j0y0hwI_3D4795428
8 简首页