介绍
在程序调用Onnx模型时,一般都会查看一下模型的属性、输入、输出信息,一般可以不看模型具体的信息。可以使用Netron查看,Netron地址:
https://netron.app/在线查看时需要有网,模型越大加载越慢。大多时候只想快速查看一下模型的输入、输出信息,所以自己写了一个C#Onnx模型信息查看工具。
效果
Netron效果
开发环境
VS2022
.net framework 4.8
OpenCvSharp 4.8
Microsoft.ML.OnnxRuntime 1.16.2
代码
using Microsoft.ML.OnnxRuntime;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace Onnx_Demo
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
// 堆代码 duidaima.com
string fileFilter = "*.*|*.onnx;";
string model_path;
StringBuilder sb = new StringBuilder();
InferenceSession onnx_session;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = fileFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
txtInfo.Text = "";
model_path = ofd.FileName;
txtPath.Text = model_path;
txtInfo.Text = "正在读取,请稍后……";
Application.DoEvents();
ShowInfo(model_path);
}
void ShowInfo(string model_path)
{
try
{
onnx_session = new InferenceSession(model_path);
}
catch (Exception ex)
{
MessageBox.Show("读取模型异常:" + ex.Message);
}
sb.Clear();
//Model Properties
sb.AppendLine("Model Properties");
sb.AppendLine("-------------------------");
Dictionary<string, string> CustomMetadataMap = onnx_session.ModelMetadata.CustomMetadataMap;
foreach (string key in CustomMetadataMap.Keys)
{
sb.AppendLine(String.Format("{0}:{1}",key, CustomMetadataMap[key])) ;
}
sb.AppendLine("---------------------------------------------------------------");
IReadOnlyList<string> InputNames = onnx_session.InputNames;
IReadOnlyDictionary<string, NodeMetadata> InputMetadata = onnx_session.InputMetadata;
//Inputs
sb.AppendLine("");
sb.AppendLine("Inputs");
sb.AppendLine("-------------------------");
foreach (var item in InputMetadata)
{
sb.AppendLine("name:" + item.Key);
NodeMetadata nmData= item.Value;
int[] dim = nmData.Dimensions;
sb.AppendLine("tensor:" + nmData.ElementDataType.ToString()+"["+ String.Join(", ", dim)+"]");
}
sb.AppendLine("---------------------------------------------------------------");
IReadOnlyList<string> OutputNames = onnx_session.OutputNames;
IReadOnlyDictionary<string, NodeMetadata> OutputMetadata = onnx_session.OutputMetadata;
//Outputs
sb.AppendLine("");
sb.AppendLine("Outputs");
sb.AppendLine("-------------------------");
foreach (var item in OutputMetadata)
{
sb.AppendLine("name:" + item.Key);
NodeMetadata nmData = item.Value;
int[] dim = nmData.Dimensions;
sb.AppendLine("tensor:" + nmData.ElementDataType.ToString() + "[" + String.Join(", ", dim) + "]");
}
sb.AppendLine("---------------------------------------------------------------");
txtInfo.Text = sb.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}