• C# Onnx Yolov8 Detect 手势识别


    目录

    效果

    模型信息

    Lable

    项目

    代码

    下载 


    效果

    模型信息

    Model Properties
    -------------------------
    author:Ultralytics
    task:detect
    license:AGPL-3.0 https://ultralytics.com/license
    version:8.0.184
    stride:32
    batch:1
    imgsz:[640, 640]
    names:{0: 'five', 1: 'four', 2: 'one', 3: 'three', 4: 'two'}
    ---------------------------------------------------------------

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

    Outputs
    -------------------------
    name:output0
    tensor:Float[1, 9, 8400]
    ---------------------------------------------------------------

    Lable

    1. five
    2. four
    3. one
    4. three
    5. two

    项目

    VS2022

    .net framework 4.8

    OpenCvSharp 4.8

    Microsoft.ML.OnnxRuntime 1.16.2

    代码

    ///


    /// 结果绘制
    ///

    /// 识别结果
    /// 绘制图片
    ///
    public Mat draw_result(Result result, Mat image)
    {
        // 将识别结果绘制到图片上
        for (int i = 0; i < result.length; i++)
        {
            //Console.WriteLine(result.rects[i]);
            Cv2.Rectangle(image, result.rects[i], new Scalar(0, 0, 255), 2, LineTypes.Link8);
            
            Cv2.Rectangle(image, new Point(result.rects[i].TopLeft.X-1, result.rects[i].TopLeft.Y - 20),
                new Point(result.rects[i].BottomRight.X, result.rects[i].TopLeft.Y), new Scalar(0, 0, 255), -1);
            
            Cv2.PutText(image, result.classes[i] + "-" + result.scores[i].ToString("0.00"),
                new Point(result.rects[i].X, result.rects[i].Y - 4),
                HersheyFonts.HersheySimplex, 0.6, new Scalar(0, 0, 0), 1);
        }
        return image;
    }

    1. using Microsoft.ML.OnnxRuntime;
    2. using Microsoft.ML.OnnxRuntime.Tensors;
    3. using OpenCvSharp;
    4. using System;
    5. using System.Collections.Generic;
    6. using System.ComponentModel;
    7. using System.Data;
    8. using System.Drawing;
    9. using System.Linq;
    10. using System.Text;
    11. using System.Windows.Forms;
    12. using static System.Net.Mime.MediaTypeNames;
    13. namespace Onnx_Yolov8_Demo
    14. {
    15. public partial class Form1 : Form
    16. {
    17. public Form1()
    18. {
    19. InitializeComponent();
    20. }
    21. string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
    22. string image_path = "";
    23. string startupPath;
    24. string classer_path;
    25. DateTime dt1 = DateTime.Now;
    26. DateTime dt2 = DateTime.Now;
    27. string model_path;
    28. Mat image;
    29. DetectionResult result_pro;
    30. Mat result_image;
    31. SessionOptions options;
    32. InferenceSession onnx_session;
    33. Tensor<float> input_tensor;
    34. List<NamedOnnxValue> input_ontainer;
    35. IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
    36. DisposableNamedOnnxValue[] results_onnxvalue;
    37. Tensor<float> result_tensors;
    38. float[] result_array = new float[8400 * 9];
    39. float[] factors = new float[2];
    40. Result result;
    41. StringBuilder sb = new StringBuilder();
    42. private void button1_Click(object sender, EventArgs e)
    43. {
    44. OpenFileDialog ofd = new OpenFileDialog();
    45. ofd.Filter = fileFilter;
    46. if (ofd.ShowDialog() != DialogResult.OK) return;
    47. pictureBox1.Image = null;
    48. image_path = ofd.FileName;
    49. pictureBox1.Image = new Bitmap(image_path);
    50. textBox1.Text = "";
    51. image = new Mat(image_path);
    52. pictureBox2.Image = null;
    53. }
    54. private void button2_Click(object sender, EventArgs e)
    55. {
    56. if (image_path == "")
    57. {
    58. return;
    59. }
    60. // 配置图片数据
    61. image = new Mat(image_path);
    62. int max_image_length = image.Cols > image.Rows ? image.Cols : image.Rows;
    63. Mat max_image = Mat.Zeros(new OpenCvSharp.Size(max_image_length, max_image_length), MatType.CV_8UC3);
    64. Rect roi = new Rect(0, 0, image.Cols, image.Rows);
    65. image.CopyTo(new Mat(max_image, roi));
    66. factors[0] = factors[1] = (float)(max_image_length / 640.0);
    67. // 将图片转为RGB通道
    68. Mat image_rgb = new Mat();
    69. Cv2.CvtColor(max_image, image_rgb, ColorConversionCodes.BGR2RGB);
    70. Mat resize_image = new Mat();
    71. Cv2.Resize(image_rgb, resize_image, new OpenCvSharp.Size(640, 640));
    72. // 输入Tensor
    73. // input_tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 });
    74. for (int y = 0; y < resize_image.Height; y++)
    75. {
    76. for (int x = 0; x < resize_image.Width; x++)
    77. {
    78. input_tensor[0, 0, y, x] = resize_image.At<Vec3b>(y, x)[0] / 255f;
    79. input_tensor[0, 1, y, x] = resize_image.At<Vec3b>(y, x)[1] / 255f;
    80. input_tensor[0, 2, y, x] = resize_image.At<Vec3b>(y, x)[2] / 255f;
    81. }
    82. }
    83. //input_tensor 放入一个输入参数的容器,并指定名称
    84. input_ontainer.Add(NamedOnnxValue.CreateFromTensor("images", input_tensor));
    85. dt1 = DateTime.Now;
    86. //运行 Inference 并获取结果
    87. result_infer = onnx_session.Run(input_ontainer);
    88. dt2 = DateTime.Now;
    89. // 将输出结果转为DisposableNamedOnnxValue数组
    90. results_onnxvalue = result_infer.ToArray();
    91. // 读取第一个节点输出并转为Tensor数据
    92. result_tensors = results_onnxvalue[0].AsTensor<float>();
    93. result_array = result_tensors.ToArray();
    94. resize_image.Dispose();
    95. image_rgb.Dispose();
    96. result_pro = new DetectionResult(classer_path, factors);
    97. result = result_pro.process_result(result_array);
    98. result_image = result_pro.draw_result(result, image.Clone());
    99. if (!result_image.Empty())
    100. {
    101. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
    102. sb.Clear();
    103. sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
    104. sb.AppendLine("------------------------------");
    105. for (int i = 0; i < result.length; i++)
    106. {
    107. sb.AppendLine(string.Format("{0}:{1},({2},{3},{4},{5})"
    108. , result.classes[i]
    109. , result.scores[i].ToString("0.00")
    110. , result.rects[i].TopLeft.X
    111. , result.rects[i].TopLeft.Y
    112. , result.rects[i].BottomRight.X
    113. , result.rects[i].BottomRight.Y
    114. ));
    115. }
    116. textBox1.Text = sb.ToString();
    117. }
    118. else
    119. {
    120. textBox1.Text = "无信息";
    121. }
    122. }
    123. private void Form1_Load(object sender, EventArgs e)
    124. {
    125. startupPath = System.Windows.Forms.Application.StartupPath;
    126. model_path = startupPath + "\\HandGesture.onnx";
    127. classer_path = startupPath + "\\lable.txt";
    128. // 创建输出会话,用于输出模型读取信息
    129. options = new SessionOptions();
    130. options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
    131. // 设置为CPU上运行
    132. options.AppendExecutionProvider_CPU(0);
    133. // 创建推理模型类,读取本地模型文件
    134. onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径
    135. // 输入Tensor
    136. input_tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 });
    137. // 创建输入容器
    138. input_ontainer = new List<NamedOnnxValue>();
    139. }
    140. }
    141. }

    下载 

    Demo下载

    数据集下载

  • 相关阅读:
    java毕业设计毕业论文管理系统Mybatis+系统+数据库+调试部署
    妈妈再也不用担心我搞不懂——log4j/logback/log4j2原理了
    2.docker镜像的导入导出
    【JAVA知识梳理】泛型详解
    用matlab做bp神经网络预测,神经网络预测matlab代码
    3516DV300 推流
    LeetCode:88. 合并两个有序数组
    宏集新闻 | 虹科传感器事业部正式更名为宏集科技
    spring源码解析——IOC之bean创建
    java计算机毕业设计ssm特大城市地铁站卫生防疫系统5i80c(附源码、数据库)
  • 原文地址:https://blog.csdn.net/lw112190/article/details/133386449