yolov10--C#接口

news2024/10/5 18:26:29

一、前言

     本章主要讲解yolov10的C#接口,主要是使用微软开发的openvinocsharp工具加载yolov10模型,并做推理。

二、yolov10模型转换

     这里为了演示,使用官方yolov10m模型(其他大小的模型同理)做演示,可从下方下载,当然也可以是自己训练好的模型

https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10m.pt

      该原始模型,需要被转换为openvinocsharp所支持的模型格式,为此需要建立一个yolov10的python环境,使用conda创建,requirements.txt 为 yolov10官方代码下的所需包

conda create -n yolov10 python=3.9
conda activate yolov10
pip install -r requirements.txt
pip install -e .

然后安装OpenVINO™环境,输入以下指令

pip install openvino==2024.1.0

在该创建好的虚拟环境,cd 至下载好的yolov10m.pt 所在目录,执行

yolo export model=yolov10m.pt format=onnx opset=11 simplify
ovc yolov10m.onnx

这样,pt文件的模型将转换为onnx文件,再换换为 openvino 所需的 bin 和 xml 文件格式

三、C#端openvinosharp相关包安装

         首先需使用VS2022构建项目,其次将openvinosharp相关包安装上

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="OpenCvSharp4" Version="4.9.0.20240103" />
    <PackageReference Include="OpenCvSharp4.Extensions" Version="4.9.0.20240103" />
    <PackageReference Include="OpenCvSharp4.runtime.win" Version="4.9.0.20240103" />
    <PackageReference Include="OpenVINO.CSharp.API" Version="2024.1.0.1" />
    <PackageReference Include="OpenVINO.CSharp.API.Extensions.OpenCvSharp" Version="1.0.4" />
    <PackageReference Include="OpenVINO.runtime.win" Version="2024.1.0.1" />
  </ItemGroup>

</Project>

也就是  OpenCvSharp4、OpenCvSharp4.Extensions、OpenCvSharp4.runtime.win、OpenVINO.CSharp.API、OpenVINO.CSharp.API.Extensions.OpenCvSharp、OpenVINO.runtime.win,这6个包给装上

这部分参考自下面博客

【OpenVINO™】在C#中使用 OpenVINO™ 部署 YOLOv10 模型实现目标_yolov10 openvino-CSDN博客

四、C#加载yolo10推理代码

这样就可以创建C# winform项目,愉快地加载前面转换好的模型文件做前向推理了

// See https://aka.ms/new-console-template for more information
//Console.WriteLine("Hello, World!");

using System.Reflection;
using System.Runtime.InteropServices;
using System;
using OpenVinoSharp;
using OpenVinoSharp.Extensions.utility;
using OpenVinoSharp.Extensions;
using OpenCvSharp;
using OpenCvSharp.Dnn;
using OpenVinoSharp.preprocess;

