C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测

目录

效果

模型信息

项目

代码 

下载


C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测

效果

模型信息

Inputs
-------------------------
name:image
tensor:Float[1, 3, 640, 640]
name:scale_factor
tensor:Float[1, 2]
---------------------------------------------------------------

Outputs
-------------------------
name:multiclass_nms3_0.tmp_0
tensor:Float[-1, 6]
name:multiclass_nms3_0.tmp_2
tensor:Int32[1]
---------------------------------------------------------------

项目

VS2022

.net framework 4.8

OpenCvSharp 4.8

Microsoft.ML.OnnxRuntime 1.16.2

代码 

using Microsoft.ML.OnnxRuntime.Tensors;
using Microsoft.ML.OnnxRuntime;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Drawing;
using System.IO;
using System.Text;

namespace Onnx_Demo
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string image_path = "";

        DateTime dt1 = DateTime.Now;
        DateTime dt2 = DateTime.Now;

        float confThreshold = 0.5f;

        int inpWidth;
        int inpHeight;

        Mat image;

        string model_path = "";

        SessionOptions options;
        InferenceSession onnx_session;
        Tensor<float> input_tensor;
        Tensor<float> input_tensor_scale;
        List<NamedOnnxValue> input_container;

        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
        DisposableNamedOnnxValue[] results_onnxvalue;

        List<string> class_names;
        int num_class;

        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;
            pictureBox2.Image = null;
            textBox1.Text = "";

            image_path = ofd.FileName;
            pictureBox1.Image = new System.Drawing.Bitmap(image_path);
            image = new Mat(image_path);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 创建输入容器
            input_container = new List<NamedOnnxValue>();

            // 创建输出会话
            options = new SessionOptions();
            options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
            options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行

            // 创建推理模型类,读取本地模型文件
            model_path = "model/ppyoloe_plus_crn_s_80e_coco_640x640.onnx";

            inpHeight = 640;
            inpWidth = 640;

            onnx_session = new InferenceSession(model_path, options);

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

            image_path = "test_img/bus.jpg";
            pictureBox1.Image = new Bitmap(image_path);

            class_names = new List<string>();
            StreamReader sr = new StreamReader("coco.names");
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                class_names.Add(line);
            }
            num_class = class_names.Count();

        }

        private unsafe void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }
            textBox1.Text = "检测中,请稍等……";
            pictureBox2.Image = null;
            sb.Clear();
            System.Windows.Forms.Application.DoEvents();

            image = new Mat(image_path);
            //-----------------前处理--------------------------
            Mat dstimg = new Mat();
            float ratio = Math.Min(inpHeight * 1.0f / image.Rows, inpWidth * 1.0f / image.Cols);
            int neww = (int)(image.Cols * ratio);
            int newh = (int)(image.Rows * ratio);
            Cv2.CvtColor(image, dstimg, ColorConversionCodes.BGR2RGB);
            Cv2.Resize(dstimg, dstimg, new OpenCvSharp.Size(neww, newh));
            Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant, new Scalar(1));
            //Cv2.ImShow("dstimg", dstimg);

            int row = dstimg.Rows;
            int col = dstimg.Cols;
            float[] input_tensor_data = new float[1 * 3 * row * col];
            for (int c = 0; c < 3; c++)
            {
                for (int i = 0; i < row; i++)
                {
                    for (int j = 0; j < col; j++)
                    {
                        byte pix = ((byte*)(dstimg.Ptr(i).ToPointer()))[j * 3 + c];
                        input_tensor_data[c * row * col + i * col + j] = (float)(pix / 255.0);
                    }
                }
            }

            input_tensor = new DenseTensor<float>(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });
            input_tensor_scale = new DenseTensor<float>(new float[] { 1, 1 }, new[] { 1, 2 });
            input_container.Add(NamedOnnxValue.CreateFromTensor("image", input_tensor));
            input_container.Add(NamedOnnxValue.CreateFromTensor("scale_factor", input_tensor_scale));

            //-----------------推理--------------------------
            dt1 = DateTime.Now;
            result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果
            dt2 = DateTime.Now;

            //-----------------后处理--------------------------
            results_onnxvalue = result_infer.ToArray();
            int nout = results_onnxvalue[0].AsTensor<float>().Dimensions[1];
            float[] outs = results_onnxvalue[0].AsTensor<float>().ToArray();
            int[] box_num = results_onnxvalue[1].AsTensor<int>().ToArray();
            List<float> confidences = new List<float>();
            List<Rect> position_boxes = new List<Rect>();
            List<int> class_ids = new List<int>();
            Result result = new Result();

            for (int i = 0; i < box_num[0]; i++)
            {
                if (outs[0 + nout * i] > -1 && outs[1 + nout * i] > confThreshold)
                {
                    class_ids.Add((int)outs[0 + nout * i]);

                    confidences.Add(outs[1 + nout * i]);

                    float xmin = outs[2 + nout * i] / ratio;
                    float ymin = outs[3 + nout * i] / ratio;
                    float xmax = outs[4 + nout * i] / ratio;
                    float ymax = outs[5 + nout * i] / ratio;

                    Rect box = new Rect();
                    box.X = (int)xmin;
                    box.Y = (int)ymin;
                    box.Width = (int)(xmax - xmin);
                    box.Height = (int)(ymax - ymin);

                    position_boxes.Add(box);
                }
            }

            for (int i = 0; i < position_boxes.Count; i++)
            {
                int index = i;
                result.add(confidences[index], position_boxes[index], class_names[class_ids[index]]);
            }

            if (pictureBox2.Image != null)
            {
                pictureBox2.Image.Dispose();
            }

            sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
            sb.AppendLine("------------------------------");

            // 将识别结果绘制到图片上
            Mat result_image = image.Clone();
            for (int i = 0; i < result.length; i++)
            {
                Cv2.Rectangle(result_image, result.rects[i], new Scalar(0, 0, 255), 2, LineTypes.Link8);

                Cv2.Rectangle(result_image, new OpenCvSharp.Point(result.rects[i].TopLeft.X - 1, result.rects[i].TopLeft.Y - 20),
                    new OpenCvSharp.Point(result.rects[i].BottomRight.X, result.rects[i].TopLeft.Y), new Scalar(0, 0, 255), -1);

                Cv2.PutText(result_image, result.classes[i] + "-" + result.scores[i].ToString("0.00"),
                    new OpenCvSharp.Point(result.rects[i].X, result.rects[i].Y - 4),
                    HersheyFonts.HersheySimplex, 0.6, new Scalar(0, 0, 0), 1);

                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();
            pictureBox2.Image = new System.Drawing.Bitmap(result_image.ToMemoryStream());

            result_image.Dispose();
            dstimg.Dispose();
            image.Dispose();

        }

        private void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
            Common.ShowNormalImg(pictureBox2.Image);
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            Common.ShowNormalImg(pictureBox1.Image);
        }
    }
}

