首页 > 编程语言 >C# Onnx Yolov8 Detect 水果识别

C# Onnx Yolov8 Detect 水果识别

时间:2023-09-27 12:35:19浏览次数:42  
标签:Detect input using C# Onnx image result path new


效果

C# Onnx Yolov8 Detect 水果识别_C#水果识别

项目

C# Onnx Yolov8 Detect 水果识别_Text_02

 代码

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

namespace Onnx_Yolov8_Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string image_path = "";
        string startupPath;
        string classer_path;
        DateTime dt1 = DateTime.Now;
        DateTime dt2 = DateTime.Now;
        string model_path;
        Mat image;
        DetectionResult result_pro;
        Mat result_image;

        SessionOptions options;
        InferenceSession onnx_session;
        Tensor<float> input_tensor;
        List<NamedOnnxValue> input_ontainer;
        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
        DisposableNamedOnnxValue[] results_onnxvalue;

        Tensor<float> result_tensors;

        float[] result_array = new float[8400 * 19];
        float[] factors = new float[2];

        Result result;
        StringBuilder sb = new StringBuilder();
        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 = "";
            image = new Mat(image_path);
            pictureBox2.Image = null;
        }

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

            // 配置图片数据
            image = new Mat(image_path);
            int max_image_length = image.Cols > image.Rows ? image.Cols : image.Rows;
            Mat max_image = Mat.Zeros(new OpenCvSharp.Size(max_image_length, max_image_length), MatType.CV_8UC3);
            Rect roi = new Rect(0, 0, image.Cols, image.Rows);
            image.CopyTo(new Mat(max_image, roi));

           
            factors[0] = factors[1] = (float)(max_image_length / 640.0);

            // 将图片转为RGB通道
            Mat image_rgb = new Mat();
            Cv2.CvtColor(max_image, image_rgb, ColorConversionCodes.BGR2RGB);
            Mat resize_image = new Mat();
            Cv2.Resize(image_rgb, resize_image, new OpenCvSharp.Size(640, 640));

            // 输入Tensor
            // input_tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 });
            for (int y = 0; y < resize_image.Height; y++)
            {
                for (int x = 0; x < resize_image.Width; x++)
                {
                    input_tensor[0, 0, y, x] = resize_image.At<Vec3b>(y, x)[0] / 255f;
                    input_tensor[0, 1, y, x] = resize_image.At<Vec3b>(y, x)[1] / 255f;
                    input_tensor[0, 2, y, x] = resize_image.At<Vec3b>(y, x)[2] / 255f;
                }
            }

            //将 input_tensor 放入一个输入参数的容器,并指定名称
            input_ontainer.Add(NamedOnnxValue.CreateFromTensor("images", input_tensor));

            dt1 = DateTime.Now;
            //运行 Inference 并获取结果
            result_infer = onnx_session.Run(input_ontainer);

            dt2 = DateTime.Now;

            // 将输出结果转为DisposableNamedOnnxValue数组
            results_onnxvalue = result_infer.ToArray();

            // 读取第一个节点输出并转为Tensor数据
            result_tensors = results_onnxvalue[0].AsTensor<float>();

            result_array = result_tensors.ToArray();

            resize_image.Dispose();
            image_rgb.Dispose();

            result_pro = new DetectionResult(classer_path, factors);
            result = result_pro.process_result(result_array);
            result_image = result_pro.draw_result(result, image.Clone());

            if (!result_image.Empty())
            {
                pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
                sb.Clear();
                sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
                sb.AppendLine("------------------------------");
                for (int i = 0; i < result.length; i++)
                {
                    sb.AppendLine(string.Format("{0}:{1},({2},{3},{4},{5})"
                        , result.classes[i]
                        , result.scores[i].ToString("0.00")
                        , result.rects[i].TopLeft.X
                        , result.rects[i].TopLeft.Y
                        , result.rects[i].BottomRight.X
                        , result.rects[i].BottomRight.Y
                        ));
                }
                textBox1.Text = sb.ToString();
            }
            else
            {
                textBox1.Text = "无信息";
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;
            model_path = startupPath + "\\fruits.onnx";
            classer_path = startupPath + "\\lable.txt";

            // 创建输出会话,用于输出模型读取信息
            options = new SessionOptions();
            options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
            // 设置为CPU上运行
            options.AppendExecutionProvider_CPU(0);

            // 创建推理模型类,读取本地模型文件
            onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径

            // 输入Tensor
            input_tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 });

            // 创建输入容器
            input_ontainer = new List<NamedOnnxValue>();

        }
    }
}

