当前位置:   article > 正文

C# Onnx Yolov8 Detect 红绿灯检测_c# yolov8 缺陷检测

c# yolov8 缺陷检测

目录

效果

模型信息

lable

项目

​编辑

代码

下载


效果

模型信息

Model Properties
-------------------------
author:Ultralytics
task:detect
license:AGPL-3.0 https://ultralytics.com/license
version:8.0.172
stride:32
batch:1
imgsz:[640, 640]
names:{0: 'GreenCircular', 1: 'GreenLeft', 2: 'GreenRight', 3: 'GreenStraight', 4: 'RedCircular', 5: 'RedLeft', 6: 'RedRight', 7: 'RedStraight'}
---------------------------------------------------------------

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

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

lable

  1. GreenCircular
  2. GreenLeft
  3. GreenRight
  4. GreenStraight
  5. RedCircular
  6. RedLeft
  7. RedRight
  8. RedStraight

项目

VS2022

.net framework 4.8

OpenCvSharp 4.8

Microsoft.ML.OnnxRuntime 1.16.2

代码

/// <summary>
/// 结果绘制
/// </summary>
/// <param name="result">识别结果</param>
/// <param name="image">绘制图片</param>
/// <returns></returns>
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 + "traffic-lights.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);
  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. }
  139. }

下载

源码下载

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/749356
推荐阅读
相关标签
  

闽ICP备14008679号