当前位置: 首页 > news >正文

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));// 输入Tensorfor (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模型文件的路径// 输入Tensorinput_tensor = new DenseTensor<float>(new[] { 4, 3, 640, 640 });// 创建输入容器input_container = new List<NamedOnnxValue>();}}
}

下载

源码下载

相关文章:

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

目录 效果 模型信息 项目 代码 下载 C# Onnx Yolov8 Detect 物体检测 多张图片同时推理 效果 模型信息 Model Properties ------------------------- date&#xff1a;2023-12-18T11:47:29.332397 description&#xff1a;Ultralytics YOLOv8n-detect model trained on …...

学习使用js保留两位小数同时去掉小数末尾多余的00

学习使用js保留两位小数同时去掉小数末尾多余的00 前言去除00方法 前言 let number 50000000;let new_number number / 10000;console.log(formatter-new_number, new_number);return new_number.toFixed(2) 万;会发现整数使用toFixed(2)&#xff0c;之后会有多余的.00 去…...

linux驱动的学习 驱动开发初识

1 设备的概念 在学习驱动和其开发之前&#xff0c;首先要知道所谓驱动&#xff0c;其对象就是设备。 1.1 主设备号&次设备号&#xff1a; 在Linux中&#xff0c;各种设备都以文件的形式存在/dev目录下&#xff0c;称为设备文件。最上层的应用程序可以打开&#xff0c;关…...

Node.js中npm中ws的WebSocket协议的实现

在Node.js中&#xff0c;ws是一个非常有用的模块&#xff0c;它提供了WebSocket协议的实现。WebSocket协议是一种在Web浏览器和服务器之间进行双向通信的协议&#xff0c;它可以使得Web应用程序更加交互式和实时。在本文中&#xff0c;我们将详细介绍npm中ws的内容。 ws是什么…...

PHP HTTPoxy CGI 应用程序漏洞 CVE-2016-5385

HTTPoxy CGI 应用程序漏洞 CVE-2016-5385 已亲自复现 漏洞名称漏洞描述影响版本 漏洞复现环境搭建漏洞利用 修复建议 漏洞名称 漏洞描述 在Oracle Communications BRM 10.x/12.x&#xff08;云软件&#xff09;中发现漏洞。它已经被宣布为关键。此漏洞影响组件用户数据库的未…...

qt-C++笔记之使用QLabel和QPushButton实现一个bool状态的指示灯

qt-C笔记之使用QLabel和QPushButton实现一个bool状态的指示灯 code review! 文章目录 qt-C笔记之使用QLabel和QPushButton实现一个bool状态的指示灯1.QPushButton实现2.QLabel实现2.QLabel实现-对错符号 1.QPushButton实现 运行 代码 #include <QtWidgets>class Ind…...

自动驾驶技术入门平台分享:百度Apollo开放平台9.0全方位升级

目录 平台全方位的升级 全新的架构 工具服务 应用软件&#xff08;场景应用&#xff09; 软件核心 硬件设备 更强的算法能力 9.0版本算法升级总结 更易用的工程框架 Apollo开放平台9.0版本的技术升级为开发者提供了许多显著的好处&#xff0c;特别是对于深度开发需求…...

Elementor Pro v3.18.1和(完整模板套件)介绍说明

WordPress 插件:免费下载 Elementor Pro v3.18.1 免费最新版本 [所有功能已激活] Elementor Pro 是一个功能强大的 WordPress 插件,使用户无需编码即可构建和设计网站。它是 Elementor 页面构建器的付费版本,提供额外的功能和小部件来创建更复杂的设计。在这篇博文中,我们将探讨…...

Windows如何安装使用TortoiseSVN客户端并实现公网访问本地SVN Server

文章目录 前言1. TortoiseSVN 客户端下载安装2. 创建检出文件夹3. 创建与提交文件4. 公网访问测试 前言 TortoiseSVN是一个开源的版本控制系统&#xff0c;它与Apache Subversion&#xff08;SVN&#xff09;集成在一起&#xff0c;提供了一个用户友好的界面&#xff0c;方便用…...

Mybatis配置-映射器(mappers)

