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

下载

源码下载

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

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

相关文章

Istio 社区周报(第一期):2023.12.11 - 12.17

欢迎来到 Istio 社区周报 Istio 社区朋友们&#xff0c;你们好&#xff01; 我很高兴呈现第一期 Istio 社区周报。作为 Istio 社区的一员&#xff0c;每周我将为您带来 Istio 的最新发展、有见地的社区讨论、专业提示和重要安全新闻内容。 祝你阅读愉快&#xff0c;并在下一期中…

第二十二章 : Spring Boot 集成定时任务(一)

第二十二章 &#xff1a; Spring Boot 集成定时任务&#xff08;一&#xff09; 前言 本章知识点&#xff1a; 介绍使用Spring Boot内置的Scheduled注解来实现定时任务-单线程和多线程&#xff1b;以及介绍Quartz定时任务调度框架&#xff1a;简单定时调度器&#xff08;Simp…

ubuntu 18.04 共享屏幕

用于windows远程ubuntu 1. sudo apt install xrdp 2. 配置 sudo vim /etc/xrdp/startwm.sh 把最下面的test和exec两行注释掉&#xff0c;添加一行 gnome-session 3.安装dconf-editor : sudo apt-get install dconf-editor 关闭require encrytion org->gnome->desktop…

go从0到1项目实战体系二:数据类型

1. 数据类型: (1). bool类型(只能存true和false) (2). 数字类型: 主要有int(4个字节)、int8(1个字节,8是8个bit位)、int16(2个字节)、int32(3个字节)、int64(4个字节)、uint8(无符号)、uint16、uint32、uint64、float32(4个字节)、float64 (3). 字符类型: ①. 语法:var a b…

农夫山姆(0006)

题意 原来体积是ABC,现在体积是(A-1)* (B-2)*&#xff08;C-2&#xff09;,输入一个现在的体积n&#xff0c;要求现在的体积比原来减少了多少&#xff0c;输出一个减小的最小值和最大值 输入 4 输出 28 41 说明 注意问题的答案可能足够大&#xff0c;所以必须使用 64 位…

TransXNet实战:使用TransXNet实现图像分类任务(一)

文章目录 摘要安装包安装timm 数据增强Cutout和MixupEMA项目结构计算mean和std生成数据集 摘要 论文提出了一种名为D-Mixer的轻量级双动态TokenMixer&#xff0c;旨在解决传统卷积的静态性质导致的表示差异和特征融合问题。D-Mixer通过应用高效的全局注意力和输入依赖的深度卷…

计算机网络实用工具之parsero

简介 Parsero是一个用Python编写的免费脚本&#xff0c;它读取web服务器的robots.txt文件&#xff0c;探测“Disallow”的条目并返回响应状态码。 例&#xff1a; 200 OK The request has succeeded. 403 Forbidden The server understood the request, but is r…

Py之tensorflow-addons:tensorflow-addons的简介、安装、使用方法之详细攻略

Py之tensorflow-addons&#xff1a;tensorflow-addons的简介、安装、使用方法之详细攻略 目录 tensorflow-addons的简介 tensorflow-addons的安装 tensorflow-addons的使用方法 1、使用 TensorFlow Addons 中的功能&#xff1a; tensorflow-addons的简介 TensorFlow Addon…

【SpringBoot快速入门】(4)SpringBoot项目案例代码示例

目录 1 创建工程3 配置文件4 静态资源 之前我们已经学习的Spring、SpringMVC、Mabatis、Maven&#xff0c;详细讲解了Spring、SpringMVC、Mabatis整合SSM的方案和案例&#xff0c;上一节我们学习了SpringBoot的开发步骤、工程构建方法以及工程的快速启动&#xff0c;从这一节开…

Python---TCP 客户端程序开发

1. 开发 TCP 客户端程序开发步骤回顾 创建客户端套接字对象和服务端套接字建立连接发送数据接收数据关闭客户端套接字 2. socket 类的介绍 导入 socket 模块 import socket 创建客户端 socket 对象 socket.socket(AddressFamily, Type) 参数说明: AddressFamily 表示IP地…

