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

这篇具有很好参考价值的文章主要介绍了C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

效果

模型信息

项目

代码 

下载


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

效果

C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测,C#人工智能实践,paddlepaddle,人工智能,计算机视觉,opencv,c#,目标检测,机器学习

模型信息

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

C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测,C#人工智能实践,paddlepaddle,人工智能,计算机视觉,opencv,c#,目标检测,机器学习

代码 

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);
        }
    }
}

下载

源码下载文章来源地址https://www.toymoban.com/news/detail-763327.html

到了这里,关于C# Onnx 百度飞桨开源PP-YOLOE-Plus目标检测的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 百度飞桨(PaddlePaddle) - PP-OCRv3 文字检测识别系统 基于 Paddle Serving快速使用(服务化部署 - CentOS 7)

    目录 Paddle Serving服务化部署实战 准备预测数据和部署环境 环境准备 安装 PaddlePaddle 2.0 安装 PaddleOCR 准备PaddleServing的运行环境, 模型转换 Paddle Serving pipeline部署 确认工作目录下文件结构: 启动服务可运行如下命令: 测试 Python发送服务请求: Postman 发送请求 参数调整 百度飞

    2024年02月07日
    浏览(42)
  • 基于PP-YOLOE-SOD实现遥感场景下的小目标检测

    本项目基于百度飞桨AI Studio平台进行实现,百度出品的深度学习平台飞桨(PaddlePaddle)是主流深度学习框架中一款完全国产化的产品,与Google TensorFlow、Facebook Pytorch齐名。2016 年飞桨正式开源,是国内首个全面开源开放、技术领先、功能完备的产业级深度学习平台。相比国内

    2024年02月13日
    浏览(25)
  • 论文解读: PP-YOLOE: An evolved version of YOLO

    论文地址:https://arxiv.org/pdf/2203.16250.pdf 发表时间:2022 PP-YOLOE基于PP-YOLOv2改进实现,其中PP-YOLOv2的整体架构包含了具有可变形卷积的ResNet50-vd的主干,使用带有SPP层和DropBlock的PAN做neck,以及轻量级的IoU感知头。在PPYOLOv2中,ReLU激活功能用于主干,而mish激活功能用于颈部。PP-

    2024年02月06日
    浏览(33)
  • 超越所有Anchor-free方法!PP-YOLOE-R:一种高效的目标检测网络

    点击下方 卡片 ,关注“ 自动驾驶之心 ”公众号 ADAS巨卷干货,即可获取 点击进入→ 自动驾驶之心【目标检测】技术交流群 后台回复 【PPYOLO】 获取论文、代码等更多资料! 超越所有Anchor-free方法!PP-YOLOE-R:一种高效的目标检测网络 PP-YOLOE-R是基于PP-YOLOE的高效anchor-free旋转

    2024年02月08日
    浏览(34)
  • 【读点论文】PP-YOLOE: An evolved version of YOLO,面向友好部署的模型设计,为项目后续产业落地提供了更加有效的参考

    在本报告中,我们介绍了PP-YOLOE,一种具有高性能和友好部署的工业最先进的目标探测器。我们在之前的PP-YOLOv2的基础上进行优化,采用无锚模式,更强大的骨干和颈部配备CSPRepResStage, ET-head和动态标签分配算法TAL。我们为不同的实践场景提供s/m/l/x模型。结果,pp - yoloe - 1在

    2024年02月15日
    浏览(30)
  • 百度飞桨(PaddlePaddle)-数字识别

    手写数字识别任务 用于对 0 ~ 9 的十类数字进行分类,即输入手写数字的图片,可识别出这个图片中的数字。 python -m pip install matplotlib numpy -i https://mirror.baidu.com/pypi/simple python -m pip install paddlepaddle==2.4.2 -i https://pypi.tuna.tsinghua.edu.cn/simple 官网代码少了 plt.show() # 要加上这句,才

    2024年02月03日
    浏览(31)
  • 百度飞桨PaddleSpeech的简单使用

    PaddleSpeech 是基于飞桨 PaddlePaddle 的语音方向的开源模型库,用于语音和音频中的各种关键任务的开发,包含大量基于深度学习前沿和有影响力的模型,一些典型的应用示例如下:语音识别、语音翻译 (英译中)、语音合成、标点恢复等。 我只用到了语音识别(语音转文字)、语

    2024年02月03日
    浏览(33)
  • 百度飞桨 paddleX操作手册

    新建项目 步骤1 、点击新建项目,根据新建项目弹窗进行信息填写名称、描述、选择任务类型、选着工作路径后创建。 步骤2 、创建后选择数据集,这里的数据选项在 数据集管理/我的数据集 模块中创建,选择完成后即点击下一步,该处提供了对数据集的预览按钮,点击查看

    2024年02月05日
    浏览(50)
  • 百度飞桨(PaddlePaddle)- 张量(Tensor)

    张量(Tensor)、标量(scalar)、向量(vector)、矩阵(matrix) 飞桨 使用张量(Tensor) 来表示神经网络中传递的数据 ,Tensor 可以理解为多维数组,类似于 Numpy 数组(ndarray) 的概念。与 Numpy 数组相比,Tensor 除了支持运行在 CPU 上,还支持运行在 GPU 及各种 AI 芯片上,以实现

    2024年02月03日
    浏览(36)
  • 基于百度飞桨PaddleOCR的图片文字识别

    PaddleOCR项目源码:https://github.com/PaddlePaddle/PaddleOCR 飞桨开源文字识别模型套件PaddleOCR,目标是打造丰富、领先、实用的文本识别模型/工具库。最新开源的超轻量PP-OCRv3模型大小仅为16.2M。同时支持中英文识别;支持倾斜、竖排等多种方向文字识别;支持GPU、CPU预测;用户既可

    2024年02月10日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包