C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测

目录

效果

模型信息

项目

代码

下载


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);
        }
    }
}

下载

源码下载

相关推荐
Q8137574605 分钟前
数据挖掘在金融交易中的应用:民锋科技的智能化布局
人工智能·科技·数据挖掘
qzhqbb9 分钟前
语言模型的采样方法
人工智能·语言模型·自然语言处理
qzhqbb12 分钟前
基于 Transformer 的语言模型
人工智能·语言模型·自然语言处理·transformer
___Dream12 分钟前
【CTFN】基于耦合翻译融合网络的多模态情感分析的层次学习
人工智能·深度学习·机器学习·transformer·人机交互
IT技术分享社区17 分钟前
C#实战:使用腾讯云识别服务轻松提取火车票信息
开发语言·c#·云计算·腾讯云·共识算法
极客代码20 分钟前
【Python TensorFlow】入门到精通
开发语言·人工智能·python·深度学习·tensorflow
义小深22 分钟前
TensorFlow|咖啡豆识别
人工智能·python·tensorflow
Tianyanxiao1 小时前
如何利用探商宝精准营销,抓住行业机遇——以AI技术与大数据推动企业信息精准筛选
大数据·人工智能·科技·数据分析·深度优先·零售
撞南墙者1 小时前
OpenCV自学系列(1)——简介和GUI特征操作
人工智能·opencv·计算机视觉
OCR_wintone4211 小时前
易泊车牌识别相机,助力智慧工地建设
人工智能·数码相机·ocr