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

下载

源码下载


http://www.niftyadmin.cn/n/5228838.html

相关文章

分享88个简历竞聘PPT,总有一款适合您

分享88个简历竞聘PPT&#xff0c;总有一款适合您 88个简历竞聘PPT下载链接&#xff1a;https://pan.baidu.com/s/1Iz73OYIv_3CmO5tOXEX8Ng?pwd8888 提取码&#xff1a;8888 Python采集代码下载链接&#xff1a;采集代码.zip - 蓝奏云 学习知识费力气&#xff0c;收集整…

vue3+vite搭建cesium项目

1.创建项目 cnpm create vite 2.安装依赖 npm i cesium vite-plugin-cesium vite -D 3.在vite.config.js里进行配置 import { defineConfig } from vite import vue from vitejs/plugin-vue import cesium from vite-plugin-cesium; export default defineConfig({plugins…

【ArcGIS Pro二次开发】(78):批量合并GDB数据库

有些GDB数据库会按分幅或行政区划进行分开储存&#xff0c;尤其是一些地形测绘或国情地理数据。 如下图所示&#xff1a; 数据是完整的&#xff0c;但使用的时候要一个一个拖进地图中&#xff0c;进行分析的时候也需要将其合并后使用。 因此就做了这个合库工具。 一、要实现的…

【电路笔记】-快速了解电阻

快速了解电阻 文章目录 快速了解电阻1、概述2、电阻器的组成类型2.1 碳电阻器2.2 薄膜电阻器2.3 绕线电阻器 3、总结 电阻器是所有电子元件中最基本、最常用的元件&#xff0c;人们几乎认为电阻器是理所当然的&#xff0c;但它们在电路中起着至关重要的作用。 1、概述 有许多不…

gstreamer读取v4l2

以下是使用Gstreamer读取v4l2的步骤&#xff1a; 确保已经安装了Gstreamer相关软件&#xff0c;可以使用以下命令进行安装&#xff1a; apt install gstreamer1.0-plugins-* gstreamer1.0-libav libgstreamer1.0* libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libgs…

重生之我是一名程序员 46 ——字符串函数(5)

哈喽啊大家晚上好&#xff01;今晚给大家带来的还是字符串函数大家庭——strtok函数。 首先&#xff0c;还是先带大家去认识一下它。strtok函数是一个字符串处理函数&#xff0c;可以将一个字符串分割成多个子字符串。其原型为&#xff1a; char *strtok(char *str, const ch…

智能遥测终端机RTU的注意事项

智能遥测终端机RTU是一种用于实时监测和控制现场数据的设备&#xff0c;可以广泛应用于水利、水文、电力、煤炭等各个领域。但是在使用智能遥测终端机RTU时&#xff0c;也需要注意一些事项&#xff0c;以确保终端的正常使用效果。 ◆注意安装位置   应安装在稳定、通风的室内…

MsSqlServer 删除指定字段的重复记录,保留唯一值

代码如下 alter table goodstemp add AIndexId [int] IDENTITY (1, 1) NOT NULL go delete from goodstemp where AIndexId not in (select min(AIndexId) from goodstemp group by goodsNo) go alter table goodstemp drop column AIndexId思路&#xff1a; 1、为表创建一个自…