目录
C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测
效果
模型信息
Inputs
name:image
tensor:Float[1, 3, 640, 640]
name:scale_factor
tensor:Float[1, 2]
Outputs
name:multiclass_nms3_0.tmp_0
tensor:Float[-1, 6]
name:multiclass_nms3_0.tmp_2
tensor:Int32[1]
项目
VS2022
.net framework 4.8
OpenCvSharp 4.8
Microsoft.ML.OnnxRuntime 1.16.2
代码
using Microsoft.ML.OnnxRuntime.Tensors;
using Microsoft.ML.OnnxRuntime;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Drawing;
using System.IO;
using System.Text;
namespace Onnx_Demo
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
string image_path = "";
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now;
float confThreshold = 0.5f;
int inpWidth;
int inpHeight;
Mat image;
string model_path = "";
SessionOptions options;
InferenceSession onnx_session;
Tensor<float> input_tensor;
Tensor<float> input_tensor_scale;
List<NamedOnnxValue> input_container;
IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
DisposableNamedOnnxValue[] results_onnxvalue;
List<string> class_names;
int num_class;
StringBuilder sb = new StringBuilder();
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = fileFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
pictureBox1.Image = null;
pictureBox2.Image = null;
textBox1.Text = "";
image_path = ofd.FileName;
pictureBox1.Image = new System.Drawing.Bitmap(image_path);
image = new Mat(image_path);
}
private void Form1_Load(object sender, EventArgs e)
{
// 创建输入容器
input_container = new List<NamedOnnxValue>();
// 创建输出会话
options = new SessionOptions();
options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行
// 创建推理模型类,读取本地模型文件
model_path = "model/ppyoloe_plus_crn_s_80e_coco_640x640.onnx";
inpHeight = 640;
inpWidth = 640;
onnx_session = new InferenceSession(model_path, options);
// 创建输入容器
input_container = new List<NamedOnnxValue>();
image_path = "test_img/bus.jpg";
pictureBox1.Image = new Bitmap(image_path);
class_names = new List<string>();
StreamReader sr = new StreamReader("coco.names");
string line;
while ((line = sr.ReadLine()) != null)
{
class_names.Add(line);
}
num_class = class_names.Count();
}
private unsafe void button2_Click(object sender, EventArgs e)
{
if (image_path == "")
{
return;
}
textBox1.Text = "检测中,请稍等......";
pictureBox2.Image = null;
sb.Clear();
System.Windows.Forms.Application.DoEvents();
image = new Mat(image_path);
//-----------------前处理--------------------------
Mat dstimg = new Mat();
float ratio = Math.Min(inpHeight * 1.0f / image.Rows, inpWidth * 1.0f / image.Cols);
int neww = (int)(image.Cols * ratio);
int newh = (int)(image.Rows * ratio);
Cv2.CvtColor(image, dstimg, ColorConversionCodes.BGR2RGB);
Cv2.Resize(dstimg, dstimg, new OpenCvSharp.Size(neww, newh));
Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant, new Scalar(1));
//Cv2.ImShow("dstimg", dstimg);
int row = dstimg.Rows;
int col = dstimg.Cols;
float[] input_tensor_data = new float[1 * 3 * row * col];
for (int c = 0; c < 3; c++)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
byte pix = ((byte*)(dstimg.Ptr(i).ToPointer()))[j * 3 + c];
input_tensor_data[c * row * col + i * col + j] = (float)(pix / 255.0);
}
}
}
input_tensor = new DenseTensor<float>(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });
input_tensor_scale = new DenseTensor<float>(new float[] { 1, 1 }, new[] { 1, 2 });
input_container.Add(NamedOnnxValue.CreateFromTensor("image", input_tensor));
input_container.Add(NamedOnnxValue.CreateFromTensor("scale_factor", input_tensor_scale));
//-----------------推理--------------------------
dt1 = DateTime.Now;
result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果
dt2 = DateTime.Now;
//-----------------后处理--------------------------
results_onnxvalue = result_infer.ToArray();
int nout = results_onnxvalue[0].AsTensor<float>().Dimensions[1];
float[] outs = results_onnxvalue[0].AsTensor<float>().ToArray();
int[] box_num = results_onnxvalue[1].AsTensor<int>().ToArray();
List<float> confidences = new List<float>();
List<Rect> position_boxes = new List<Rect>();
List<int> class_ids = new List<int>();
Result result = new Result();
for (int i = 0; i < box_num[0]; i++)
{
if (outs[0 + nout * i] > -1 && outs[1 + nout * i] > confThreshold)
{
class_ids.Add((int)outs[0 + nout * i]);
confidences.Add(outs[1 + nout * i]);
float xmin = outs[2 + nout * i] / ratio;
float ymin = outs[3 + nout * i] / ratio;
float xmax = outs[4 + nout * i] / ratio;
float ymax = outs[5 + nout * i] / ratio;
Rect box = new Rect();
box.X = (int)xmin;
box.Y = (int)ymin;
box.Width = (int)(xmax - xmin);
box.Height = (int)(ymax - ymin);
position_boxes.Add(box);
}
}
for (int i = 0; i < position_boxes.Count; i++)
{
int index = i;
result.add(confidences[index], position_boxes[index], class_names[class_ids[index]]);
}
if (pictureBox2.Image != null)
{
pictureBox2.Image.Dispose();
}
sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
sb.AppendLine("------------------------------");
// 将识别结果绘制到图片上
Mat result_image = image.Clone();
for (int i = 0; i < result.length; i++)
{
Cv2.Rectangle(result_image, result.rects[i], new Scalar(0, 0, 255), 2, LineTypes.Link8);
Cv2.Rectangle(result_image, new OpenCvSharp.Point(result.rects[i].TopLeft.X - 1, result.rects[i].TopLeft.Y - 20),
new OpenCvSharp.Point(result.rects[i].BottomRight.X, result.rects[i].TopLeft.Y), new Scalar(0, 0, 255), -1);
Cv2.PutText(result_image, result.classes[i] + "-" + result.scores[i].ToString("0.00"),
new OpenCvSharp.Point(result.rects[i].X, result.rects[i].Y - 4),
HersheyFonts.HersheySimplex, 0.6, new Scalar(0, 0, 0), 1);
sb.AppendLine(string.Format("{0}:{1},({2},{3},{4},{5})"
, result.classes[i]
, result.scores[i].ToString("0.00")
, result.rects[i].TopLeft.X
, result.rects[i].TopLeft.Y
, result.rects[i].BottomRight.X
, result.rects[i].BottomRight.Y
));
}
textBox1.Text = sb.ToString();
pictureBox2.Image = new System.Drawing.Bitmap(result_image.ToMemoryStream());
result_image.Dispose();
dstimg.Dispose();
image.Dispose();
}
private void pictureBox2_DoubleClick(object sender, EventArgs e)
{
Common.ShowNormalImg(pictureBox2.Image);
}
private void pictureBox1_DoubleClick(object sender, EventArgs e)
{
Common.ShowNormalImg(pictureBox1.Image);
}
}
}
using Microsoft.ML.OnnxRuntime.Tensors;
using Microsoft.ML.OnnxRuntime;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Drawing;
using System.IO;
using System.Text;
namespace Onnx_Demo
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
string image_path = "";
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now;
float confThreshold = 0.5f;
int inpWidth;
int inpHeight;
Mat image;
string model_path = "";
SessionOptions options;
InferenceSession onnx_session;
Tensor<float> input_tensor;
Tensor<float> input_tensor_scale;
List<NamedOnnxValue> input_container;
IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
DisposableNamedOnnxValue[] results_onnxvalue;
List<string> class_names;
int num_class;
StringBuilder sb = new StringBuilder();
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = fileFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
pictureBox1.Image = null;
pictureBox2.Image = null;
textBox1.Text = "";
image_path = ofd.FileName;
pictureBox1.Image = new System.Drawing.Bitmap(image_path);
image = new Mat(image_path);
}
private void Form1_Load(object sender, EventArgs e)
{
// 创建输入容器
input_container = new List<NamedOnnxValue>();
// 创建输出会话
options = new SessionOptions();
options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行
// 创建推理模型类,读取本地模型文件
model_path = "model/ppyoloe_plus_crn_s_80e_coco_640x640.onnx";
inpHeight = 640;
inpWidth = 640;
onnx_session = new InferenceSession(model_path, options);
// 创建输入容器
input_container = new List<NamedOnnxValue>();
image_path = "test_img/bus.jpg";
pictureBox1.Image = new Bitmap(image_path);
class_names = new List<string>();
StreamReader sr = new StreamReader("coco.names");
string line;
while ((line = sr.ReadLine()) != null)
{
class_names.Add(line);
}
num_class = class_names.Count();
}
private unsafe void button2_Click(object sender, EventArgs e)
{
if (image_path == "")
{
return;
}
textBox1.Text = "检测中,请稍等......";
pictureBox2.Image = null;
sb.Clear();
System.Windows.Forms.Application.DoEvents();
image = new Mat(image_path);
//-----------------前处理--------------------------
Mat dstimg = new Mat();
float ratio = Math.Min(inpHeight * 1.0f / image.Rows, inpWidth * 1.0f / image.Cols);
int neww = (int)(image.Cols * ratio);
int newh = (int)(image.Rows * ratio);
Cv2.CvtColor(image, dstimg, ColorConversionCodes.BGR2RGB);
Cv2.Resize(dstimg, dstimg, new OpenCvSharp.Size(neww, newh));
Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant, new Scalar(1));
//Cv2.ImShow("dstimg", dstimg);
int row = dstimg.Rows;
int col = dstimg.Cols;
float[] input_tensor_data = new float[1 * 3 * row * col];
for (int c = 0; c < 3; c++)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
byte pix = ((byte*)(dstimg.Ptr(i).ToPointer()))[j * 3 + c];
input_tensor_data[c * row * col + i * col + j] = (float)(pix / 255.0);
}
}
}
input_tensor = new DenseTensor<float>(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });
input_tensor_scale = new DenseTensor<float>(new float[] { 1, 1 }, new[] { 1, 2 });
input_container.Add(NamedOnnxValue.CreateFromTensor("image", input_tensor));
input_container.Add(NamedOnnxValue.CreateFromTensor("scale_factor", input_tensor_scale));
//-----------------推理--------------------------
dt1 = DateTime.Now;
result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果
dt2 = DateTime.Now;
//-----------------后处理--------------------------
results_onnxvalue = result_infer.ToArray();
int nout = results_onnxvalue[0].AsTensor<float>().Dimensions[1];
float[] outs = results_onnxvalue[0].AsTensor<float>().ToArray();
int[] box_num = results_onnxvalue[1].AsTensor<int>().ToArray();
List<float> confidences = new List<float>();
List<Rect> position_boxes = new List<Rect>();
List<int> class_ids = new List<int>();
Result result = new Result();
for (int i = 0; i < box_num[0]; i++)
{
if (outs[0 + nout * i] > -1 && outs[1 + nout * i] > confThreshold)
{
class_ids.Add((int)outs[0 + nout * i]);
confidences.Add(outs[1 + nout * i]);
float xmin = outs[2 + nout * i] / ratio;
float ymin = outs[3 + nout * i] / ratio;
float xmax = outs[4 + nout * i] / ratio;
float ymax = outs[5 + nout * i] / ratio;
Rect box = new Rect();
box.X = (int)xmin;
box.Y = (int)ymin;
box.Width = (int)(xmax - xmin);
box.Height = (int)(ymax - ymin);
position_boxes.Add(box);
}
}
for (int i = 0; i < position_boxes.Count; i++)
{
int index = i;
result.add(confidences[index], position_boxes[index], class_names[class_ids[index]]);
}
if (pictureBox2.Image != null)
{
pictureBox2.Image.Dispose();
}
sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
sb.AppendLine("------------------------------");
// 将识别结果绘制到图片上
Mat result_image = image.Clone();
for (int i = 0; i < result.length; i++)
{
Cv2.Rectangle(result_image, result.rects[i], new Scalar(0, 0, 255), 2, LineTypes.Link8);
Cv2.Rectangle(result_image, new OpenCvSharp.Point(result.rects[i].TopLeft.X - 1, result.rects[i].TopLeft.Y - 20),
new OpenCvSharp.Point(result.rects[i].BottomRight.X, result.rects[i].TopLeft.Y), new Scalar(0, 0, 255), -1);
Cv2.PutText(result_image, result.classes[i] + "-" + result.scores[i].ToString("0.00"),
new OpenCvSharp.Point(result.rects[i].X, result.rects[i].Y - 4),
HersheyFonts.HersheySimplex, 0.6, new Scalar(0, 0, 0), 1);
sb.AppendLine(string.Format("{0}:{1},({2},{3},{4},{5})"
, result.classes[i]
, result.scores[i].ToString("0.00")
, result.rects[i].TopLeft.X
, result.rects[i].TopLeft.Y
, result.rects[i].BottomRight.X
, result.rects[i].BottomRight.Y
));
}
textBox1.Text = sb.ToString();
pictureBox2.Image = new System.Drawing.Bitmap(result_image.ToMemoryStream());
result_image.Dispose();
dstimg.Dispose();
image.Dispose();
}
private void pictureBox2_DoubleClick(object sender, EventArgs e)
{
Common.ShowNormalImg(pictureBox2.Image);
}
private void pictureBox1_DoubleClick(object sender, EventArgs e)
{
Common.ShowNormalImg(pictureBox1.Image);
}
}
}