大数据爬虫技术

随着互联网的发展&#xff0c;各行各业都开始注重数据的分析和应用。而大数据的出现&#xff0c;则让这一切变得更加便捷。但是&#xff0c;大数据的获取过程却并不简单&#xff0c;需要借助于爬虫技术来实现。本文将从基础概念到实践操作&#xff0c;详细介绍大数据爬虫技术。…

解决Electron应用中的白屏问题的实用方法

在使用Electron构建应用程序时&#xff0c;一些开发者可能会面临窗口加载过程中出现的白屏问题。这种问题主要分为两个方面&#xff1a; Electron未加载完毕HTML&#xff1a; 这时Electron自身产生的白色背景可能导致用户在启动应用时看到一片空白。HTML加载渲染过程中的短暂白…

JavaScript:函数

JavaScript&#xff1a;函数 函数的作用函数的声明和调用函数声明函数调用函数重复声明 函数传参传参语法参数默认值与参数数量问题传参数量过多传参数量太少参数默认值 函数的返回值函数表达式匿名函数立即执行函数 函数的作用 在我们编程过程中&#xff0c;会出现一种情况&a…

[软件] Image2LCD v4.0

介绍 通过打开图片, 可以提取图片的像素特征, 生成.c文件, 或者二进制文件等, 提供人们根据需要选择. 16位真彩色 每一个像素点需要用16位来表示, 分别是RGB, R: 5位 G: 6位, B: 5位, 共两个字节. 配置 tftLCD180显示屏, 官方给的参考代码, 需要如下所示设置.

gateway配置

server:port: 8080 spring:application:name: test-gatewaycloud:nacos:discovery:server-addr: localhost:8848gateway:discovery:locator:enabled: false#是否开启网关enabled: trueroutes:- id: test-order-route#目标微服务的请求地址和端口uri: lb://test-orderpredicates…

【Spring Security】认证密码加密Token令牌CSRF的使用详解

&#x1f389;&#x1f389;欢迎来到我的CSDN主页&#xff01;&#x1f389;&#x1f389; &#x1f3c5;我是Java方文山&#xff0c;一个在CSDN分享笔记的博主。&#x1f4da;&#x1f4da; &#x1f31f;推荐给大家我的专栏《Spring Security》。&#x1f3af;&#x1f3af; …

【如何隔离受感染主机】

以下是隔离感染主机的详细可实施步骤&#xff1a; 断开网络连接&#xff1a; 对于有线连接&#xff0c;直接从感染主机上拔掉网线。 对于无线连接&#xff0c;执行以下操作&#xff1a; Windows系统&#xff1a;点击任务栏的网络图标&#xff0c;然后点击“断开”。macOS系统&a…

频谱论文:RadioUNet:使用卷积神经网络的快速无线电地图估计

#频谱# R. Levie, . Yapar, G. Kutyniok and G. Caire, "RadioUNet: Fast Radio Map Estimation With Convolutional Neural Networks," in IEEE Transactions on Wireless Communications, vol. 20, no. 6, pp. 4001-4015, June 2021, doi: 10.1109/TWC.2021.305497…

Triton + HF + Qwen 推理经验总结

1. 简介 Triton介绍参考&#xff1a;GitHub - triton-inference-server/tutorials: This repository contains tutorials and examples for Triton Inference Server 2. 实现方案 2.1. docker部署 # 拉取docker镜像 git clone -b r23.10 https://github.com/triton-inferen…

【hadoop】解决浏览器不能访问Hadoop的50070、8088等端口?!

【hadoop】解决浏览器不能访问Hadoop的50070、8088等端口&#xff1f;&#xff01;&#x1f60e; 前言&#x1f64c;【hadoop】解决浏览器不能访问Hadoop的50070、8088等端口&#xff1f;&#xff01;查看自己的配置文件&#xff1a;最终成功访问如图所示&#xff1a; 总结撒花…