using Microsoft.ML.OnnxRuntime.Tensors;
using Microsoft.ML.OnnxRuntime;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Drawing;
using System.IO;
using System.Text;namespace Onnx_Demo
{public partial class frmMain : Form{public frmMain(){InitializeComponent();}string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";string image_path = "";DateTime dt1 = DateTime.Now;DateTime dt2 = DateTime.Now;float confThreshold = 0.5f;int inpWidth;int inpHeight;Mat image;string model_path = "";SessionOptions options;InferenceSession onnx_session;Tensor<float> input_tensor;Tensor<float> input_tensor_scale;List<NamedOnnxValue> input_container;IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;DisposableNamedOnnxValue[] results_onnxvalue;List<string> class_names;int num_class;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;pictureBox2.Image = null;textBox1.Text = "";image_path = ofd.FileName;pictureBox1.Image = new System.Drawing.Bitmap(image_path);image = new Mat(image_path);}private void Form1_Load(object sender, EventArgs e){// 创建输入容器input_container = new List<NamedOnnxValue>();// 创建输出会话options = new SessionOptions();options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行// 创建推理模型类,读取本地模型文件model_path = "model/ppyoloe_plus_crn_s_80e_coco_640x640.onnx";inpHeight = 640;inpWidth = 640;onnx_session = new InferenceSession(model_path, options);// 创建输入容器input_container = new List<NamedOnnxValue>();image_path = "test_img/bus.jpg";pictureBox1.Image = new Bitmap(image_path);class_names = new List<string>();StreamReader sr = new StreamReader("coco.names");string line;while ((line = sr.ReadLine()) != null){class_names.Add(line);}num_class = class_names.Count();}private unsafe void button2_Click(object sender, EventArgs e){if (image_path == ""){return;}textBox1.Text = "检测中,请稍等……";pictureBox2.Image = null;sb.Clear();System.Windows.Forms.Application.DoEvents();image = new Mat(image_path);//-----------------前处理--------------------------Mat dstimg = new Mat();float ratio = Math.Min(inpHeight * 1.0f / image.Rows, inpWidth * 1.0f / image.Cols);int neww = (int)(image.Cols * ratio);int newh = (int)(image.Rows * ratio);Cv2.CvtColor(image, dstimg, ColorConversionCodes.BGR2RGB);Cv2.Resize(dstimg, dstimg, new OpenCvSharp.Size(neww, newh));Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant, new Scalar(1));//Cv2.ImShow("dstimg", dstimg);int row = dstimg.Rows;int col = dstimg.Cols;float[] input_tensor_data = new float[1 * 3 * row * col];for (int c = 0; c < 3; c++){for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){byte pix = ((byte*)(dstimg.Ptr(i).ToPointer()))[j * 3 + c];input_tensor_data[c * row * col + i * col + j] = (float)(pix / 255.0);}}}input_tensor = new DenseTensor<float>(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });input_tensor_scale = new DenseTensor<float>(new float[] { 1, 1 }, new[] { 1, 2 });input_container.Add(NamedOnnxValue.CreateFromTensor("image", input_tensor));input_container.Add(NamedOnnxValue.CreateFromTensor("scale_factor", input_tensor_scale));//-----------------推理--------------------------dt1 = DateTime.Now;result_infer = onnx_session.Run(input_container);//运行 Inference 并获取结果dt2 = DateTime.Now;//-----------------后处理--------------------------results_onnxvalue = result_infer.ToArray();int nout = results_onnxvalue[0].AsTensor<float>().Dimensions[1];float[] outs = results_onnxvalue[0].AsTensor<float>().ToArray();int[] box_num = results_onnxvalue[1].AsTensor<int>().ToArray();List<float> confidences = new List<float>();List<Rect> position_boxes = new List<Rect>();List<int> class_ids = new List<int>();Result result = new Result();for (int i = 0; i < box_num[0]; i++){if (outs[0 + nout * i] > -1 && outs[1 + nout * i] > confThreshold){class_ids.Add((int)outs[0 + nout * i]);confidences.Add(outs[1 + nout * i]);float xmin = outs[2 + nout * i] / ratio;float ymin = outs[3 + nout * i] / ratio;float xmax = outs[4 + nout * i] / ratio;float ymax = outs[5 + nout * i] / ratio;Rect box = new Rect();box.X = (int)xmin;box.Y = (int)ymin;box.Width = (int)(xmax - xmin);box.Height = (int)(ymax - ymin);position_boxes.Add(box);}}for (int i = 0; i < position_boxes.Count; i++){int index = i;result.add(confidences[index], position_boxes[index], class_names[class_ids[index]]);}if (pictureBox2.Image != null){pictureBox2.Image.Dispose();}sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");sb.AppendLine("------------------------------");// 将识别结果绘制到图片上Mat result_image = image.Clone();for (int i = 0; i < result.length; i++){Cv2.Rectangle(result_image, result.rects[i], new Scalar(0, 0, 255), 2, LineTypes.Link8);Cv2.Rectangle(result_image, new OpenCvSharp.Point(result.rects[i].TopLeft.X - 1, result.rects[i].TopLeft.Y - 20),new OpenCvSharp.Point(result.rects[i].BottomRight.X, result.rects[i].TopLeft.Y), new Scalar(0, 0, 255), -1);Cv2.PutText(result_image, result.classes[i] + "-" + result.scores[i].ToString("0.00"),new OpenCvSharp.Point(result.rects[i].X, result.rects[i].Y - 4),HersheyFonts.HersheySimplex, 0.6, new Scalar(0, 0, 0), 1);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();pictureBox2.Image = new System.Drawing.Bitmap(result_image.ToMemoryStream());result_image.Dispose();dstimg.Dispose();image.Dispose();}private void pictureBox2_DoubleClick(object sender, EventArgs e){Common.ShowNormalImg(pictureBox2.Image);}private void pictureBox1_DoubleClick(object sender, EventArgs e){Common.ShowNormalImg(pictureBox1.Image);}}
}

