https://github.com/sdcb/PaddleSharp/blob/feature/2.5/docs/paddle2onnx.md
效果
项目
代码
using Sdcb.Paddle2Onnx;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Paddle模型转ONNX模型
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string pdiparamsfileFilter = "*.pdiparams|*.pdiparams";
string pdmodelfileFilter = "*.pdmodel|*.pdmodel";
string paramsFile;
string modelFile;
StringBuilder sb = new StringBuilder();
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now;
private void button1_Click(object sender, EventArgs e)
{
sb.Clear();
textBox3.Text = "";
if (string.IsNullOrEmpty(modelFile) || string.IsNullOrEmpty(paramsFile))
{
return;
}
dt1 = DateTime.Now;
bool can = Paddle2OnnxConverter.CanConvert(modelFile, paramsFile);
Console.WriteLine(can);
if (can)
{
byte[] modelBuffer = File.ReadAllBytes(modelFile);
PaddleModelInfo modelInfo = Paddle2OnnxConverter.DescribePaddleModel(modelBuffer);
sb.AppendLine($"PaddleModel Input: {string.Join(", ", modelInfo.InputNames)}");
sb.AppendLine($"PaddleModel Output: {string.Join(", ", modelInfo.OutputNames)}");
sb.AppendLine("");
byte[] paramsBuffer = File.ReadAllBytes(paramsFile);
byte[] onnxModel = Paddle2OnnxConverter.ConvertToOnnx(modelBuffer, paramsBuffer);
OnnxModelInfo onnxInfo = Paddle2OnnxConverter.DescribeOnnxModel(onnxModel);
sb.AppendLine("OnnxModel Input:");
sb.AppendLine(string.Join("\r\n", onnxInfo.Inputs.Select(x => x.ToString())));
sb.AppendLine("OnnxModel Output:");
sb.AppendLine(string.Join("\r\n", onnxInfo.Outputs.Select(x => x.ToString())));
//输出onnx模型
using (FileStream fs = new FileStream("model.onnx", FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Write(onnxModel, 0, onnxModel.Length);
}
dt2 = DateTime.Now;
sb.AppendLine("----------------------------------------------------------------------");
sb.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sb.AppendLine("耗时:" + (dt2 - dt1).TotalMilliseconds + "ms\n");
textBox3.Text = sb.ToString();
//MessageBox.Show("ok");
}
else
{
MessageBox.Show("该Paddle模型不能转成ONNX模型");
}
}
/// <summary>
/// paramsFile
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = pdiparamsfileFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
paramsFile = ofd.FileName;
textBox1.Text = paramsFile;
}
/// <summary>
/// modelFile
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = pdmodelfileFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
modelFile = ofd.FileName;
textBox2.Text = modelFile;
}
}
}
Demo下载