首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

C# OnnxRuntime YoloV5 Demo

  • 25-02-19 03:41
  • 3317
  • 14009
blog.csdn.net

目录

效果

模型信息

项目

代码

Form1.cs

YoloV5.cs

下载


效果

模型信息

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

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

Outputs
-------------------------
name:output
tensor:Float[1, 25200, 85]
name:350
tensor:Float[1, 3, 80, 80, 85]
name:416
tensor:Float[1, 3, 40, 40, 85]
name:482
tensor:Float[1, 3, 20, 20, 85]
---------------------------------------------------------------

项目

代码

Form1.cs

using OpenCvSharp;
using System;
using System.Drawing;
using System.Drawing.Imaging;
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 startupPath;
        DateTime dt1 = DateTime.Now;
        DateTime dt2 = DateTime.Now;
        Mat image;
        Mat result_image;
        YoloV5 yoloV5;

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

        private void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }

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

            //读图片
            image = Cv2.ImRead(image_path);
          
            float confidence = 0.4f;
            if (!float.TryParse(txtConfidence.Text,out confidence))
            {
                confidence = 0.4f;
            }

            dt1 = DateTime.Now;
            var detResults = yoloV5.Detect(image, confidence);
            dt2 = DateTime.Now;

            result_image = image.Clone();
            image.Dispose();

            StringBuilder sb=new StringBuilder();

            foreach (DetectionResult r in detResults)
            {
                string info = $"{r.Class}:{r.Confidence:P0}";
                //绘制
                Cv2.PutText(result_image, info, 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(info);
            }

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            result_image.Dispose();
            textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms\r\n";
            textBox1.Text += "---------------------------\r\n";
            textBox1.Text += sb.ToString();

            button2.Enabled = true;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;
            yoloV5 = new YoloV5("model/yolov5n.onnx", "model/lable.txt");

            image_path = "test_img/dog.jpg";
            pictureBox1.Image = new Bitmap(image_path);
            image = new Mat(image_path);
        }

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

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

        SaveFileDialog sdf = new SaveFileDialog();
        private void button3_Click(object sender, EventArgs e)
        {
            if (pictureBox2.Image == null)
            {
                return;
            }
            Bitmap output = new Bitmap(pictureBox2.Image);
            sdf.Title = "保存";
            sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp";
            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;
                        }
                }
                MessageBox.Show("保存成功,位置:" + sdf.FileName);
            }
        }
    }
}

  1. using OpenCvSharp;
  2. using System;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.Text;
  6. using System.Windows.Forms;
  7. namespace Onnx_Demo
  8. {
  9. public partial class Form1 : Form
  10. {
  11. public Form1()
  12. {
  13. InitializeComponent();
  14. }
  15. string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  16. string image_path = "";
  17. string startupPath;
  18. DateTime dt1 = DateTime.Now;
  19. DateTime dt2 = DateTime.Now;
  20. Mat image;
  21. Mat result_image;
  22. YoloV5 yoloV5;
  23. private void button1_Click(object sender, EventArgs e)
  24. {
  25. OpenFileDialog ofd = new OpenFileDialog();
  26. ofd.Filter = fileFilter;
  27. if (ofd.ShowDialog() != DialogResult.OK) return;
  28. pictureBox1.Image = null;
  29. image_path = ofd.FileName;
  30. pictureBox1.Image = new Bitmap(image_path);
  31. textBox1.Text = "";
  32. pictureBox2.Image = null;
  33. }
  34. private void button2_Click(object sender, EventArgs e)
  35. {
  36. if (image_path == "")
  37. {
  38. return;
  39. }
  40. button2.Enabled = false;
  41. pictureBox2.Image = null;
  42. textBox1.Text = "";
  43. Application.DoEvents();
  44. //读图片
  45. image = Cv2.ImRead(image_path);
  46. float confidence = 0.4f;
  47. if (!float.TryParse(txtConfidence.Text,out confidence))
  48. {
  49. confidence = 0.4f;
  50. }
  51. dt1 = DateTime.Now;
  52. var detResults = yoloV5.Detect(image, confidence);
  53. dt2 = DateTime.Now;
  54. result_image = image.Clone();
  55. image.Dispose();
  56. StringBuilder sb=new StringBuilder();
  57. foreach (DetectionResult r in detResults)
  58. {
  59. string info = $"{r.Class}:{r.Confidence:P0}";
  60. //绘制
  61. Cv2.PutText(result_image, info, new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  62. Cv2.Rectangle(result_image, r.Rect, Scalar.Red, thickness: 2);
  63. sb.AppendLine(info);
  64. }
  65. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  66. result_image.Dispose();
  67. textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms\r\n";
  68. textBox1.Text += "---------------------------\r\n";
  69. textBox1.Text += sb.ToString();
  70. button2.Enabled = true;
  71. }
  72. private void Form1_Load(object sender, EventArgs e)
  73. {
  74. startupPath = System.Windows.Forms.Application.StartupPath;
  75. yoloV5 = new YoloV5("model/yolov5n.onnx", "model/lable.txt");
  76. image_path = "test_img/dog.jpg";
  77. pictureBox1.Image = new Bitmap(image_path);
  78. image = new Mat(image_path);
  79. }
  80. private void pictureBox1_DoubleClick(object sender, EventArgs e)
  81. {
  82. Common.ShowNormalImg(pictureBox1.Image);
  83. }
  84. private void pictureBox2_DoubleClick(object sender, EventArgs e)
  85. {
  86. Common.ShowNormalImg(pictureBox2.Image);
  87. }
  88. SaveFileDialog sdf = new SaveFileDialog();
  89. private void button3_Click(object sender, EventArgs e)
  90. {
  91. if (pictureBox2.Image == null)
  92. {
  93. return;
  94. }
  95. Bitmap output = new Bitmap(pictureBox2.Image);
  96. sdf.Title = "保存";
  97. sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp";
  98. if (sdf.ShowDialog() == DialogResult.OK)
  99. {
  100. switch (sdf.FilterIndex)
  101. {
  102. case 1:
  103. {
  104. output.Save(sdf.FileName, ImageFormat.Jpeg);
  105. break;
  106. }
  107. case 2:
  108. {
  109. output.Save(sdf.FileName, ImageFormat.Png);
  110. break;
  111. }
  112. case 3:
  113. {
  114. output.Save(sdf.FileName, ImageFormat.Bmp);
  115. break;
  116. }
  117. }
  118. MessageBox.Show("保存成功,位置:" + sdf.FileName);
  119. }
  120. }
  121. }
  122. }

YoloV5.cs

  1. using Microsoft.ML.OnnxRuntime;
  2. using Microsoft.ML.OnnxRuntime.Tensors;
  3. using OpenCvSharp;
  4. using OpenCvSharp.Dnn;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. namespace Onnx_Demo
  11. {
  12. internal class YoloV5
  13. {
  14. float[] input_image;
  15. int inpWidth = 640;
  16. int inpHeight = 640;
  17. float confThreshold;
  18. float nmsThreshold;
  19. List<string> classes;
  20. SessionOptions options;
  21. InferenceSession onnx_session;
  22. public YoloV5(string modelPath, string classesPath)
  23. {
  24. confThreshold = 0.5f;
  25. nmsThreshold = 0.5f;
  26. classes = File.ReadAllLines(classesPath, Encoding.UTF8).ToList();
  27. options = new SessionOptions();
  28. options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
  29. options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行
  30. // 创建推理模型类,读取本地模型文件
  31. onnx_session = new InferenceSession(modelPath, options);
  32. }
  33. public List<DetectionResult> Detect(Mat frame, float confidence)
  34. {
  35. float ratio = 0.0f;
  36. confThreshold = confidence;
  37. List<DetectionResult> detResults = new List<DetectionResult>();
  38. int max_image_length = frame.Cols > frame.Rows ? frame.Cols : frame.Rows;
  39. Mat max_image = Mat.Zeros(new OpenCvSharp.Size(max_image_length, max_image_length), MatType.CV_8UC3);
  40. Rect roi = new Rect(0, 0, frame.Cols, frame.Rows);
  41. frame.CopyTo(new Mat(max_image, roi));
  42. Cv2.CvtColor(max_image, max_image, ColorConversionCodes.BGR2RGB);
  43. Cv2.Resize(max_image, max_image, new Size(inpWidth, inpHeight));
  44. ratio = (float)(max_image_length / 640.0);
  45. max_image.ConvertTo(max_image, MatType.CV_32FC3, (float)(1 / 255.0));
  46. var input = new DenseTensor<float>(Common.ExtractMat(max_image), new[] { 1, 3, inpHeight, inpWidth });
  47. max_image.Dispose();
  48. // Setup inputs and outputs
  49. var inputs = new List<NamedOnnxValue>
  50. {
  51. NamedOnnxValue.CreateFromTensor("images", input)
  52. };
  53. var results = onnx_session.Run(inputs);
  54. //Postprocessing
  55. var resultsArray = results.ToArray();
  56. var pred_value = resultsArray[0].AsEnumerable<float>().ToArray();
  57. var pred_dim = resultsArray[0].AsTensor<float>().Dimensions.ToArray();
  58. var nc = pred_dim[pred_dim.Length - 1] - 5;
  59. var candidate = Common.GetCandidate(pred_value, pred_dim, confThreshold);
  60. //Compute conf
  61. for (int i = 0; i < candidate.Count; i++)
  62. {
  63. var obj_cnf = candidate[i][4];
  64. for (int j = 5; j < candidate[i].Count; j++)
  65. {
  66. candidate[i][j] *= obj_cnf;
  67. }
  68. }
  69. float[] confidenceInfo = new float[nc];
  70. float[] rectData = new float[4];
  71. for (int i = 0; i < candidate.Count; i++)
  72. {
  73. Array.Copy(candidate[i].ToArray(), 0, rectData, 0, 4);
  74. Array.Copy(candidate[i].ToArray(), 5, confidenceInfo, 0, nc);
  75. float score = confidenceInfo.Max(); // 获取最大值
  76. int maxIndex = Array.IndexOf(confidenceInfo, score); // 获取最大值的位置
  77. int _centerX = (int)(rectData[0] * ratio);
  78. int _centerY = (int)(rectData[1] * ratio);
  79. int _width = (int)(rectData[2] * ratio);
  80. int _height = (int)(rectData[3] * ratio);
  81. detResults.Add(new DetectionResult(
  82. maxIndex,
  83. classes[maxIndex],
  84. new Rect(_centerX - _width / 2, _centerY - _height / 2, _width, _height),
  85. score));
  86. }
  87. //NMS
  88. CvDnn.NMSBoxes(detResults.Select(x => x.Rect), detResults.Select(x => x.Confidence), confThreshold, nmsThreshold, out int[] indices);
  89. detResults = detResults.Where((x, index) => indices.Contains(index)).ToList();
  90. return detResults;
  91. }
  92. }
  93. }

下载

源码下载

天天代码码天天
微信公众号
.NET 人工智能实践
注:本文转载自blog.csdn.net的天天代码码天天的文章"https://lw112190.blog.csdn.net/article/details/141286935"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top