下载

源码下载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/186419.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Redis 基本命令

使用 Redis 字符串、列表和集合的常用命令完成任务分配的后端处理逻辑。 相关知识 你需要掌握&#xff1a;1&#xff0e;常用字符串命令&#xff0c;2&#xff0e;常用列表命令&#xff0c;3&#xff0e;常用集合命令。 常用字符串命令 Redis 的字符串可以存储三种类型的值…

服务器之间的conda环境迁移

有的时候python环境中可能包含了我们编译好的很多库文件&#xff0c;如果在别的服务器想直接使用环境就会比较困难些。最好的办法就是直接迁移环境。而传统的迁移方法导出“*.yaml”环境配置的这种方法&#xff0c;实际是需要重新安装环境&#xff0c;对于这种安装好的环境是不…

数据结构:图文详解顺序表的各种操作(新增元素,查找元素,删除元素,给指定位置元素赋值)

目录 一.顺序表的概念 二.顺序表的实现 新增元素 默认尾部新增 指定位置添加元素 查找元素 查找是否存在 查找元素对应的位置 查找指定位置对应的元素 删除元素 获取顺序表长度 清空顺序表 一.顺序表的概念 在线性数据结构中&#xff0c;我们一般分为俩类&#xf…

在Transformer模型中, Positional Encoding的破坏性分析