namespace yolov10_det_opencvsharp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string model_path = "./model_demo/yolov10m.xml";
            string image_path = "./model_demo/cat.png";
            string device = "AUTO";  //CPU GPU AUTO,可选AUTO模式

      

            // -------- Get OpenVINO runtime version --------

            OpenVinoSharp.Version version = Ov.get_openvino_version();

            Slog.INFO("---- OpenVINO INFO----");
            Slog.INFO("Description : " + version.description);
            Slog.INFO("Build number: " + version.buildNumber);

            Slog.INFO("Predict model files: " + model_path);
            Slog.INFO("Predict image  files: " + image_path);
            Slog.INFO("Inference device: " + device);
            Slog.INFO("Start yolov10 model inference.");

            //yolov10_det(model_path, image_path, device);
            yolov10_det_process(model_path, image_path , device);
        }
        static void yolov10_det(string model_path, string image_path, string device)
        {
            DateTime start = DateTime.Now;
            // -------- Step 1. Initialize OpenVINO Runtime Core --------
            Core core = new Core();
            DateTime end = DateTime.Now;
            Slog.INFO("1. Initialize OpenVINO Runtime Core success, time spend: " + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 2. Read inference model --------
            start = DateTime.Now;
            Model model = core.read_model(model_path);
            end = DateTime.Now;
            Slog.INFO("2. Read inference model success, time spend: " + (end - start).TotalMilliseconds + "ms.");
            OvExtensions.printf_model_info(model);
            // -------- Step 3. Loading a model to the device --------
            start = DateTime.Now;
            CompiledModel compiled_model = core.compile_model(model, device);
            end = DateTime.Now;
            Slog.INFO("3. Loading a model to the device success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 4. Create an infer request --------
            start = DateTime.Now;
            InferRequest infer_request = compiled_model.create_infer_request();
            end = DateTime.Now;
            Slog.INFO("4. Create an infer request success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 5. Process input images --------
            start = DateTime.Now;
            Mat image = new Mat(image_path); // Read image by opencvsharp
            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 factor = (float)(max_image_length / 640.0);
            end = DateTime.Now;
            Slog.INFO("5. Process input images success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 6. Set up input data --------
            start = DateTime.Now;
            Tensor input_tensor = infer_request.get_input_tensor();
            Shape input_shape = input_tensor.get_shape();
            Mat input_mat = CvDnn.BlobFromImage(max_image, 1.0 / 255.0, new OpenCvSharp.Size(input_shape[2], input_shape[3]), 0, true, false);
            float[] input_data = new float[input_shape[1] * input_shape[2] * input_shape[3]];
            Marshal.Copy(input_mat.Ptr(0), input_data, 0, input_data.Length);
            input_tensor.set_data<float>(input_data);

            end = DateTime.Now;
            Slog.INFO("6. Set up input data success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 7. Do inference synchronously --------
            infer_request.infer();
            start = DateTime.Now;
            infer_request.infer();
            end = DateTime.Now;
            Slog.INFO("7. Do inference synchronously success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 8. Get infer result data --------
            start = DateTime.Now;
            Tensor output_tensor = infer_request.get_output_tensor();
            int output_length = (int)output_tensor.get_size();
            float[] output_data = output_tensor.get_data<float>(output_length);
            end = DateTime.Now;
            Slog.INFO("8. Get infer result data success, time spend:" + (end - start).TotalMilliseconds + "ms.");

             -------- Step 9. Process reault  --------
            start = DateTime.Now;

            List<Rect> position_boxes = new List<Rect>();
            List<int> class_ids = new List<int>();
            List<float> confidences = new List<float>();

            // Preprocessing output results
            for (int i = 0; i < output_data.Length / 6; i++)
            {
                int s = 6 * i;
                if ((float)output_data[s + 4] > 0.5)
                {
                    float cx = output_data[s + 0];
                    float cy = output_data[s + 1];
                    float dx = output_data[s + 2];
                    float dy = output_data[s + 3];
                    int x = (int)((cx) * factor);
                    int y = (int)((cy) * factor);
                    int width = (int)((dx - cx) * factor);
                    int height = (int)((dy - cy) * factor);
                    Rect box = new Rect();
                    box.X = x;
                    box.Y = y;
                    box.Width = width;
                    box.Height = height;

                    position_boxes.Add(box);
                    class_ids.Add((int)output_data[s + 5]);
                    confidences.Add((float)output_data[s + 4]);
                }
            }


            end = DateTime.Now;
            Slog.INFO("9. Process reault  success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            for (int i = 0; i < class_ids.Count; i++)
            {
                int index = i;
                Cv2.Rectangle(image, position_boxes[index], new Scalar(0, 0, 255), 2, LineTypes.Link8);
                Cv2.Rectangle(image, new OpenCvSharp.Point(position_boxes[index].TopLeft.X, position_boxes[index].TopLeft.Y + 30),
                    new OpenCvSharp.Point(position_boxes[index].BottomRight.X, position_boxes[index].TopLeft.Y), new Scalar(0, 255, 255), -1);
                Cv2.PutText(image, class_ids[index] + "-" + confidences[index].ToString("0.00"),
                    new OpenCvSharp.Point(position_boxes[index].X, position_boxes[index].Y + 25),
                    HersheyFonts.HersheySimplex, 0.8, new Scalar(0, 0, 0), 2);
            }
            string output_path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(image_path)),
                Path.GetFileNameWithoutExtension(image_path) + "_result.jpg");
            Cv2.ImWrite(output_path, image);
            Slog.INFO("The result save to " + output_path);
            Cv2.ImShow("Result", image);
            Cv2.WaitKey(0);
        }
        static void yolov10_det_process(string model_path, string image_path, string device)
        {
            DateTime start = DateTime.Now;
            // -------- Step 1. Initialize OpenVINO Runtime Core --------
            Core core = new Core();
            DateTime end = DateTime.Now;
            Slog.INFO("1. Initialize OpenVINO Runtime Core success, time spend: " + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 2. Read inference model --------
            start = DateTime.Now;
            Model model = core.read_model(model_path);
            end = DateTime.Now;
            Slog.INFO("2. Read inference model success, time spend: " + (end - start).TotalMilliseconds + "ms.");
            OvExtensions.printf_model_info(model);
            PrePostProcessor processor = new PrePostProcessor(model);
            Tensor input_tensor_pro = new Tensor(new OvType(ElementType.U8), new Shape(1, 640, 640, 3));   //注意这个地方要改和模型窗口一致,模型是640,这里也要640
            InputInfo input_info = processor.input(0);
            InputTensorInfo input_tensor_info = input_info.tensor();
            input_tensor_info.set_from(input_tensor_pro).set_layout(new Layout("NHWC")).set_color_format(ColorFormat.BGR);

            PreProcessSteps process_steps = input_info.preprocess();
            process_steps.convert_color(ColorFormat.RGB).resize(ResizeAlgorithm.RESIZE_LINEAR)
                .convert_element_type(new OvType(ElementType.F32)).scale(255.0f).convert_layout(new Layout("NCHW"));
            Model new_model = processor.build();
            // -------- Step 3. Loading a model to the device --------
            start = DateTime.Now;
            CompiledModel compiled_model = core.compile_model(new_model, device);
            end = DateTime.Now;
            Slog.INFO("3. Loading a model to the device success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 4. Create an infer request --------
            start = DateTime.Now;
            InferRequest infer_request = compiled_model.create_infer_request();
            end = DateTime.Now;
            Slog.INFO("4. Create an infer request success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 5. Process input images --------
            start = DateTime.Now;
            Mat image = new Mat(image_path); // Read image by opencvsharp
            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));
            Cv2.Resize(max_image, max_image, new OpenCvSharp.Size(640, 640));   //注意这个地方要改和模型窗口一致,模型是640,这里也要640
            float factor = (float)(max_image_length / 640.0);
            end = DateTime.Now;
            Slog.INFO("5. Process input images success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 6. Set up input data --------
            start = DateTime.Now;
            Tensor input_tensor = infer_request.get_input_tensor();
            Shape input_shape = input_tensor.get_shape();
            byte[] input_data = new byte[input_shape[1] * input_shape[2] * input_shape[3]];
            //max_image.GetArray<int>(out input_data);
            Marshal.Copy(max_image.Ptr(0), input_data, 0, input_data.Length);
            IntPtr destination = input_tensor.data();
            Marshal.Copy(input_data, 0, destination, input_data.Length);

            end = DateTime.Now;
            Slog.INFO("6. Set up input data success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            // -------- Step 7. Do inference synchronously --------
            infer_request.infer();
            start = DateTime.Now;
            infer_request.infer();
  
            end = DateTime.Now;
            Slog.INFO("7. Do inference synchronously success, time spend:" + (end - start).TotalMilliseconds + "ms.");

            // -------- Step 8. Get infer result data --------
            start = DateTime.Now;
            Tensor output_tensor = infer_request.get_output_tensor();
            int output_length = (int)output_tensor.get_size();
            float[] output_data = output_tensor.get_data<float>(output_length);
            end = DateTime.Now;
            Slog.INFO("8. Get infer result data success, time spend:" + (end - start).TotalMilliseconds + "ms.");

             -------- Step 9. Process reault  --------
            start = DateTime.Now;

            List<Rect> position_boxes = new List<Rect>();
            List<int> class_ids = new List<int>();
            List<float> confidences = new List<float>();

            // Preprocessing output results
            for (int i = 0; i < output_data.Length / 6; i++)
            {
                int s = 6 * i;
                if ((float)output_data[s + 4] > 0.2)
                {
                    float cx = output_data[s + 0];
                    float cy = output_data[s + 1];
                    float dx = output_data[s + 2];
                    float dy = output_data[s + 3];
                    int x = (int)((cx) * factor);
                    int y = (int)((cy) * factor);
                    int width = (int)((dx - cx) * factor);
                    int height = (int)((dy - cy) * factor);
                    Rect box = new Rect();
                    box.X = x;
                    box.Y = y;
                    box.Width = width;
                    box.Height = height;

                    position_boxes.Add(box);
                    class_ids.Add((int)output_data[s + 5]);
                    confidences.Add((float)output_data[s + 4]);
                }
            }


            end = DateTime.Now;
            Slog.INFO("9. Process reault  success, time spend:" + (end - start).TotalMilliseconds + "ms.");
            for (int i = 0; i < class_ids.Count; i++)
            {
                int index = i;
                Cv2.Rectangle(image, position_boxes[index], new Scalar(0, 0, 255), 2, LineTypes.Link8);
                Cv2.Rectangle(image, new OpenCvSharp.Point(position_boxes[index].TopLeft.X, position_boxes[index].TopLeft.Y + 30),
                    new OpenCvSharp.Point(position_boxes[index].BottomRight.X, position_boxes[index].TopLeft.Y), new Scalar(0, 255, 255), -1);
                Cv2.PutText(image, class_ids[index] + "-" + confidences[index].ToString("0.00"),
                    new OpenCvSharp.Point(position_boxes[index].X, position_boxes[index].Y + 25),
                    HersheyFonts.HersheySimplex, 0.8, new Scalar(0, 0, 0), 2);
            }
            string output_path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(image_path)),
                Path.GetFileNameWithoutExtension(image_path) + "_result.jpg");
            Cv2.ImWrite(output_path, image);
            Slog.INFO("The result save to " + output_path);
            Cv2.ImShow("Result", image);
            Cv2.WaitKey(0);
        }
    }
}


五、输出结果

        运行代码,可以得到统计的代码加载、预处理、推理的运行时间,并且得到识别结果,类别号、置信度、以及位置

       有显卡的话,可将模型AUTO改为GPU,运行时间会更快些。。。

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

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

相关文章

构建LangChain应用程序的示例代码:37、基于LangGraph的文档检索与答案生成系统教程

这示例它实现了一个基于LangGraph的系统&#xff0c;用于处理文档检索和生成答案的过程。 好的&#xff0c;我会按照Markdown格式完整翻译并保留文件结构和格式&#xff1a; ! pip install langchain_community tiktoken langchain-openai langchainhub chromadb langchain lan…

聚类分析 #数据挖掘 #Python

聚类分析&#xff08;Cluster Analysis&#xff09;是一种无监督机器学习方法&#xff0c;主要用于数据挖掘和数据分析中&#xff0c;它的目标是将一组对象或观测值根据它们之间的相似性或相关性自动分组&#xff0c;形成不同的簇或类别。聚类分析并不预先知道每个观测值的具体…

cloudflare worker访问自己的网站显示521问题解决

写在前面&#xff1a;如果你的网站不是在80端口上运行的&#xff0c;开一下80端口可能就行了… 1.在cloudlare上添加域名 前文搭建了自己的DNS服务器&#xff08;DNS服务器搭建&#xff09;&#xff0c;现在想通过自己的DNS服务器解析域名&#xff0c;需要四步&#xff1a; 添…

2Y0A21 GP2Y0A21YK0F 红外测距传感器 arduino使用教程

三根线 正极负极信号线 确认自己的三根线分别代表什么&#xff0c;我们的颜色可能不一样 附一张我买的传感器他们的说明图 正极 接 开发板5V 负极 接开发板GND 信号线 接A0 代码arduino ide上面写 // Infračerven senzor vzdlenosti Sharp 2Y0A21// připojen potře…

vscode-关闭ts与js语义校验

1.ts与js语义校验 TypeScript&#xff08;TS&#xff09;和JavaScript&#xff08;JS&#xff09;在语义校验方面有很大的不同。TypeScript是一种静态类型检查的编程语言&#xff0c;它是JavaScript的一个超集&#xff0c;为JavaScript添加了类型系统和其他一些特性。而JavaScr…

软件测试技术(一):软件测试流程

软件测试流程 软件测试流程如下&#xff1a; 测试计划测试设计测试执行 单元测试集成测试确认测试系统测试验收测试回归测试验证活动 测试计划 测试计划由测试负责人来编写&#xff0c;用于确定各个测试阶段的目标和策略。这个过程将输出测试计划&#xff0c;明确要完成的测…

有个网友问Webview2如何另存为mhtml

有个网友问Webview2如何另存为mhtml 。俺查了一下&#xff0c;Webview2没有直接的saveas函数。然后我查到 之后我就使用 webview2 capture 这2个关键字去查询&#xff0c;果然搜到了 一段代码 然后我把这段代码 改成成C#的&#xff0c; string data await webView21.CoreWebV…

这四个有意思的工具,很香

提醒英雄 提醒英雄应用是一款能够帮助用户彻底解决健忘症的应用程序。该应用创建的事项会完全同步到通知中心&#xff0c;并且持续保持在锁屏界面上&#xff0c;只要打开手机&#xff0c;用户就会看到之前设置的提醒事项。这种设计确保了用户在任何时候都能及时收到提醒&#…

[C#] opencvsharp对Mat数据进行序列化或者反序列化以及格式化输出

【简要介绍】 在OpenCVSharp中&#xff0c;FileStorage类用于将数据&#xff08;包括OpenCV的Mat类型数据&#xff09;序列化为XML或YAML格式的文件&#xff0c;以及从这些文件中反序列化数据。以下是关于FileStorage类用法的详细说明&#xff1a; 写入数据&#xff08;序列化…

铠侠全面复产:NAND价格还会涨吗?

近期&#xff0c;日本经济新闻&#xff08;Nikkei&#xff09;报道指出&#xff0c;经历长达20个月的产能削减后&#xff0c;全球第四大三维NAND闪存制造商铠侠已全面恢复生产。这一转变不仅标志着铠侠再次全力投入到市场份额的争夺中&#xff0c;也可能预示着闪存市场价格即将…

深入探究RTOS的任务调度

阅读引言&#xff1a; 此文将会从一个工程文件&#xff0c; 一步一步的分析RTOS的任务调度实现&#xff0c; 这里选用FreeRTOS分析&#xff0c; 别的也差不多的&#xff0c; 可能在细节上有少许不一样。 目录 1&#xff0c; 常见嵌入式实时操作系统 2&#xff0c; 任务调度的…

数据库系统概述选择简答概念复习

目录 一、组成数据库的三要素 二、关系数据库特点 三、三级模式、二级映像 四、视图和审计提供的安全性 审计(Auditing) 视图(Views) 五、grant、revoke GRANT REVOKE 六、三种完整性 实体完整性 参照完整性 自定义完整性 七、事务的特性ACDI 原子性(Atomicity)…

基于卷积变分自编码器的心电信号异常检测

代码较为简单&#xff0c;运行代码如下&#xff1a; # Built-in libraries # import os import time import random import pandas as pd import numpy as np from tqdm import tqdm # ------------------------------- # Visualization libraries # import matplotlib.p…

179海关接口源码并实践:打造具备跨境报关功能的多平台商城

一、跨境电商的发展与挑战 随着全球化的快速发展&#xff0c;跨境电商成为了各国商家开拓市场的重要方式。然而&#xff0c;跨境电商在面临海关报关等复杂流程时&#xff0c;常常遇到各种挑战。为了解决这些问题&#xff0c;许多商家开始关注179海关接口源码的使用&#xff0c…

mkv文件怎么转成mp4?教你四种常见的转换方法!

mkv文件怎么转成mp4&#xff1f;大家在使用mkv文件的时候有没有遇到过下面这些缺点&#xff0c;首先是mkv的兼容性不行&#xff0c;这体验在它不方便分享上面&#xff0c;很有可能我们分享出去但是对方根本无法进行接受&#xff0c;这就导致我们需要进行额外的操作才能分享&…

qt登录和闹钟实现

qt实现登录 #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);// 去掉头部this->setWindowFlag(Qt::FramelessWindowHint);// 去掉空白部分this->s…

汽车IVI中控开发入门及进阶(二十七):车载摄像头vehicle camera

前言: 在车载IVI、智能座舱系统中,有一个重要的应用场景就是视频。视频应用又可分为三种,一种是直接解码U盘、SD卡里面的视频文件进行播放,一种是手机投屏,就是把手机投屏软件已视频方式投屏到显示屏上显示,另外一种就是对视频采集设备(主要就是摄像头Camera)的视频源…

反激开关电源保险丝以及热敏电阻的选型

保险丝&#xff08;2A/250V&#xff09; 保险丝的选型及计算 1、保险丝的作用就是在电路出现故障造成过流甚至短路时能及时切断电路电源的联系。&#xff08; 保护后 级电路&#xff0c;一旦出现故障&#xff0c;由于电流过大温度过高&#xff0c;保险丝熔断 &#xff09; 2、…

硫碳复合材料可用作固态电池正极材料 锂硫电池是重要下游

硫碳复合材料可用作固态电池正极材料 锂硫电池是重要下游 硫碳复合材料&#xff0c;是半固态电池、固态电池的正极材料&#xff0c;主要用于金属硫电池制造领域&#xff0c;在锂硫电池应用中研究热度最高。 锂硫电池&#xff0c;一种二次电池&#xff0c;以硫元素为正极&#x…

【多模态】39、HRVDA | 基于高分辨率输入的高效文档助手(CVPR2024)

论文&#xff1a;HRVDA: High-Resolution Visual Document Assistant 代码&#xff1a;暂无 出处&#xff1a;中国科学技术大学 | 腾讯优图 贡献点&#xff1a; 作者提出了高分辨率视觉文档助手 HRVDA&#xff0c;能直接处理高分辨率图像输入作者提出了内容过滤机制和指令过…