现在&#xff0c;我们已经配置了MyBatis的行为&#xff0c;准备定义我们的映射SQL语句。但首先&#xff0c;我们需要告诉MyBatis在哪里找到它们。在这方面&#xff0c;Java并没有提供很好的自动发现机制&#xff0c;所以最好的方法是直接告诉MyBatis在哪里找到映射文件。 您可以…...

python 音视频合并

目录 moviepy ffmpeg命令合成&#xff1a; 添加字幕文件&#xff1a; 添加字幕文本&#xff1a; pipeline添加字幕&#xff1a; moviepy python&#xff08;opencv pyaudio moviepy&#xff09;实现录制音视频文件并合并_ubuntu使用python的sounddeviceopencv录制音视频…...

HttpUtils——助力高效网络通信

使用HttpClient发送请求、接收响应很简单&#xff0c;一般需要如下几步即可: 1、创建HttpClient对象。 2、创建请求方法的实例&#xff0c;并指定请求URL。如果需要发送GET请求&#xff0c; 创建HttpGet对象&#xff1b;如果需要发送POST请求&#xff0c;创建HttpPost对象。 3…...

WAF绕过常见方法

前面写了WAF如何检测&#xff0c;现在直接上WAF常见的一些绕过方法。 方法1:变换大小写 实例: 比如WAF拦截了union&#xff0c;那就使用Union、UnloN等方式绕过。 方法2:编码绕过 实例1: WAF检测敏感字~&#xff0c;则可以用Ox7e代替&#xff0c;如extractvalue(1,concat(~…...

SpringCloud微服务 【实用篇】| Docker镜像、容器、数据卷操作

目录 一&#xff1a;Docker基本操作 1. 镜像操作 镜像相关命令 2. 容器操作 容器相关命令 3. 数据卷&#xff08;容器数据管理&#xff09; 数据卷 操作数据卷 挂载数据卷 挂载的方式区别 前些天突然发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0…...

OSPF面试总结

OSPF 基本特点 属于IGP、LS支持无类域间路由没有环路&#xff08;区域内运行LS、区域间是DV,所以所有的区域要和区域0相连&#xff09;收敛速度快使用组播发送数据 224.0.0.5、224.0.0.6 什么时候用224.0.0.5&#xff1f;支持多条等价路由支持协议报文认证 OSPF路由的计算过程…...

【算法系列篇】递归、搜索和回溯(四)

文章目录 前言什么是决策树1. 全排列1.1 题目要求1.2 做题思路1.3 代码实现 2. 子集2.1 题目要求2.2 做题思路2.3 代码实现 3. 找出所有子集的异或总和再求和3.1 题目要求3.2 做题思路3.3 代码实现 4. 全排列II4.1 题目要求4.2 做题思路4.3 代码实现 前言 前面我们通过几个题目…...

Windows 系统下本地单机搭建 Redis(一主二从三哨兵)

目录 一、Redis环境准备&#xff1a; 1、下载redis 2、Windows下的.msi安装和.zip格式区别&#xff1a; 二、哨兵介绍&#xff1a; 1、一主二从三哨兵理论图&#xff1a; 2.哨兵的主要功能&#xff1a; 3.哨兵用于实现 redis 集群的高可用&#xff0c;本身也是分布式的&…...

数据库访问被拒怎么操作?

就一点&#xff1a; &#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01; cmd打开命令窗口直接输入 mysql -u root -p 然后加密码打开数据库服务再去试试&#xff01;&#xff01; &#xff01;&#xff01;&#xff01;&#xff01;&…...

Vue 2 生命周期即将结束

本文章翻译自 Vue 2 is Approaching End Of Life 文章原作者 youyuxi 2024 年即将到来&#xff0c;我们想借此机会提醒 Vue 社区&#xff0c;Vue 2 将于 2023 年 12 月 31 日达到生命周期结束 (EOL) Vue 2.0 于 2016 年发布&#xff0c;已有 7 年多的时间。这是 Vue 成为主流框…...

Python---端口和端口号的介绍