在Transformer模型中&#xff0c;Word Embedding 被加上一个Positional Encoding&#xff0c;是否会破坏原来的Word Embedding 的含义 Sinusoidal Positional Encoding的破坏性可以从两个方面来分析&#xff1a;一是对Word Embedding的语义信息的破坏&#xff0c;二是对Word Em…

程序员也需要养生——程序员睡不好,重视一下你的情绪吧

程序员也需要养生——程序员睡不好&#xff0c;重视一下你的情绪吧 睡眠是一个复杂的系统工程&#xff0c;可以促进生长发育&#xff0c;修复受损的组织。促进大脑细胞的修复等等。在情绪的失调会影响到我们的睡眠状况。 一、心情差&#xff0c;压力大&#xff0c;睡不好跟这…

项目设计---MQ

文章目录 一. 项目描述二. 核心技术三. 需求分析概要设计四. 详细设计4.1 服务器模块4.1.1 内存管理4.1.2 硬盘管理4.1.2.1 数据库管理4.1.2.2 文件管理 4.1.3 消息转发 4.2 客户端模块4.2.1 连接管理4.2.2 信道管理 4.3 公共模块4.3.1 通信协议4.3.2 序列化/反序列化 一. 项目…

利润大增,MAU膝斩,谋求转型的新氧头顶“荆棘王冠”

撰稿|行星 来源|贝多财经 近日&#xff0c;医疗美容服务平台新氧科技&#xff08;NASDAQ:SY&#xff0c;下称“新氧”&#xff09;发布了2023年第三季度未经审计的财务业绩报告。 财报显示&#xff0c;新氧于2023年第三季度实现收入3.85亿元&#xff0c;同比增长19.2%&#x…

【redis数据结构和高性能原理】

文章目录 Redis的单线程和高性能Redis是单线程吗&#xff1f;Redis 单线程为什么还能这么快&#xff1f;Redis 单线程如何处理那么多的并发客户端连接&#xff1f; Redis的单线程和高性能 Redis是单线程吗&#xff1f; Redis 的单线程主要是指 Redis 的网络 IO 和键值对读写是…

【玩转 EdgeOne】| 腾讯云下一代边缘加速CDN EdgeOne 是安全加速界的未来吗?

目录 前言边缘加速与安全加固边缘计算与CDN的融合EdgeOne优秀的安全特性EdgeOne卓越的性能表现灵活的配置和管理生态系统的支持与发展技术创新与未来展望EdgeOne试用结束语 前言 在当下互联网的迅猛发展的时刻&#xff0c;云计算和边缘计算技术的快速发展为网络加速领域带来了…

