效果
模型信息
Inputs
-------------------------
name:images
tensor:Float[1, 3, 192, 320]
---------------------------------------------------------------
Outputs
-------------------------
name:output
tensor:Float[1, 1260, 80]
name:953
tensor:Float[1, 1260, 4]
---------------------------------------------------------------
项目
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 OpenCvSharp.Dnn;
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;
float nmsThreshold = 0.85f;
int inpWidth;
int inpHeight;
Mat image;
string model_path = "";
SessionOptions options;
InferenceSession onnx_session;
Tensor<float> input_tensor;
List<NamedOnnxValue> input_container;
IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
DisposableNamedOnnxValue[] results_onnxvalue;
List<string> class_names;
int nout;
int num_proposal;
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/damoyolo_tinynasL20_T_192x320.onnx";
inpHeight = 192;
inpWidth = 320;
onnx_session = new InferenceSession(model_path, options);
// 创建输入容器
input_container = new List<NamedOnnxValue>();
image_path = "test_img/dog.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);
//-----------------前处理--------------------------
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);
Mat dstimg = new Mat();
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));
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] = pix;
}
}
}
input_tensor = new DenseTensor<float>(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });
input_container.Add(NamedOnnxValue.CreateFromTensor("images", input_tensor));
//-----------------推理--------------------------
dt1 = DateTime.Now;
result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果
dt2 = DateTime.Now;
//-----------------后处理--------------------------
results_onnxvalue = result_infer.ToArray();
num_proposal = results_onnxvalue[0].AsTensor<float>().Dimensions[1];
nout = results_onnxvalue[0].AsTensor<float>().Dimensions[2];
int n = 0, k = 0; ///cx,cy,w,h,box_score, class_score
float[] pscores = results_onnxvalue[0].AsTensor<float>().ToArray();
float[] pbboxes = results_onnxvalue[1].AsTensor<float>().ToArray();
List<float> confidences = new List<float>();
List<Rect> position_boxes = new List<Rect>();
List<int> class_ids = new List<int>();
for (n = 0; n < num_proposal; n++) ///特征图尺度
{
int max_ind = 0;
float class_socre = 0;
for (k = 0; k < num_class; k++)
{
if (pscores[k + n * nout] > class_socre)
{
class_socre = pscores[k + n * nout];
max_ind = k;
}
}
if (class_socre > confThreshold)
{
float xmin = pbboxes[0 + n * 4] / ratio;
float ymin = pbboxes[1 + n * 4] / ratio;
float xmax = pbboxes[2 + n * 4] / ratio;
float ymax = pbboxes[3 + n * 4] / 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);
confidences.Add(class_socre);
class_ids.Add(max_ind);
}
}
// NMS非极大值抑制
int[] indexes = new int[position_boxes.Count];
CvDnn.NMSBoxes(position_boxes, confidences, confThreshold, nmsThreshold, out indexes);
Result result = new Result();
for (int i = 0; i < indexes.Length; i++)
{
int index = indexes[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 OpenCvSharp.Dnn;
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;float nmsThreshold = 0.85f;int inpWidth;int inpHeight;Mat image;string model_path = "";SessionOptions options;InferenceSession onnx_session;Tensor<float> input_tensor;List<NamedOnnxValue> input_container;IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;DisposableNamedOnnxValue[] results_onnxvalue;List<string> class_names;int nout;int num_proposal;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/damoyolo_tinynasL20_T_192x320.onnx";inpHeight = 192;inpWidth = 320;onnx_session = new InferenceSession(model_path, options);// 创建输入容器input_container = new List<NamedOnnxValue>();image_path = "test_img/dog.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);//-----------------前处理--------------------------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);Mat dstimg = new Mat();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));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] = pix;}}}input_tensor = new DenseTensor<float>(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });input_container.Add(NamedOnnxValue.CreateFromTensor("images", input_tensor)); //将 input_tensor 放入一个输入参数的容器,并指定名称//-----------------推理--------------------------dt1 = DateTime.Now;result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果dt2 = DateTime.Now;//-----------------后处理--------------------------results_onnxvalue = result_infer.ToArray();num_proposal = results_onnxvalue[0].AsTensor<float>().Dimensions[1];nout = results_onnxvalue[0].AsTensor<float>().Dimensions[2];int n = 0, k = 0; ///cx,cy,w,h,box_score, class_scorefloat[] pscores = results_onnxvalue[0].AsTensor<float>().ToArray();float[] pbboxes = results_onnxvalue[1].AsTensor<float>().ToArray();List<float> confidences = new List<float>();List<Rect> position_boxes = new List<Rect>();List<int> class_ids = new List<int>();for (n = 0; n < num_proposal; n++) ///特征图尺度{int max_ind = 0;float class_socre = 0;for (k = 0; k < num_class; k++){if (pscores[k + n * nout] > class_socre){class_socre = pscores[k + n * nout];max_ind = k;}}if (class_socre > confThreshold){float xmin = pbboxes[0 + n * 4] / ratio;float ymin = pbboxes[1 + n * 4] / ratio;float xmax = pbboxes[2 + n * 4] / ratio;float ymax = pbboxes[3 + n * 4] / 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);confidences.Add(class_socre);class_ids.Add(max_ind);}}// NMS非极大值抑制int[] indexes = new int[position_boxes.Count];CvDnn.NMSBoxes(position_boxes, confidences, confThreshold, nmsThreshold, out indexes);Result result = new Result();for (int i = 0; i < indexes.Length; i++){int index = indexes[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);}}
}
下载
源码下载