yolov10--C#接口

一、前言

     本章主要讲解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 opencvsharpint 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 resultsfor (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,这里也要640InputInfo 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 opencvsharpint 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,这里也要640float 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 resultsfor (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.rhkb.cn/news/360174.html

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

相关文章

动态规划数字三角形模型——AcWing 275. 传纸条

动态规划数字三角形模型 定义 动态规划数字三角形模型是在一个三角形的数阵中&#xff0c;通过一定规则找到从顶部到底部的最优路径或最优值。 运用情况 通常用于解决具有递推关系、需要在不同路径中做出选择以达到最优结果的问题。比如计算最短路径、最大和等。 计算其他…

服务器数据恢复—NTFS文件系统下双循环riad5数据恢复案例

服务器存储数据恢复环境&#xff1a; EMC CX4-480存储&#xff0c;该存储中有10块硬盘&#xff0c;其中有3块磁盘为掉线磁盘&#xff0c;另外7块磁盘组成一组RAID5磁盘阵列。运维人员在处理掉线磁盘时只添加新的硬盘做rebuild&#xff0c;并没有将掉线的硬盘拔掉&#xff0c;所…

重点!业内分享:如何找到自己门店的生鲜经营定位

说到经营生鲜品类 许多商超人士或许都会面临这样一个困境 即品类繁多且复杂&#xff0c;那么如何做到精准施策&#xff1f; 比如说&#xff0c;蔬菜和水果虽都归为生鲜&#xff0c;然而细分起来&#xff0c;价格和消费群体均存在差异。像蔬菜&#xff0c;价格通常较低&#…

docker入门配置

1、创建配置镜像 由于国内docker连接外网速度慢&#xff0c;采用代理 vi /etc/docker/daemon.json添加以下内容 {"registry-mirrors": ["https://9cpn8tt6.mirror.aliyuncs.com","https://dockerproxy.com","https://hub-mirror.c.163.co…

Python开发日记--手撸加解密小工具(2)

目录 1. UI设计和代码生成 2.运行代码查看效果 3.小结 1. UI设计和代码生成 昨天讨论到每一类算法设计为一个Tab&#xff0c;利用的是TabWidget&#xff0c;那么接下来就要在每个Tab里设计算法必要的参数了&#xff0c;这里我们会用到组件有Label、PushButton、TextEdit、Ra…

第4讲:pixi.js绘制舞台、随窗口大小而改变画布大小和舞台位置

基于前面写的代码&#xff0c;在gamelets的工程目录下新建一个CanvasAndStage.ts 代码如下 import {Application, Graphics} from pixi.js; // 不要忘了&#xff0c;一定要引用这个css样式&#xff0c;否则就会以默认样式显示 import ./style.css // app.view就是画布&#xf…

使用JAVA代码实现发送订阅消息以及模板消息

今天写了一个商品到货提醒的job任务&#xff0c;具体效果如下 这里用到了微信的发送订阅消息&#xff0c;主要代码是这一块的&#xff0c;最后我把发送了消息的订单存到表里&#xff0c;因为是定时任务&#xff0c;大家可不存 发送订阅消息 | 微信开放文档 /*** 微信平台-商品…

<电力行业> - 《第1课:电力行业的五大四小》

1 什么是电力行业的五大四小&#xff1f; 我们常说的电力行业的五大四小&#xff0c;指的是电力行业有实力的公司&#xff0c;分为&#xff1a;较强梯队的五大集团、较弱梯队的四小豪门。 五个实力雄厚的集团&#xff0c;分别是&#xff1a; 中国华能集团公司中国大唐集团公…

公交行业系统特点及面临的挑战

在当前城市发展中&#xff0c;公交行业作为公共交通的重要组成部分&#xff0c;承担着重要的社会责任。随着科技的进步和城市化进程的加快&#xff0c;公交行业系统也在不断地发展和完善。然而&#xff0c;从目前的发展情况来看&#xff0c;公交行业系统也呈现出一些显著的特点…

怎么加密文件夹?文件夹加密软件推荐

文件夹加密是保护电脑数据的重要方法&#xff0c;那么你知道怎么加密文件夹吗&#xff1f;下面小编就为大家推荐两款文件夹加密软件&#xff0c;帮助你安全保护重要文件夹。 文件夹加密超级大师 在加密电脑文件夹时&#xff0c;文件夹加密超级大师是你必须要了解的文件夹加密软…

uniapp顶部导航栏实现自定义功能按钮+搜索框并监听响应事件

目录 第一步&#xff1a;先下载按钮需要展示的图标&#xff08;若不使用图标&#xff0c;直接使用文字可跳过这步&#xff09; 1、点击需要的图标&#xff0c;添加入库 2、点击旁边的购物车&#xff0c;在弹出的窗口中选择下载代码 3、解压下载的压缩包&#xff0c;将这几个…

鸿蒙 HarmonyOS NEXT星河版APP应用开发-阶段二

一、鸿蒙应用界面开发 弹性布局-Flex 语法 /* 弹性容器组件 Flex() 位置&#xff1a; Flex默认主轴水平往右&#xff0c;交叉轴垂直向下&#xff08;类似Row&#xff09; 语法&#xff1a; Flex(参数对象){子组件1,子组件2,子组件3 } 属性方法&#xff1a; direction&#xf…

Hi3861 OpenHarmony嵌入式应用入门--轮询按键

本篇介绍使用轮询方式读取gpio状态来判断按键状态。 原理图如下 GPIO API API名称 说明 hi_u32 hi_gpio_init(hi_void); GPIO模块初始化 hi_u32 hi_io_set_pull(hi_io_name id, hi_io_pull val); 设置某个IO上下拉功能。 hi_u32 hi_gpio_set_dir(hi_gpio_idx id, hi_gpi…

达梦数据库(DM8)替换授权dm.key遇到的错误, lic info is different between dm.key and sysinfo.

1、报错贴图 2、报错日志提示 version info: security lic info is different between dm.key and sysinfo. 原因说明&#xff1a;dm.key授权与服务器的硬件环境不匹配引起的报错&#xff0c;如&#xff1a;cpu、操作系统版本有关。

高通安卓12-安卓系统定制2

将开机动画打包到system.img里面 在目录device->qcom下面 有lito和qssi两个文件夹 现在通过QSSI的方式创建开机动画&#xff0c;LITO方式是一样的 首先加入自己的开机动画&#xff0c;制作过程看前面的部分 打开qssi.mk文件&#xff0c;在文件的最后加入内容 PRODUCT_CO…

嘀嗒出行项目管理专家和项目管理负责人王禹华受邀为第十三届中国PMO大会演讲嘉宾

全国PMO专业人士年度盛会 嘀嗒出行项目管理专家和项目管理负责人王禹华女士受邀为第十三届中国PMO大会演讲嘉宾&#xff0c;演讲议题为“AI时代项目经理挑战机会和个人成长”。大会将于6月29-30日在北京举办&#xff0c;敬请关注&#xff01; 议题简要&#xff1a; AI时代对互…

智能雷达在线编辑名片小程序源码系统 前后端分离 带完整的安装代码包以及搭建教程

系统概述 智能雷达在线编辑名片小程序源码系统是一款集创新性、实用性和便捷性于一体的工具。它采用前后端分离的架构&#xff0c;为用户提供了一个强大的平台&#xff0c;可用于创建、编辑和管理个性化名片。 该系统旨在满足现代商业和社交需求&#xff0c;提供了一种高效、…

高校新生如何选择最优手机流量卡?

一年一度的高考已经结束了&#xff0c;愿广大学子金榜题名&#xff0c;家长们都给孩子准备好了手机&#xff0c;那么手机流量卡应该如何选择呢&#xff1f; 高校新生在选择手机流量卡时&#xff0c;需要综合考量流量套餐、费用、网络覆盖、售后服务等多方面因素&#xff0c;以下…

如何选择和优化谷歌外贸关键词?

长尾关键词是关键&#xff0c;长尾关键词是指由三个或更多词组成的更具体、更详细的搜索词组。与单个关键词相比&#xff0c;长尾关键词虽然搜索量较低&#xff0c;但往往能带来更高的转化率&#xff0c;因为它们更能精准地反映用户的搜索意图和需求 使用长尾关键词有几个优势…

全国计算机等级考试WPS如何报名

全国计算机等级考试WPS如何报名&#xff1f; 注册并登录 全国计算机等级考试官网选择 考试服务-在线报名选择报考省份-开始报名