lable.txt

cucumber
apple
kiwi
banana
orange
coconut
peach
cherry
pear
pomegranate
pineapple
watermelon
melon
grape
strawberry

数据集

C# Onnx Yolov8 Detect 水果识别_Text_03

数据集下载 

Demo下载 

标签:Detect,input,using,C#,Onnx,image,result,path,new
From: https://blog.51cto.com/u_2617730/7622963

相关文章

  • C# PaddleDetection 安全帽检测
    效果项目 代码usingOpenCvSharp;usingOpenCvSharp.Extensions;usingSdcb.PaddleDetection;usingSdcb.PaddleInference;usingSystem;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingYamlDotNet;usingstaticSystem.Windows.Forms.Visual......
  • C# OpenCvSharp 图片模糊检测(拉普拉斯算子)
    效果项目代码usingOpenCvSharp;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Windows.Forms.VisualStyles;usin......
  • C# OpenCvSharp Yolov8 Detect 目标检测
    效果项目代码usingOpenCvSharp;usingOpenCvSharp.Dnn;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;namespaceOpenCvSharp......
  • 文心一言 VS 讯飞星火 VS chatgpt (96)-- 算法导论9.3 1题
    一、用go语言,在算法SELECT中,输人元素被分为每组5个元素。如果它们被分为每组7个元素,该算法仍然会是线性时间吗?证明:如果分成每组3个元素,SELECT的运行时间不是线性的。文心一言:在算法分析中,一个算法的运行时间是否线性依赖于其输入数据的大小。线性时间意味着算法的运行时......
  • 文心一言 VS 讯飞星火 VS chatgpt (97)-- 算法导论9.3 3题
    三、用go语言,假设所有元素都是互异的,说明在最坏情况下,如何才能使快速排序的运行时间为O(nlgn)。文心一言:快速排序是一种基于分治策略的排序算法,其平均时间复杂度为O(nlgn)。在最坏情况下,快速排序的时间复杂度为O(n^2),这是因为当输入数组已经排序或接近排序时,快速排序的性能会退化。......
  • 2023-09-20:用go语言,保证一定是n*n的正方形,实现从里到外转圈打印的功能 如果n是奇数,中
    2023-09-20:用go语言,保证一定是n*n的正方形,实现从里到外转圈打印的功能如果n是奇数,中心点唯一,比如abcdefghie是中心点,依次打印:efihgdabc如果n是偶数,中心点为最里层2*2的右下点比如abcdefghijklmnopqrstuvwxyz0123456789最里层是opu......
  • By.CSS_SELECTOR
    #导包fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromtimeimportsleepfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasEC#浏览器驱动driver=webdriver.Ch......
  • 27、Flink 的SQL之SELECT (Group Aggregation分组聚合、Over Aggregation Over聚合 和
    文章目录Flink系列文章一、GroupAggregation分组聚合1、count示例2、groupby的聚合示例3、distinct聚合4、GROUPINGSETS1)、ROLLUP2)、CUBE5、Having二、OverAggregation1、语法1)、ORDERBY2)、PARTITIONBY3)、RangeDefinitions4)、RANGEintervals5)、ROWintervals2、示例三、......
  • 27、Flink 的SQL之SELECT (SQL Hints 和 Joins)介绍及详细示例(2-2)
    Flink系列文章1、Flink部署、概念介绍、source、transformation、sink使用示例、四大基石介绍和示例等系列综合文章链接13、Flink的tableapi与sql的基本概念、通用api介绍及入门示例14、Flink的tableapi与sql之数据类型:内置数据类型以及它们的属性15、Flink的tableapi与s......
  • 27、Flink 的SQL之SELECT (窗口聚合)介绍及详细示例(4)
    文章目录Flink系列文章一、WindowTVFAggregation1、WindowingTVFs窗口函数1)、TUMBLE滚动窗口示例2)、HOP滑动窗口示例3)、CUMULATE累积窗口示例2、GROUPINGSETS分组集介绍及示例1)、ROLLUP介绍及示例2)、CUBE介绍及示例3、SelectingGroupWindowStartandEndTimestamps4、Cas......