《博主简介》
小伙伴们好,我是阿旭。专注于人工智能、AIGC、python、计算机视觉相关分享研究。
✌更多学习资源,可关注公-仲-hao:【阿旭算法与机器学习】,共同学习交流~
👍感谢小伙伴们点赞、关注!
《------往期经典推荐------》
二、机器学习实战专栏【链接】,已更新31期,欢迎关注,持续更新中~~
三、深度学习【Pytorch】专栏【链接】
四、【Stable Diffusion绘画系列】专栏【链接】
五、YOLOv8改进专栏【链接】,持续更新中~~
六、YOLO性能对比专栏【链接】,持续更新中~
《------正文------》
引言
在使用onnx模型进行模型部署时,我们需要查看onnx模型的输入与输出结构
,然后才能进行数据的预处理与后处理过程
,从而帮助我们进行模型的部署。本文介绍3种查看onnx模型输入与输出结构的方式
,以yolov8n.onnx
为例。
方式1:使用netron
打开网页:https://netron.app
,然后打开需要查看的onnx模型,此处打开yolov8n.onnx
模型。
通过这种方式,我们不仅可以看到模型的输入与输出结构,而且可以清楚的查看模型的详细网络结构。通过右下角我们可以看到,模型的输入为【1,3,640,640】
,输出为【1,84,8400】
。
解释说明:
【1,3,640,640】表示,batch为1,输入图片为3640640;
【1,84,8400】表示,batch为1,输出向量为84【代表x, y, w, h,cls类别数80】,检测框数目为8400个。
方式2:使用onnx
我们使用onnx库
加载模型,并查看模型的输入输出结构。代码如下:
import onnx
# 加载ONNX模型
model = onnx.load('yolov8n.onnx')
# 获取并打印OpSet导入信息,从中可以找到OpSet版本
for imp in model.opset_import:
print(f"Domain: {imp.domain}, Version: {imp.version}")
# 验证模型是否有效
onnx.checker.check_model(model)
# 获取并打印模型的输入信息
print("Input(s) of the model:")
for input in model.graph.input:
print(f"Name: {input.name}, Type: {input.type}")
# 获取并打印模型的输出信息
print("\nOutput(s) of the model:")
for output in model.graph.output:
print(f"Name: {output.name}, Type: {output.type}")
输出结果如下:
Domain: , Version: 17
Input(s) of the model:
Name: images, Type: tensor_type {
elem_type: 1
shape {
dim {
dim_value: 1
}
dim {
dim_value: 3
}
dim {
dim_value: 640
}
dim {
dim_value: 640
}
}
}
Output(s) of the model:
Name: output0, Type: tensor_type {
elem_type: 1
shape {
dim {
dim_value: 1
}
dim {
dim_value: 84
}
dim {
dim_value: 8400
}
}
}
可以看到输入为【1,3,640,640】,输出为【1,84,8400】。
方式3:使用onnxruntime
我们使用onnxruntime库
加载模型,并查看模型的输入输出结构。代码如下:
import onnxruntime as ort
providers = ["CPUExecutionProvider"]
session_options = ort.SessionOptions()
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
# 使用ONNX模型创建推理会话,并指定执行提供者
session = ort.InferenceSession('yolov8n.onnx',
session_options=session_options,
providers=providers)
# 获取模型的输入信息
inputs_info = session.get_inputs()
print("Input(s) of the model:")
for input in inputs_info:
print(f"Name: {input.name}, Shape: {input.shape}, Type: {input.type}")
# 获取模型的输出信息
outputs_info = session.get_outputs()
print("\nOutput(s) of the model:")
for output in outputs_info:
print(f"Name: {output.name}, Shape: {output.shape}, Type: {output.type}")
打印信息如下:
Input(s) of the model:
Name: images, Shape: [1, 3, 640, 640], Type: tensor(float)
Output(s) of the model:
Name: output0, Shape: [1, 84, 8400], Type: tensor(float)
好了,这篇文章就介绍到这里,喜欢的小伙伴感谢给点个赞和关注,更多精彩内容持续更新~~