• C# Onnx Yolov8 Detect 指纹检测


    目录

    效果

    模型信息

    项目

    代码

    数据集

    下载


    效果

    模型信息

    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: 'fingerprint'}
    ---------------------------------------------------------------

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

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

    项目

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

    数据集

    下载

    源码下载

    数据集(带标注信息)下载

  • 相关阅读:
    lLinux环境变量
    Spring Boot拦截器Interceptor
    SpringBoot-线程池ThreadPoolExecutor异步处理(包含拆分集合工具类)
    用vue实现pdf预览
    【无标题】
    基于springboot+vue实现学校田径运动会管理系统【附项目源码+论文说明】
    MVC第三波书店购物车展示页面
    17、读写锁(ReadWriteLock(里面有读锁和写锁))
    好用的word插件汇总
    vmware虚拟机安装centos7及网络配置
  • 原文地址:https://blog.csdn.net/lw112190/article/details/133939033