如何将 ONNX 模型转换为 OpenVINO IR 格式(.xml 和 .bin)

在深度学习应用中,模型的格式和优化对推理性能至关重要。OpenVINO 提供了一种方便的方式将 ONNX 模型转换为其优化的中间表示(Intermediate Representation,IR),这包括 .xml.bin 文件。了解如何使用 OpenVINO 工具将 ONNX 模型转换为 OpenVINO IR 格式。

1. 准备环境

首先,确保你的系统已经安装了 OpenVINO 工具。可以通过以下命令安装最新版本的 OpenVINO:

pip install openvino-dev -i https://pypi.tuna.tsinghua.edu.cn/simple

2. 准备 ONNX 模型

在转换模型之前,你需要有一个预训练的 ONNX 模型文件。假设我们有一个名为 ir_classifier.onnx 的 ONNX 文件,存放在 E:\Desktop\targetClassify 目录中。

3. 编写 Python 代码进行转换

OpenVINO 提供了简单易用的 Python API 来完成模型转换。以下是完整的 Python 脚本示例:

# coding:UTF-8
import os
from openvino.tools.ovc import convert_model

# 定义 ONNX 模型路径
onnx_model_path = "E:\\Desktop\\targetClassify\\ir_classifier.onnx"

# 定义输出目录路径
output_dir = "E:\\Desktop\\targetClassify\\weight"

# 检查输出目录是否存在,如果不存在则创建
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
    print(f"Created output directory at: {output_dir}")
else:
    print(f"Output directory already exists at: {output_dir}")

# 设置模型转换参数
try:
    convert_model(
        model_path=onnx_model_path,  # 指定 ONNX 模型路径
        output_dir=output_dir        # 指定输出目录,模型文件将保存到这个目录中
    )
    print(f"Model successfully converted and saved to: {output_dir}")
except Exception as e:
    print(f"Error during model conversion: {e}")

4.运行脚本

Output directory already exists at: E:\Desktop\targetClassify\weight
[ INFO ] MO command line tool is considered as the legacy conversion API as of OpenVINO 2023.2 release.
In 2025.0 MO command line tool and openvino.tools.mo.convert_model() will be removed. Please use OpenVINO Model Converter (OVC) or openvino.convert_model(). OVC represents a lightweight alternative of MO and provides simplified model conversion API. 
Find more information about transition from MO to OVC at https://docs.openvino.ai/2023.2/openvino_docs_OV_Converter_UG_prepare_model_convert_model_MO_OVC_transition.html
[ INFO ] Generated IR will be compressed to FP16. If you get lower accuracy, please consider disabling compression explicitly by adding argument --compress_to_fp16=False.
Find more information about compression to FP16 at https://docs.openvino.ai/2023.0/openvino_docs_MO_DG_FP16_Compression.html
[ SUCCESS ] Generated IR version 11 model.
[ SUCCESS ] XML file: E:\Desktop\targetClassify\weight\ir_classifier.xml
[ SUCCESS ] BIN file: E:\Desktop\targetClassify\weight\ir_classifier.bin
Model successfully converted and saved to: E:\Desktop\targetClassify\weight

成功生成了.bin文件和.xml文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值