python版pytorch模型转openvino及调用

一、openvino安装

参看官方文档https://www.intel.com/content/www/us/en/developer/tools/openvino-toolkit/download.html
在这里插入图片描述
在这里插入图片描述
安装命令是根据上面的选择生成。这里安装了pytorch和onnx依赖。

二、pytorch模型转opnvino模型推理

import os
import time
import cv2
import numpy as np
import torch

from openvino.runtime import Core
from openvino.tools import mo


img_path = r'./000000002306.jpg'
model_path = 'pure_pose.pt'
## 加载onnx模型
model = torch.load(model_path)
model.eval()
## onnx模型转openvino
model_ir = mo.convert_model(
    model, input_shape=[1,3, 256, 192],
    mean_values = [123.675, 116.28 , 103.53],
    scale_values=[58.395, 57.12 , 57.375],
    compress_to_fp16=True
)

## 图片预处理
image = cv2.cvtColor(
    src=cv2.imread(filename=str(img_path)),
    code=cv2.COLOR_BGR2RGB,
)
resized_image,ratio, (dw, dh) = letterbox(image,new_shape=(256,192))

# # # Convert the image shape to a shape and a data type expected by the network
# # # for OpenVINO IR model: (1, 3, 512, 512).
input_image = np.expand_dims(np.transpose(resized_image, (2, 0, 1)), 0)

ie = Core()
compiled_model_ir = ie.compile_model(model=model_ir, device_name="CPU")
# Get the names of input and output layers.
input_layer_ir = compiled_model_ir.input(0)
output_layer_ir = compiled_model_ir.output(0)

# Do inference on the input image.
start_time = time.perf_counter()
result = compiled_model_ir([input_image])[output_layer_ir]
end_time = time.perf_counter()
print(
    f"Inference finished. Inference time: {end_time-start_time:.3f} seconds, "
    f"FPS: {1/(end_time-start_time):.2f}."
)

在pytorch转openvino模型的时候,已包含归一化操作过程。在推理的时候不需要对输入图片做归一化操作。

三、onnx模型转opnvino模型推理

1. onnx模型转openvino模型

在上面的安装文件夹openvino_env文件夹下找到mo_onnx.py文件。我的路径:openvino_env/lib/python3.9/site-packages/openvino/tools/mo/mo_onnx.py
根据下面的脚本将onnx模型转成openvino模型

python ../openvino_env/lib/python3.9/site-packages/openvino/tools/mo/mo_onnx.py \
  --input_model ./mobilenet_load.onnx  \
  --output_dir ./openvino_model \
  --input_shape "[1,3,256,192]" \
  --mean_values="[123.675, 116.28 , 103.53]" \
  --scale_values="[58.395, 57.12 , 57.375]" \
  --data_type FP16

生成下面三个文件
在这里插入图片描述

2. 调用openvino模型进行推理

import time
import cv2
import numpy as np
from openvino.runtime import Core
img_path = r'./000000002306.jpg'
from utils import letterbox

image = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)

# Convert the resized images to network input shape
resized_image,ratio, (dw, dh) = letterbox(image,new_shape=(256,192))
h, w, c = resized_image.shape
input_image = np.expand_dims(np.transpose(resized_image, (2, 0, 1)), 0)

# Load the network in Inference Engine
core = Core()
model_ir = core.read_model(model="openvino_model/mobilenet_load.xml")
compiled_model_ir = core.compile_model(model=model_ir, device_name="CPU")

# Get output layer
output_layer_ir = compiled_model_ir.output(0)

# Run inference on the input image
# Do inference on the input image.
start_time = time.perf_counter()
res_ir = compiled_model_ir([input_image])[output_layer_ir]
end_time = time.perf_counter()
print(
    f"Inference finished. Inference time: {end_time-start_time:.3f} seconds, "
    f"FPS: {1/(end_time-start_time):.2f}."
)

比较通过pytorch和onnx转成的openvino模型的推理时间,差不多。openvino模型推理时间大概是pytorch模型推理时间的1/5.

模型推理时间(s)
openvino0.010
onnx0.015
pytorch0.048
OpenVINO™ 工具套件可以有效加速基于Python的大模型部署,提高推理性能,并优化资源利用率。下面简要介绍如何利用 OpenVINO 进行 Python 部署。 ### 1. 准备工作 首先你需要安装 Intel® Distribution of OpenVINO™ 工具包。你可以通过官方网站获取最新本并按照官方文档完成环境配置。 接着确保已准备好你要换和运行的目标深度学习模型文件(如 .onnx 或者 TensorFlow、PyTorch 格式的预训练模型)。如果需要的话还可以下载公共数据集用于测试目的。 ### 2. 模型换 为了让模型能够在 OpenVINO 中高效地执行,通常我们需要将原始框架下的模型成 Intermediate Representation (IR) 文件形式: ```python from openvino.tools import mo import os # 设置输入模型路径和其他必要的参数 input_model = "path/to/your/model" output_dir = "./ir_models" if not os.path.exists(output_dir): os.mkdir(output_dir) mo.convert_model(input_model=input_model, output_dir=output_dir) ``` 上述命令会生成 `.xml` 和 `.bin` 后缀名组成的 IR 对象对;前者描述网络拓扑结构而后者则保存权重信息等具体内容。 ### 3. 加载与推断 接下来就是编写 Python 脚本来加载刚刚创建好的 IR 并构建实际应用了。这里以简单的图像分类任务为例展示基本流程: ```python import numpy as np import cv2 from openvino.runtime import Core def preprocess_image(image_path, input_size=(224, 224)): image = cv2.imread(image_path) resized = cv2.resize(image, dsize=input_size[::-1]) transposed = resized.transpose((2,0,1)) # HWC->CHW normalized = ((transposed / 255.) - [0.485, 0.456, 0.406]) / ([0.229, 0.224, 0.225] * 255.) return np.expand_dims(normalized, axis=0).astype(np.float32) core = Core() model = core.read_model(model="path/to/converted.xml") compiled_model = core.compile_model(model=model, device_name="CPU") infer_request = compiled_model.create_infer_request() image_input = preprocess_image("test.jpg") results = infer_request.infer([image_input]) print(results) ``` 这个脚本演示了一个从读取图片到前处理再到最终得到预测结果完整的端到端过程。 请注意这只是一个非常基础的例子,在真实场景下还需要考虑很多细节比如批量大小调整、异步调用管理等等因素来进一步提升效率和服务质量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值