C# OnnxRuntime部署DAMO-YOLO香烟检测

embedded/2025/3/4 9:46:18/

 目录

说明

效果

模型信息

项目

代码

下载

参考


说明

效果

模型信息

Model Properties
-------------------------
---------------------------------------------------------------

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

Outputs
-------------------------
name:transposed_output
tensor:Float[1, 5, 8400]
---------------------------------------------------------------

项目

代码

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Onnx_Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string image_path = "";
        string model_path;
        string classer_path;
        public string[] class_names;
        public int class_num;

        DateTime dt1 = DateTime.Now;
        DateTime dt2 = DateTime.Now;

        int input_height;
        int input_width;

        InferenceSession onnx_session;

        int box_num;
        float conf_threshold;
        float nms_threshold;


        StringBuilder sb = new StringBuilder();

        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;

            pictureBox1.Image = null;

            image_path = ofd.FileName;
            pictureBox1.Image = new Bitmap(image_path);

            textBox1.Text = "";
            pictureBox2.Image = null;
        }

        /// <summary>
        /// 推理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }

            button2.Enabled = false;
            pictureBox2.Image = null;
            textBox1.Text = "";
            sb.Clear();
            Application.DoEvents();

            Mat image = new Mat(image_path);

            float ratio = Math.Min(input_height * 1.0f / image.Rows, input_width * 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, input_height - newh, 0, input_width - neww, BorderTypes.Constant, new Scalar(1));

            //Cv2.ImShow("input_img", dstimg);

            //输入Tensor
            Tensor<float> input_tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 });
            for (int y = 0; y < dstimg.Height; y++)
            {
                for (int x = 0; x < dstimg.Width; x++)
                {
                    input_tensor[0, 0, y, x] = dstimg.At<Vec3b>(y, x)[0];
                    input_tensor[0, 1, y, x] = dstimg.At<Vec3b>(y, x)[1];
                    input_tensor[0, 2, y, x] = dstimg.At<Vec3b>(y, x)[2];
                }
            }

            dstimg.Dispose();

            List<NamedOnnxValue> input_container = new List<NamedOnnxValue>
            {
                NamedOnnxValue.CreateFromTensor("input", input_tensor)
            };

            //推理
            dt1 = DateTime.Now;
            var ort_outputs = onnx_session.Run(input_container).ToArray();
            dt2 = DateTime.Now;

            float[] data = Transpose(ort_outputs[0].AsTensor<float>().ToArray(), 4 + class_num, box_num);

            float[] confidenceInfo = new float[class_num];
            float[] rectData = new float[4];

            List<DetectionResult> detResults = new List<DetectionResult>();

            for (int i = 0; i < box_num; i++)
            {
                Array.Copy(data, i * (class_num + 4), rectData, 0, 4);
                Array.Copy(data, i * (class_num + 4) + 4, confidenceInfo, 0, class_num);

                float score = confidenceInfo.Max(); // 获取最大值

                int maxIndex = Array.IndexOf(confidenceInfo, score); // 获取最大值的位置

                int xmin = (int)(rectData[0] / ratio);
                int ymin = (int)(rectData[1] / ratio);
                int xmax = (int)(rectData[2] / ratio);
                int ymax = (int)(rectData[3] / ratio);

                Rect box = new Rect();
                box.X = (int)xmin;
                box.Y = (int)ymin;
                box.Width = (int)(xmax - xmin);
                box.Height = (int)(ymax - ymin);

                detResults.Add(new DetectionResult(
                   maxIndex,
                   class_names[maxIndex],
                   box,
                   score));
            }

            //NMS
            CvDnn.NMSBoxes(detResults.Select(x => x.Rect), detResults.Select(x => x.Confidence), conf_threshold, nms_threshold, out int[] indices);
            detResults = detResults.Where((x, index) => indices.Contains(index)).ToList();

            sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
            sb.AppendLine("------------------------------");

            //绘制结果
            Mat result_image = image.Clone();
            foreach (DetectionResult r in detResults)
            {
                Cv2.PutText(result_image, $"{r.Class}:{r.Confidence:P0}", new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.Rectangle(result_image, r.Rect, Scalar.Red, thickness: 2);

                sb.AppendLine(string.Format("{0}:{1},({2},{3},{4},{5})"
                   , r.Class
                   , r.Confidence.ToString("P0")
                   , r.Rect.TopLeft.X
                   , r.Rect.TopLeft.Y
                   , r.Rect.BottomRight.X
                   , r.Rect.BottomRight.Y
                   ));
            }

            if (pictureBox2.Image != null)
            {
                pictureBox2.Image.Dispose();
            }

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());

            result_image.Dispose();

            textBox1.Text = sb.ToString();

            button2.Enabled = true;
        }

        /// <summary>
        ///窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            model_path = "model/damoyolo_cigarette.onnx";

            //创建输出会话,用于输出模型读取信息
            SessionOptions options = new SessionOptions();
            options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
            options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行

            // 创建推理模型类,读取模型文件
            onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径

            input_height = 640;
            input_width = 640;

            box_num = 8400;
            conf_threshold = 0.25f;
            nms_threshold = 0.5f;

            classer_path = "model/lable.txt";
            class_names = File.ReadAllLines(classer_path, Encoding.UTF8);
            class_num = class_names.Length;

            image_path = "test_img/2.jpg";
            pictureBox1.Image = new Bitmap(image_path);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (pictureBox2.Image == null)
            {
                return;
            }
            Bitmap output = new Bitmap(pictureBox2.Image);
            SaveFileDialog sdf = new SaveFileDialog();
            sdf.Title = "保存";
            sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp|Images (*.emf)|*.emf|Images (*.exif)|*.exif|Images (*.gif)|*.gif|Images (*.ico)|*.ico|Images (*.tiff)|*.tiff|Images (*.wmf)|*.wmf";
            if (sdf.ShowDialog() == DialogResult.OK)
            {
                switch (sdf.FilterIndex)
                {
                    case 1:
                        {
                            output.Save(sdf.FileName, ImageFormat.Jpeg);
                            break;
                        }
                    case 2:
                        {
                            output.Save(sdf.FileName, ImageFormat.Png);
                            break;
                        }
                    case 3:
                        {
                            output.Save(sdf.FileName, ImageFormat.Bmp);
                            break;
                        }
                    case 4:
                        {
                            output.Save(sdf.FileName, ImageFormat.Emf);
                            break;
                        }
                    case 5:
                        {
                            output.Save(sdf.FileName, ImageFormat.Exif);
                            break;
                        }
                    case 6:
                        {
                            output.Save(sdf.FileName, ImageFormat.Gif);
                            break;
                        }
                    case 7:
                        {
                            output.Save(sdf.FileName, ImageFormat.Icon);
                            break;
                        }

                    case 8:
                        {
                            output.Save(sdf.FileName, ImageFormat.Tiff);
                            break;
                        }
                    case 9:
                        {
                            output.Save(sdf.FileName, ImageFormat.Wmf);
                            break;
                        }
                }
                MessageBox.Show("保存成功,位置:" + sdf.FileName);
            }
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            ShowNormalImg(pictureBox1.Image);
        }

        private void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
            ShowNormalImg(pictureBox2.Image);
        }

        public void ShowNormalImg(Image img)
        {
            if (img == null) return;

            frmShow frm = new frmShow();

            frm.Width = Screen.PrimaryScreen.Bounds.Width;
            frm.Height = Screen.PrimaryScreen.Bounds.Height;

            if (frm.Width > img.Width)
            {
                frm.Width = img.Width;
            }

            if (frm.Height > img.Height)
            {
                frm.Height = img.Height;
            }

            bool b = frm.richTextBox1.ReadOnly;
            Clipboard.SetDataObject(img, true);
            frm.richTextBox1.ReadOnly = false;
            frm.richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
            frm.richTextBox1.ReadOnly = b;

            frm.ShowDialog();

        }

        public unsafe float[] Transpose(float[] tensorData, int rows, int cols)
        {
            float[] transposedTensorData = new float[tensorData.Length];

            fixed (float* pTensorData = tensorData)
            {
                fixed (float* pTransposedData = transposedTensorData)
                {
                    for (int i = 0; i < rows; i++)
                    {
                        for (int j = 0; j < cols; j++)
                        {
                            int index = i * cols + j;
                            int transposedIndex = j * rows + i;
                            pTransposedData[transposedIndex] = pTensorData[index];
                        }
                    }
                }
            }
            return transposedTensorData;
        }
    }

    public class DetectionResult
    {
        public DetectionResult(int ClassId, string Class, Rect Rect, float Confidence)
        {
            this.ClassId = ClassId;
            this.Confidence = Confidence;
            this.Rect = Rect;
            this.Class = Class;
        }

        public string Class { get; set; }

        public int ClassId { get; set; }

        public float Confidence { get; set; }

        public Rect Rect { get; set; }

    }

}

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace Onnx_Demo
{public partial class Form1 : Form{public Form1(){InitializeComponent();}string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";string image_path = "";string model_path;string classer_path;public string[] class_names;public int class_num;DateTime dt1 = DateTime.Now;DateTime dt2 = DateTime.Now;int input_height;int input_width;InferenceSession onnx_session;int box_num;float conf_threshold;float nms_threshold;StringBuilder sb = new StringBuilder();/// <summary>/// 选择图片/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.Filter = fileFilter;if (ofd.ShowDialog() != DialogResult.OK) return;pictureBox1.Image = null;image_path = ofd.FileName;pictureBox1.Image = new Bitmap(image_path);textBox1.Text = "";pictureBox2.Image = null;}/// <summary>/// 推理/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button2_Click(object sender, EventArgs e){if (image_path == ""){return;}button2.Enabled = false;pictureBox2.Image = null;textBox1.Text = "";sb.Clear();Application.DoEvents();Mat image = new Mat(image_path);float ratio = Math.Min(input_height * 1.0f / image.Rows, input_width * 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, input_height - newh, 0, input_width - neww, BorderTypes.Constant, new Scalar(1));//Cv2.ImShow("input_img", dstimg);//输入TensorTensor<float> input_tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 });for (int y = 0; y < dstimg.Height; y++){for (int x = 0; x < dstimg.Width; x++){input_tensor[0, 0, y, x] = dstimg.At<Vec3b>(y, x)[0];input_tensor[0, 1, y, x] = dstimg.At<Vec3b>(y, x)[1];input_tensor[0, 2, y, x] = dstimg.At<Vec3b>(y, x)[2];}}dstimg.Dispose();List<NamedOnnxValue> input_container = new List<NamedOnnxValue>{NamedOnnxValue.CreateFromTensor("input", input_tensor)};//推理dt1 = DateTime.Now;var ort_outputs = onnx_session.Run(input_container).ToArray();dt2 = DateTime.Now;float[] data = Transpose(ort_outputs[0].AsTensor<float>().ToArray(), 4 + class_num, box_num);float[] confidenceInfo = new float[class_num];float[] rectData = new float[4];List<DetectionResult> detResults = new List<DetectionResult>();for (int i = 0; i < box_num; i++){Array.Copy(data, i * (class_num + 4), rectData, 0, 4);Array.Copy(data, i * (class_num + 4) + 4, confidenceInfo, 0, class_num);float score = confidenceInfo.Max(); // 获取最大值int maxIndex = Array.IndexOf(confidenceInfo, score); // 获取最大值的位置int xmin = (int)(rectData[0] / ratio);int ymin = (int)(rectData[1] / ratio);int xmax = (int)(rectData[2] / ratio);int ymax = (int)(rectData[3] / ratio);Rect box = new Rect();box.X = (int)xmin;box.Y = (int)ymin;box.Width = (int)(xmax - xmin);box.Height = (int)(ymax - ymin);detResults.Add(new DetectionResult(maxIndex,class_names[maxIndex],box,score));}//NMSCvDnn.NMSBoxes(detResults.Select(x => x.Rect), detResults.Select(x => x.Confidence), conf_threshold, nms_threshold, out int[] indices);detResults = detResults.Where((x, index) => indices.Contains(index)).ToList();sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");sb.AppendLine("------------------------------");//绘制结果Mat result_image = image.Clone();foreach (DetectionResult r in detResults){Cv2.PutText(result_image, $"{r.Class}:{r.Confidence:P0}", new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);Cv2.Rectangle(result_image, r.Rect, Scalar.Red, thickness: 2);sb.AppendLine(string.Format("{0}:{1},({2},{3},{4},{5})", r.Class, r.Confidence.ToString("P0"), r.Rect.TopLeft.X, r.Rect.TopLeft.Y, r.Rect.BottomRight.X, r.Rect.BottomRight.Y));}if (pictureBox2.Image != null){pictureBox2.Image.Dispose();}pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());result_image.Dispose();textBox1.Text = sb.ToString();button2.Enabled = true;}/// <summary>///窗体加载/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Form1_Load(object sender, EventArgs e){model_path = "model/damoyolo_cigarette.onnx";//创建输出会话,用于输出模型读取信息SessionOptions options = new SessionOptions();options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行// 创建推理模型类,读取模型文件onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径input_height = 640;input_width = 640;box_num = 8400;conf_threshold = 0.25f;nms_threshold = 0.5f;classer_path = "model/lable.txt";class_names = File.ReadAllLines(classer_path, Encoding.UTF8);class_num = class_names.Length;image_path = "test_img/2.jpg";pictureBox1.Image = new Bitmap(image_path);}/// <summary>/// 保存/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button3_Click(object sender, EventArgs e){if (pictureBox2.Image == null){return;}Bitmap output = new Bitmap(pictureBox2.Image);SaveFileDialog sdf = new SaveFileDialog();sdf.Title = "保存";sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp|Images (*.emf)|*.emf|Images (*.exif)|*.exif|Images (*.gif)|*.gif|Images (*.ico)|*.ico|Images (*.tiff)|*.tiff|Images (*.wmf)|*.wmf";if (sdf.ShowDialog() == DialogResult.OK){switch (sdf.FilterIndex){case 1:{output.Save(sdf.FileName, ImageFormat.Jpeg);break;}case 2:{output.Save(sdf.FileName, ImageFormat.Png);break;}case 3:{output.Save(sdf.FileName, ImageFormat.Bmp);break;}case 4:{output.Save(sdf.FileName, ImageFormat.Emf);break;}case 5:{output.Save(sdf.FileName, ImageFormat.Exif);break;}case 6:{output.Save(sdf.FileName, ImageFormat.Gif);break;}case 7:{output.Save(sdf.FileName, ImageFormat.Icon);break;}case 8:{output.Save(sdf.FileName, ImageFormat.Tiff);break;}case 9:{output.Save(sdf.FileName, ImageFormat.Wmf);break;}}MessageBox.Show("保存成功,位置:" + sdf.FileName);}}private void pictureBox1_DoubleClick(object sender, EventArgs e){ShowNormalImg(pictureBox1.Image);}private void pictureBox2_DoubleClick(object sender, EventArgs e){ShowNormalImg(pictureBox2.Image);}public void ShowNormalImg(Image img){if (img == null) return;frmShow frm = new frmShow();frm.Width = Screen.PrimaryScreen.Bounds.Width;frm.Height = Screen.PrimaryScreen.Bounds.Height;if (frm.Width > img.Width){frm.Width = img.Width;}if (frm.Height > img.Height){frm.Height = img.Height;}bool b = frm.richTextBox1.ReadOnly;Clipboard.SetDataObject(img, true);frm.richTextBox1.ReadOnly = false;frm.richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));frm.richTextBox1.ReadOnly = b;frm.ShowDialog();}public unsafe float[] Transpose(float[] tensorData, int rows, int cols){float[] transposedTensorData = new float[tensorData.Length];fixed (float* pTensorData = tensorData){fixed (float* pTransposedData = transposedTensorData){for (int i = 0; i < rows; i++){for (int j = 0; j < cols; j++){int index = i * cols + j;int transposedIndex = j * rows + i;pTransposedData[transposedIndex] = pTensorData[index];}}}}return transposedTensorData;}}public class DetectionResult{public DetectionResult(int ClassId, string Class, Rect Rect, float Confidence){this.ClassId = ClassId;this.Confidence = Confidence;this.Rect = Rect;this.Class = Class;}public string Class { get; set; }public int ClassId { get; set; }public float Confidence { get; set; }public Rect Rect { get; set; }}}

下载

源码下载

参考

https://modelscope.cn/models/iic/cv_tinynas_object-detection_damoyolo_cigarette/summary


http://www.ppmy.cn/embedded/169880.html

相关文章

k8s内存不足问题

所有pods占用内存 kubectl top pods -A所有nodes占用内存cpu情况 kubectl top nodes删除一些没用的服务&#xff0c;清理空间然后重新部署或者加服务器的cpu和内存

清华大学DeepSeek详细使用教程共6版免费下载

「清华北大-Deepseek使用手册」 链接&#xff1a;https://pan.quark.cn/s/98782f7d61dc 「清华大学Deepseek整理&#xff09; 1&#xff0d;6版本链接&#xff1a;https://pan.quark.cn/s/72194e32428a AI学术工具公测链接:https://pan.baidu.com/s/104w_uBB2F42Da0qnk78_ew …

接口管理工具深度对比:Apipost与Apifox在Redis/MongoDB支持上的关键差异

在现代软件开发中&#xff0c;数据库是驱动各类应用和服务运行的核心组件。无论是企业级应用、互联网服务&#xff0c;还是物联网解决方案&#xff0c;数据库的类型和数量通常都因业务需求和技术架构的复杂性而不断拓展。 与此同时&#xff0c;接口管理工具作为开发和维护这些…

解决Java项目中Maven爆红,三方包下载不下来的问题

前言 在Java项目开发过程中&#xff0c;我们经常会遇到各种依赖管理的问题。今天&#xff0c;就和大家分享一下我在处理dataease项目后端源码编译时&#xff0c;遇到三方包下载不下来的问题及详细解决过程&#xff0c;希望能帮助大家在遇到类似问题时快速解决。 一、问题背景…

AcWing 蓝桥杯集训·每日一题2025·5439. 农夫约翰真的种地

5439. 农夫约翰真的种地 题目描述 农夫约翰在他的农场种植了 N N N 个芦笋&#xff0c;编号 ( 1 ∼ N ) (1 \sim N) (1∼N)。 其中&#xff0c;第 i i i 个芦笋的初始高度为 h i h_i hi​&#xff0c;每经过一天高度会增长 a i a_i ai​。 给定一个 ( 0 ∼ N − 1 ) (0…

自学微信小程序的第八天

DAY8 1、使用动画API即可完成动画效果的制作,先通过wx.createAnimation()方法获取Animation实例,然后调用Animation实例的方法实现动画效果。 表40:wx.createAnimation()方法的常用选项 选项 类型 说明 duration number 动画持续时间,单位为毫秒,默认值为400毫秒 timing…

如何远程访问svn中的URL

简介&#xff1a; 主要opencascade相关知识学习 格言&#xff1a; 万丈高楼平地起 要远程访问 SVN&#xff08;Subversion&#xff09;仓库中的 URL&#xff0c;通常需要以下步骤和注意事项&#xff1a; 1. 确认远程 SVN 服务器的访问协议 SVN 支持多种协议访问远程仓库&…

在python语言中,请详细介绍一下比较运算符中等于符号(==)的情况?

李升伟 整理 一、有关思考 嗯&#xff0c;我现在要详细了解一下Python中的等于运算符&#xff08;&#xff09;。首先&#xff0c;我得回忆一下自己之前学过的知识&#xff0c;可能有些地方不太确定&#xff0c;需要仔细思考或者查阅资料。 首先&#xff0c;等于运算符&#…