C# Onnx Yolov8 Detect 物体检测 多张图片同时推理

目录

效果

模型信息

项目

代码

下载


C# Onnx Yolov8 Detect 物体检测 多张图片同时推理

效果

模型信息

Model Properties
-------------------------
date:2023-12-18T11:47:29.332397
description:Ultralytics YOLOv8n-detect model trained on coco.yaml
author:Ultralytics
task:detect
license:AGPL-3.0 https://ultralytics.com/license
version:8.0.172
stride:32
batch:4
imgsz:[640, 640]
names:{0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'}
---------------------------------------------------------------

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

Outputs
-------------------------
name:output0
tensor:Float[4, 84, 8400]
---------------------------------------------------------------

项目

代码

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

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

        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_container;
        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
        DisposableNamedOnnxValue[] results_onnxvalue;
        Tensor<float> result_tensors;

        private void button2_Click(object sender, EventArgs e)
        {
            float[] result_array = new float[8400 * 84 * 4];
            List<float[]> ltfactors = new List<float[]>();

            for (int i = 0; i < 4; i++)
            {
                image_path = "test_img/" + i.ToString() + ".jpg";

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

                float[] factors = new float[2];
                factors[0] = factors[1] = (float)(max_image_length / 640.0);
                ltfactors.Add(factors);

                // 将图片转为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
                for (int y = 0; y < resize_image.Height; y++)
                {
                    for (int x = 0; x < resize_image.Width; x++)
                    {
                        input_tensor[i, 0, y, x] = resize_image.At<Vec3b>(y, x)[0] / 255f;
                        input_tensor[i, 1, y, x] = resize_image.At<Vec3b>(y, x)[1] / 255f;
                        input_tensor[i, 2, y, x] = resize_image.At<Vec3b>(y, x)[2] / 255f;
                    }
                }

            }

            input_container.Add(NamedOnnxValue.CreateFromTensor("images", input_tensor));

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

            results_onnxvalue = result_infer.ToArray();

            result_tensors = results_onnxvalue[0].AsTensor<float>();

            result_array = result_tensors.ToArray();

            for (int i = 0; i < 4; i++)
            {
                image_path = "test_img/" + i.ToString() + ".jpg";

                result_pro = new DetectionResult(classer_path, ltfactors[i]);

                float[] temp = new float[8400 * 84];

                Array.Copy(result_array, 8400 * 84 * i, temp, 0, 8400 * 84);

                Result result = result_pro.process_result(temp);

                result_image = result_pro.draw_result(result, new Mat(image_path));

                Cv2.ImShow(image_path, result_image);

            }

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;

            model_path = "model\\yolov8n-detect-batch4.onnx";
            classer_path = "model\\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[] { 4, 3, 640, 640 });

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

        }
    }
}

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

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

        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_container;
        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
        DisposableNamedOnnxValue[] results_onnxvalue;
        Tensor<float> result_tensors;

        private void button2_Click(object sender, EventArgs e)
        {
            float[] result_array = new float[8400 * 84 * 4];
            List<float[]> ltfactors = new List<float[]>();

            for (int i = 0; i < 4; i++)
            {
                image_path = "test_img/" + i.ToString() + ".jpg";

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

                float[] factors = new float[2];
                factors[0] = factors[1] = (float)(max_image_length / 640.0);
                ltfactors.Add(factors);

                // 将图片转为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
                for (int y = 0; y < resize_image.Height; y++)
                {
                    for (int x = 0; x < resize_image.Width; x++)
                    {
                        input_tensor[i, 0, y, x] = resize_image.At<Vec3b>(y, x)[0] / 255f;
                        input_tensor[i, 1, y, x] = resize_image.At<Vec3b>(y, x)[1] / 255f;
                        input_tensor[i, 2, y, x] = resize_image.At<Vec3b>(y, x)[2] / 255f;
                    }
                }

            }

            input_container.Add(NamedOnnxValue.CreateFromTensor("images", input_tensor));

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

            results_onnxvalue = result_infer.ToArray();

            result_tensors = results_onnxvalue[0].AsTensor<float>();

            result_array = result_tensors.ToArray();

            for (int i = 0; i < 4; i++)
            {
                image_path = "test_img/" + i.ToString() + ".jpg";

                result_pro = new DetectionResult(classer_path, ltfactors[i]);

                float[] temp = new float[8400 * 84];

                Array.Copy(result_array, 8400 * 84 * i, temp, 0, 8400 * 84);

                Result result = result_pro.process_result(temp);

                result_image = result_pro.draw_result(result, new Mat(image_path));

                Cv2.ImShow(image_path, result_image);

            }

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;

            model_path = "model\\yolov8n-detect-batch4.onnx";
            classer_path = "model\\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[] { 4, 3, 640, 640 });

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

        }
    }
}

