C# Onnx CenterNet目标检测

目录

效果

模型信息

项目

代码

下载


效果

模型信息

Inputs
-------------------------
name:input.1
tensor:Float[1, 3, 384, 384]
---------------------------------------------------------------

Outputs
-------------------------
name:508
tensor:Float[1, 80, 96, 96]
name:511
tensor:Float[1, 2, 96, 96]
name:514
tensor:Float[1, 2, 96, 96]
---------------------------------------------------------------

项目

代码

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;
using OpenCvSharp.Flann;

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.4f;
        float nmsThreshold = 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();

        float[] mean = { 0.406f, 0.456f, 0.485f };
        float[] std = { 0.225f, 0.224f, 0.229f };

        int num_grid_y;
        int num_grid_x;

        float sigmoid(float x)
        {
            return (float)(1.0 / (1.0 + Math.Exp(-x)));
        }

        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/ctdet_coco_dlav0_384.onnx";

            inpHeight = 384;
            inpWidth = 384;

            num_grid_y = 96;
            num_grid_x = 96;

            onnx_session = new InferenceSession(model_path, options);

            // 创建输入容器
            input_container = new List<NamedOnnxValue>();

            image_path = "test_img/person.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();
            Cv2.CvtColor(image, dstimg, ColorConversionCodes.BGR2RGB);
            Cv2.Resize(dstimg, dstimg, new OpenCvSharp.Size(inpWidth, inpHeight));
            Mat[] mv = new Mat[3];
            Cv2.Split(dstimg, out mv);
            for (int i = 0; i < mv.Length; i++)
            {
                mv[i].ConvertTo(mv[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(mv, 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++)
                    {
                        float pix = ((float*)(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("input.1", input_tensor));

            //-----------------推理--------------------------
            dt1 = DateTime.Now;
            result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果
            dt2 = DateTime.Now;

            //-----------------后处理--------------------------
            results_onnxvalue = result_infer.ToArray();

            float ratioh = (float)image.Rows / inpHeight;
            float ratiow = (float)image.Cols / inpWidth;
            float stride = inpHeight / num_grid_y;

            float[] pscore = results_onnxvalue[0].AsTensor<float>().ToArray();
            float[] pxy = results_onnxvalue[1].AsTensor<float>().ToArray();
            float[] pwh = results_onnxvalue[2].AsTensor<float>().ToArray();
            int area = num_grid_y * num_grid_x;

            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 < num_grid_y; i++)
            {
                for (int j = 0; j < num_grid_x; j++)
                {
                    float max_class_score = -1000;
                    int class_id = -1;
                    for (int c = 0; c < num_class; c++)
                    {
                        float score = sigmoid(pscore[c * area + i * num_grid_x + j]);
                        if (score > max_class_score)
                        {
                            max_class_score = score;
                            class_id = c;
                        }
                    }

                    if (max_class_score > confThreshold)
                    {
                        float cx = (pxy[i * num_grid_x + j] + j) * stride * ratiow;  ///cx
                        float cy = (pxy[area + i * num_grid_x + j] + i) * stride * ratioh;   ///cy
                        float w = pwh[i * num_grid_x + j] * stride * ratiow;   ///w
                        float h = pwh[area + i * num_grid_x + j] * stride * ratioh;  ///h

                        int x = (int)Math.Max(cx - 0.5 * w, 0);
                        int y = (int)Math.Max(cy - 0.5 * h, 0);
                        int width = (int)Math.Min(w, image.Cols - 1);
                        int height = (int)Math.Min(h, image.Rows - 1);

                        position_boxes.Add(new Rect(x, y, width, height));
                        class_ids.Add(class_id);
                        confidences.Add(max_class_score);
                    }
                }
            }

            // NMS非极大值抑制
            int[] indexes = new int[position_boxes.Count];
            CvDnn.NMSBoxes(position_boxes, confidences, confThreshold, nmsThreshold, out indexes);

            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;
using OpenCvSharp.Flann;

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.4f;
        float nmsThreshold = 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();

        float[] mean = { 0.406f, 0.456f, 0.485f };
        float[] std = { 0.225f, 0.224f, 0.229f };

        int num_grid_y;
        int num_grid_x;

        float sigmoid(float x)
        {
            return (float)(1.0 / (1.0 + Math.Exp(-x)));
        }

        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/ctdet_coco_dlav0_384.onnx";

            inpHeight = 384;
            inpWidth = 384;

            num_grid_y = 96;
            num_grid_x = 96;

            onnx_session = new InferenceSession(model_path, options);

            // 创建输入容器
            input_container = new List<NamedOnnxValue>();

            image_path = "test_img/person.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();
            Cv2.CvtColor(image, dstimg, ColorConversionCodes.BGR2RGB);
            Cv2.Resize(dstimg, dstimg, new OpenCvSharp.Size(inpWidth, inpHeight));
            Mat[] mv = new Mat[3];
            Cv2.Split(dstimg, out mv);
            for (int i = 0; i < mv.Length; i++)
            {
                mv[i].ConvertTo(mv[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(mv, 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++)
                    {
                        float pix = ((float*)(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("input.1", input_tensor));

            //-----------------推理--------------------------
            dt1 = DateTime.Now;
            result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果
            dt2 = DateTime.Now;

            //-----------------后处理--------------------------
            results_onnxvalue = result_infer.ToArray();

            float ratioh = (float)image.Rows / inpHeight;
            float ratiow = (float)image.Cols / inpWidth;
            float stride = inpHeight / num_grid_y;

            float[] pscore = results_onnxvalue[0].AsTensor<float>().ToArray();
            float[] pxy = results_onnxvalue[1].AsTensor<float>().ToArray();
            float[] pwh = results_onnxvalue[2].AsTensor<float>().ToArray();
            int area = num_grid_y * num_grid_x;

            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 < num_grid_y; i++)
            {
                for (int j = 0; j < num_grid_x; j++)
                {
                    float max_class_score = -1000;
                    int class_id = -1;
                    for (int c = 0; c < num_class; c++)
                    {
                        float score = sigmoid(pscore[c * area + i * num_grid_x + j]);
                        if (score > max_class_score)
                        {
                            max_class_score = score;
                            class_id = c;
                        }
                    }

                    if (max_class_score > confThreshold)
                    {
                        float cx = (pxy[i * num_grid_x + j] + j) * stride * ratiow;  ///cx
                        float cy = (pxy[area + i * num_grid_x + j] + i) * stride * ratioh;   ///cy
                        float w = pwh[i * num_grid_x + j] * stride * ratiow;   ///w
                        float h = pwh[area + i * num_grid_x + j] * stride * ratioh;  ///h

                        int x = (int)Math.Max(cx - 0.5 * w, 0);
                        int y = (int)Math.Max(cy - 0.5 * h, 0);
                        int width = (int)Math.Min(w, image.Cols - 1);
                        int height = (int)Math.Min(h, image.Rows - 1);

                        position_boxes.Add(new Rect(x, y, width, height));
                        class_ids.Add(class_id);
                        confidences.Add(max_class_score);
                    }
                }
            }

            // NMS非极大值抑制
            int[] indexes = new int[position_boxes.Count];
            CvDnn.NMSBoxes(position_boxes, confidences, confThreshold, nmsThreshold, out indexes);

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

下载

源码下载


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

相关文章

香港科技大学广州|机器人与自主系统学域博士招生宣讲会—北京专场!!!(暨全额奖学金政策)

在机器人和自主系统领域实现全球卓越—机器人与自主系统学域 硬核科研实验室&#xff0c;浓厚创新产学研氛围&#xff01; 教授亲临现场&#xff0c;面对面答疑解惑助攻申请&#xff01; 一经录取&#xff0c;享全额奖学金1.5万/月&#xff01; 时间&#xff1a;2023年12月09日…

http的 content-type都有哪些?

HTTP请求中的Content-Type是用来指定请求或者响应的内容类型&#xff0c;告诉浏览器或者相关设备如何显示或处理加载的数据&#xff0c;此属性的值可以查看MIME&#xff08;Multipurpose Internet Mail Extensions&#xff0c;多用途互联网邮件扩展&#xff09;的类型。 如果设…

PHP处理字符串

一&#xff1a;字符串分割成数组 日常工作中&#xff0c;如果需要把一个字符串分割成数组&#xff0c;我们一般使用 explode() 函数对字符串进行分割&#xff0c;具体代码如下所示&#xff1a; <?php$str PHP|python|java|js|css|html; $arr explode(|,$str); print_r(…

使用vue UI安装路由插件

1.使用vue创建项目 vue create vue-appvue ui 2.使用vue ui界面创建管理项目 终端页面输入&#xff1a;vue ui 创建项目 安装完成。可以直接在ui界面运行&#xff0c;也可以在编辑器中使用命令运行 安装路由&#xff0c;安装状态 选择插件 - 添加vue-router、添加vuex 安装…

VSCode 创建工作区,多文件夹终端切换

VSCode 创建工作区的好处有以下几点&#xff1a; 项目结构清晰&#xff1a;每个工作区都有自己的文件夹结构&#xff0c;可以更好地组织和管理项目文件。版本控制&#xff1a;VSCode 支持多种版本控制系统&#xff0c;如Git&#xff0c;可以在工作区内进行代码的版本管理。插件…

Redis quicklist源码+listpack源码(6.0+以上版本)

ziplist设计上的问题&#xff0c;每一次增删改都需要计算前面元素的空间和长度&#xff08;prevlen&#xff09;&#xff0c;这种设计缺陷非常明显&#xff0c;一旦其中一个entry发生修改&#xff0c;以这个entry后面开始&#xff0c;全部需要重新计算prevlen&#xff0c;因此诞…

KUKA机器人如何自定义数值型变量?

KUKA机器人如何自定义数值型变量? 在KUKA机器人系统中如何自定义数值型变量来实现工件计数、计时等功能? 具体方法可参考以下内容: 如下图所示,找到SYSTEM—CONFIG.DAT文件,进入(需要管理员权限), 如下图所示,在第10行自定义一个int型的变量a, 如下图所示,自定义完成…

JDBC增删查改操作-jsp实验-实现页面跳转

实验 JDBC增删查改操作 一、实验目的 1、掌握JDBC增删查改MySQL或者sql server数据库表的方法。 2、在增删查改页面间跳转 二、实验内容 在MySQL或者sql server中创建一张表&#xff0c;之后使用JDBC进行增删查改。&#xff08;功能不限&#xff09;&#xff0c;包括&#xff1…