Linux下查看目录大小

查看目录大小 Linux下查看当前目录大小&#xff0c;可用一下命令&#xff1a; du -h --max-depth1它会从下到大的显示文件的大小。

WARNING: Access control is not enabled for the database.

MongoDB shell version v3.4.24 WARNING: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted. 1)未启用访问控制 2)读写访问不受限制 D:\MongoDB\Server\3.4\bin>mongo MongoDB shell version v3.4.24 c…

【Vulnhub 靶场】【DriftingBlues: 9 (final)】【简单】【20210509】

1、环境介绍 靶场介绍&#xff1a;https://www.vulnhub.com/entry/driftingblues-9-final,695/ 靶场下载&#xff1a;https://download.vulnhub.com/driftingblues/driftingblues9.ova 靶场难度&#xff1a;简单 发布日期&#xff1a;2021年05月09日 文件大小&#xff1a;738 …

2023.11.27 滴滴P0级故障或为k8s升级造成

滴滴11.27 P0级故障|打车|宕机|网约车|出租车|滴滴出行|系统故障_网易订阅 (163.com) 如何看待滴滴11月27日故障&#xff0c;对日常生产生活有哪些影响&#xff1f; - 知乎 (zhihu.com) 最新消息滴滴P0故障原因&#xff0c;是由于k8s集群升级导致的&#xff0c;后面又进行版本…

每日OJ题_算法_滑动窗口①_力扣209. 长度最小的子数组

力扣209. 长度最小的子数组 209. 长度最小的子数组 - 力扣&#xff08;LeetCode&#xff09; 难度 中等 给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其总和大于等于 target 的长度最小的 连续子数组 [numsl, numsl1, ..., numsr-1, numsr] &…

【JavaEE】多线程 -- 死锁问题

目录 1. 问题引入 2.死锁问题的概念和原因 3. 解决死锁问题 1. 问题引入 在学习死锁之前, 我们先观察下面的代码能否输出正确的结果: 运行程序, 能正常输出结果: 这个代码只管上看起来, 好像是有锁冲突的, 此时的 locker 对象已经是加锁的状态, 在尝试对 locker 加锁, 不应该…

常用Java开发规范整理

常用Java开发规范整理 命名时 接口类中的方法和属性不要加任何修饰符号&#xff08; public 也不要加&#xff09;&#xff0c;保持代码的简洁性&#xff0c;并加上有效的 javadoc 注释代码中相同意义的概念的单词可能有多种&#xff0c;在业务中应该统一禁止中英文混合使用 …

使用 OpenTelemetry 和 Golang

入门 在本文中&#xff0c;我将展示你需要配置和处理统计信息所需的基本代码。在这个简短的教程中&#xff0c;我们将使用 Opentelemetry 来集成我们的 Golang 代码&#xff0c;并且为了可视化&#xff0c;我们将使用 Jeager。 在开始之前&#xff0c;让我简要介绍一下什么是 …

go学习之json和单元测试知识

文章目录 一、json以及序列化1.概述2.json应用场景图3.json数据格式说明4.json的序列化1&#xff09;介绍2&#xff09;应用案例 5.json的反序列化1&#xff09;介绍2&#xff09;应用案例 二、单元测试1.引子2.单元测试-基本介绍3.代码实现4.单元测试的细节说明5.单元测试的综…

中国毫米波雷达产业分析4——毫米波雷达企业介绍

一、矽典微 &#xff08;一&#xff09;公司简介 矽典微致力于实现射频技术的智能化&#xff0c;专注于研发高性能无线技术相关芯片&#xff0c;产品广泛适用于毫米波传感器、下一代移动通信、卫星通信等无线领域。 整合自身在芯片、系统、软件、算法等领域的专业能力&#xf…

C++学不会?一篇文章带你快速入门

1. 命名空间 1.1 命名空间的概念 C命名空间是一种用于避免名称冲突的机制。它允许在多个文件中定义相同的函数、类或变量&#xff0c;而不会相互干扰。 1.2 命名空间的定义 namespace是命名空间的关键字&#xff0c;后面是命名空间的名字&#xff0c;然后后面一对 {},{}中即…