下载

源码下载

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

jeecg如果修改BasicForm提交按钮文字

可以通过 submitButtonOptions 属性来设置&#xff0c;代码如下 <BasicForm :schemas"mySchema" :submitButtonOptions"{ text: 保存 }" />欢迎关注微信公众号&#xff1a;文本魔术&#xff0c;了解更多

在统信UOS操作系统1060上如何部署DNS服务器?01

原文链接&#xff1a;在统信UOS操作系统1060上如何部署DNS服务器&#xff1f;01 hello&#xff0c;大家好啊&#xff01;今天我要给大家带来的是在统信UOS操作系统1060上部署DNS服务器系列的第一篇文章。在这个系列中&#xff0c;我们将一步步搭建一个完整的DNS服务器环境。而今…

npm安装依赖报错ERESOLVE unable to resolve dependency tree(我是在taro项目中)(node、npm 版本问题)

换了电脑之后新电脑安装包出错 &#x1f447;&#x1f447;&#x1f447; npm install 安装包报错 ERESOLVE unable to resolve dependency tree 百度后尝试使用 npm install --force 还是报错 参考 有人说是 node 版本和 npm 版本的问题 参考 新电脑 node版本&#xff1a;16.1…

MyBatis 运行原理

MyBatis框架在操作数据库时&#xff0c;大体经过了8个步骤&#xff1a; 1.读取 MyBatis 配置文件&#xff1a;mybatis-config.xml 为 MyBatis 的全局配置文件&#xff0c;配置了 MyBatis 的运行环境等信息&#xff0c;例如数据库连接信息。 2.加载映射文件&#xff1a;映射文…

服务器解析漏洞是什么?攻击检测及修复

服务器解析漏洞&#xff08;Server-side Include Vulnerability&#xff0c;SSI漏洞&#xff09;是一种安全漏洞&#xff0c;通常出现在支持服务器端包含&#xff08;SSI&#xff09;功能的Web服务器上。SSI是一种在Web页面中嵌入动态内容的技术&#xff0c;允许开发人员将外部…

Word的兼容性问题很常见,禁用兼容模式虽步不是最有效的,但可以解决兼容性问题

当你在较新版本的Word应用程序中打开用较旧版本的Word创建的文档时&#xff0c;会出现兼容性问题。错误通常发生在文件名附近&#xff08;兼容模式&#xff09;。兼容性模式问题&#xff08;暂时&#xff09;禁用Word功能&#xff0c;从而限制使用较新版本Word的用户编辑文档。…

四、W5100S/W5500+RP2040之MicroPython开发<TCP Client示例>

文章目录 1 前言2 相关网络信息2 .1 简介2.2 TCP_Client工作步骤2.3 TCP Client的优点2.4 应用场景 3 WIZnet以太网芯片4 TCP_Client网络设置示例概述以及使用4.1 流程图4.2 准备工作核心4.3 连接方式4.4 主要代码概述4.5 烧录验证 5 注意事项6 相关链接 1 前言 在这个智能硬件…

【扩散模型】6、Classifier-Free Diffusion Guidance | 无需显示分类器指导也能获得很好的生成效果

论文&#xff1a;Classifier-Free Diffusion Guidance 代码&#xff1a;暂无 出处&#xff1a;NIPS 2021 workshop&#xff08;短版本论文&#xff09; 一、背景 在此之前&#xff0c;classifier guidance &#xff08;diffusion model beats GAN&#xff09;模型使用类别引…

C++的设计模式总结

通过指针指向一个多态对象来表达灵活性

MongoDB的覆盖索引查询