1. 问题思考 不同电脑上的飞秋之间进行数据通信&#xff0c;它是如何保证把数据给飞秋而不是给其它软件呢? 其实&#xff0c;每运行一个网络程序都会有一个端口&#xff0c;想要给对应的程序发送数据&#xff0c;找到对应的端口即可。 端口效果图: 2. 什么是端口 端口是传…...

家政维修平台实战20:权限设计

目录 1 获取工人信息2 搭建工人入口3 权限判断总结 目前我们已经搭建好了基础的用户体系&#xff0c;主要是分成几个表&#xff0c;用户表我们是记录用户的基础信息&#xff0c;包括手机、昵称、头像。而工人和员工各有各的表。那么就有一个问题&#xff0c;不同的角色&#xf…...

Nginx server_name 配置说明

Nginx 是一个高性能的反向代理和负载均衡服务器&#xff0c;其核心配置之一是 server 块中的 server_name 指令。server_name 决定了 Nginx 如何根据客户端请求的 Host 头匹配对应的虚拟主机&#xff08;Virtual Host&#xff09;。 1. 简介 Nginx 使用 server_name 指令来确定…...

土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等

&#x1f50d; 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术&#xff0c;可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势&#xff0c;还能有效评价重大生态工程…...

.Net Framework 4/C# 关键字(非常用,持续更新...)

一、is 关键字 is 关键字用于检查对象是否于给定类型兼容,如果兼容将返回 true,如果不兼容则返回 false,在进行类型转换前,可以先使用 is 关键字判断对象是否与指定类型兼容,如果兼容才进行转换,这样的转换是安全的。 例如有:首先创建一个字符串对象,然后将字符串对象隐…...

回溯算法学习

一、电话号码的字母组合 import java.util.ArrayList; import java.util.List;import javax.management.loading.PrivateClassLoader;public class letterCombinations {private static final String[] KEYPAD {"", //0"", //1"abc", //2"…...

NXP S32K146 T-Box 携手 SD NAND(贴片式TF卡):驱动汽车智能革新的黄金组合

在汽车智能化的汹涌浪潮中&#xff0c;车辆不再仅仅是传统的交通工具&#xff0c;而是逐步演变为高度智能的移动终端。这一转变的核心支撑&#xff0c;来自于车内关键技术的深度融合与协同创新。车载远程信息处理盒&#xff08;T-Box&#xff09;方案&#xff1a;NXP S32K146 与…...

AirSim/Cosys-AirSim 游戏开发(四)外部固定位置监控相机

这个博客介绍了如何通过 settings.json 文件添加一个无人机外的 固定位置监控相机&#xff0c;因为在使用过程中发现 Airsim 对外部监控相机的描述模糊&#xff0c;而 Cosys-Airsim 在官方文档中没有提供外部监控相机设置&#xff0c;最后在源码示例中找到了&#xff0c;所以感…...

uniapp 开发ios, xcode 提交app store connect 和 testflight内测

uniapp 中配置 配置manifest 文档&#xff1a;manifest.json 应用配置 | uni-app官网 hbuilderx中本地打包 下载IOS最新SDK 开发环境 | uni小程序SDK hbulderx 版本号&#xff1a;4.66 对应的sdk版本 4.66 两者必须一致 本地打包的资源导入到SDK 导入资源 | uni小程序SDK …...

C++ 设计模式 《小明的奶茶加料风波》

&#x1f468;‍&#x1f393; 模式名称&#xff1a;装饰器模式&#xff08;Decorator Pattern&#xff09; &#x1f466; 小明最近上线了校园奶茶配送功能&#xff0c;业务火爆&#xff0c;大家都在加料&#xff1a; 有的同学要加波霸 &#x1f7e4;&#xff0c;有的要加椰果…...

毫米波雷达基础理论(3D+4D)

3D、4D毫米波雷达基础知识及厂商选型 PreView : https://mp.weixin.qq.com/s/bQkju4r6med7I3TBGJI_bQ 1. FMCW毫米波雷达基础知识 主要参考博文&#xff1a; 一文入门汽车毫米波雷达基本原理 &#xff1a;https://mp.weixin.qq.com/s/_EN7A5lKcz2Eh8dLnjE19w 毫米波雷达基础…...