• C# Onnx Yolov8 Fire Detect 火焰识别,火灾检测


    目录

    效果

    ​模型信息

    项目

    ​代码

    下载 


    效果

    模型信息

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

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

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

    项目

    代码

    ///


    /// 结果绘制
    ///

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

    下载 

    源码下载

  • 相关阅读:
    比较含退格的字符串+每日温度
    KeyDB源码解析四——其他特性
    whisper large-v3 模型文件下载链接
    【C语言初学者周冲刺计划】5.2一个二维数组中的鞍点
    Redis注解式开发结合SSM项目使用与Quartz框架介绍以及击穿、穿透、雪崩问题解决
    VivadoAndTcl: synth_ip
    【C#/.NET】Dapper使用QueryMultipleAsync执行多条SQL
    SimpleChannelInboundHandler使用总结
    51种企业应用架构模式详解
    【CT】LeetCode手撕—42. 接雨水
  • 原文地址:https://blog.csdn.net/lw112190/article/details/132873810