本文主要介绍MongoDB的覆盖索引查询。 目录 MongoDB的覆盖索引查询使用ensureIndex()创建索引使用createIndex()创建索引覆盖索引查询 MongoDB的覆盖索引查询 使用ensureIndex()创建索引 db.collection.ensureIndex()用于在集合中创建索引。索引是一种数据结构&#xff0c;用…

Github 2023-12-20 开源项目日报 Top10

根据Github Trendings的统计&#xff0c;今日(2023-12-20统计)共有10个项目上榜。根据开发语言中项目的数量&#xff0c;汇总情况如下&#xff1a; 开发语言项目数量Python项目5非开发语言项目2Rust项目1Solidity项目1TypeScript项目1C项目1 Manticore Search: 开源快速数据库…

读取spring boot项目resource目录下的文件

背景 项目开发过程中&#xff0c;有一些情况下将配置文件放在resource下能简化代码实现和部署时的打包步骤。例如&#xff1a; 项目中使用的数据库升级脚本、初始化脚本。将文件放到resource下&#xff0c;打包在jar包中&#xff0c;不能直接通过File路径读取。下面介绍两种读…

linux搭建gitlab

gitlab的介绍 区别于github&#xff0c;github是面向互联网基于git实现的代码托管平台&#xff0c;gitlab是基于Ruby语言实现的git管理平台软件&#xff0c;一般用于公司内部代码仓库。 gitlab组成 Nginx 静态Web服务器Gitlab-workhorse 轻量级的反向代理服务器Gitlab-shell 用…

5分钟上手浏览器插件测试——Eolink Apikit

Eolink Apikit 研发管理和自动化测试产品中&#xff0c;提供了多种发起 API 测试的方式&#xff1a; 服务器测试&#xff1a;通过 Eolink Apikit 官方远程服务器发送请求&#xff0c;不需要安装任何插件&#xff0c;但是无法访问本地服务器(localhost)、内网、局域网。插件测试…

小程序使用web-view无法打开该H5页面不支持打开的解决方法

我在正式上线版小程序使用 web-view 组件测试时提示&#xff1a;“无法打开该页面&#xff0c;不支持打开 https://xxxxxx&#xff0c;请在“小程序右上角更多->反馈与投诉”中和开发者反馈。” 奇怪的是&#xff0c;“真机调试”、“开发模式”都可以使用 web-view 组件访…

net6使用StackExchangeRedis实现分布式缓存

上一篇讲解了Redis的搭建及ServiceStack.Redis 与 StackExchange.Reids 的区别https://blog.csdn.net/qq_39569480/article/details/105249607 这篇文章遗我们来说下使用Microsoft.Extensions.Caching.StackExchangeRedis来对redis进行操作及帮助类。 首先在windows上安装red…

【一】FPGA实现SPI协议之SPI协议介绍

【一】FPGA实现SPI协议之SPI协议介绍 一、spi协议解析 spi协议有4根线&#xff0c;主机输出从机输入MOSI、主机输入从机输出MISO、时钟信号SCLK、片选信号SS\CS 。 一般用于主机和从机之间通信。由主机发起读请求和写请求&#xff0c;主机的权限是主动的&#xff0c;从机是被…

STM32——串口通信应用篇

一、引言 STM32微控制器是一款功能强大的嵌入式系统芯片&#xff0c;广泛应用于各种领域。其中&#xff0c;串口通信是其重要功能之一&#xff0c;可用于与外部设备进行数据交换和控制。本文将介绍STM32串口通信的基本原理、应用场景以及实现方法。 二、STM32串口通信基本原理 …

Ubuntu 虚拟机环境,编译AOSP源码

环境 : VMware虚拟机 Ubuntu 20.04.3 LTS 搭建配置开发环境 sudo apt-get install git-core gnupg flex bison build-essential zip curl zlib1g-dev gcc-multilib g-multilib libc6-dev-i386 libncurses5 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev libgl…

【大数据存储与处理】实验一 HBase 的基本操作

一、实验目的&#xff1a; 1. 掌握 Hbase 创建数据库表及删除数据库表 2. 掌握 Hbase 对数据库表数据的增、删、改、查。 二、实验内容&#xff1a; 1、题目 0&#xff1a;进入 hbase shell 2、题目 1&#xff1a;Hbase 创建数据库表 创建数据库表的命令&#xff1a;create 表…