YoloV10 训练自己的数据集(推理,转化,C#部署)

news2024/9/28 0:55:17

目录

一、下载

三、开始训练

train.py

detect.py

export.py

超参数都在这个路径下

四、C#读取yolov10模型进行部署推理

如下程序是用来配置openvino

配置好引用后就可以生成dll了  再创建一个控件,作为显示 net framework 4.8版本的

再nuget工具箱里下载 opencvsharp4  以及openvino 

然后主流程代码

效果

我的yolov10 训练源码

C#部署yolov10源码


一、下载

       GitHub - THU-MIG/yolov10: YOLOv10: Real-Time End-to-End Object Detection

或者你可以再浏览器搜索框里直接搜索      yolov10 github

二、环境配置 

下载anaconda 并安装 在网上随意下载一个2022版本的就行

      yolov10和yolov8的文件结构差不多  所以如果你训练过其他的yolov5以上的yolo,你可以直接拷贝环境进行使用,当然你如果想配置gpu   

就需要cuda  cudnn  和 gpu版本的torch    

其他的直接pip install 即可

pip install requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

下方网站中下载你需要的版本下载时要注意对应关系,

cuda和cudnn各个版本的Pytorch下载网页版,onnx,ncnn,pt模型转化工具_cuda国内镜像下载网站-CSDN博客

三、开始训练

     有一点要注意v10版本其实是从v8版本上面改的 所以v10的预训练模型你需要自行下载  否则就会下载成v8的

    首先标注数据集  在pycharm 中下载labelimg

pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple

下载好后直接在终端输入labelimg 开始标注 训练流程基本和yolov5差不多

在yolov10的根目录下创建一个名为data的文件夹 里面再创建一个data.yaml文件 用于数据集的读取

再在根目录创建三个py文件  分别是  train.py  detect.py    export.py

train.py

from ultralytics import YOLOv10

model_yaml_path = "ultralytics/cfg/models/v10/yolov10s.yaml"
#数据集配置文件
data_yaml_path = 'data/data.yaml'
#预训练模型
pre_model_name = 'yolov10s.pt'

if __name__ == '__main__':
    #加载预训练模型
    model = YOLOv10(model_yaml_path).load(pre_model_name)
    #训练模型
    results = model.train(data=data_yaml_path,
                          epochs=450,
                          batch=8,
                          device=0,
                          name='train/exp')


# yolo export model="H:\\DL\\yolov10-main\\runs\\detect\\train\\exp\\weights\\best.pt" format=onnx opset=13 simplify

detect.py


from ultralytics import YOLOv10

import torch
if  torch.cuda.is_available():
    device = torch.device("cuda")
else:
    raise Exception("CUDA is not")

model_path = r"H:\\DL\\yolov10-main\\runs\\detect\\train\\exp4\\weights\\best.pt"
model = YOLOv10(model_path)
results = model(source=r'H:\DL\yolov10-main\dataDakeset\two_CD_double\test',
                name='predict/exp',
                conf=0.45,
                save=True,
                device='0'
                )

export.py

from ultralytics import YOLOv10
model=YOLOv10("H:\\DL\\yolov10-main\\runs\\detect\\train\\exp\\weights\\best.pt")

model.export(format='onnx')

# 'torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle'

超参数都在这个路径下

然后设置好参数就可以直接训练了

推理用detect.py 推理   转化用export.py 转化, 转化为哪种模型 就替换即可

四、C#读取yolov10模型进行部署推理

我们需要设定yolov10的模型结构

using OpenCvSharp;
using OpenVinoSharp.Extensions.result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yolov10_DLLnet
{
    public class YOLOv10Det : YOLO
    {
        public YOLOv10Det(string model_path, string engine, string device, int categ_nums, float det_thresh, float det_nms_thresh, int input_size)
            : base(model_path, engine, device, categ_nums, det_thresh, det_nms_thresh, new int[] { 1, 3, input_size, input_size },
            new List<string> { "images" }, new List<int[]> { new int[] { 1, 4 + categ_nums, 8400 } }, new List<string> { "output0" })
        {
        }

        protected override BaseResult postprocess(List<float[]> results)
        {
            List<Rect> positionBoxes = new List<Rect>();
            List<int> classIds = new List<int>();
            List<float> confidences = new List<float>();

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

                    positionBoxes.Add(box);
                    classIds.Add((int)results[0][s + 5]);
                    confidences.Add((float)results[0][s + 4]);
                }
            }
            DetResult re = new DetResult();
            // 
            for (int i = 0; i < positionBoxes.Count; i++)
            {
                re.add(classIds[i], confidences[i], positionBoxes[i]);
            }
            return re;
        }
    }
}

然后再设置各项参数 你可以再其中自己定义一个文件 里面写上你需要的类  比如置信度,类别  以及类别数量等等。为后续的dll生成做准备。

如下程序是用来配置openvino

using OpenCvSharp.Dnn;
using OpenCvSharp;
using OpenVinoSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
//using static System.Windows.Forms.Design.AxImporter;

namespace Yolov10_DLLnet
{
    public class Predictor : IDisposable
    {
        private Core core;
        private Model model;
        private CompiledModel compiled;
        private InferRequest openvino_infer;
        private Net opencv_infer;
        private string engine = null;

        public Predictor() { }

        public Predictor(string model_path, string engine, string device)
        {
            if (model_path == null)
            {
                throw new ArgumentNullException(nameof(model_path));
            }
            this.engine = engine;
            if (engine == "OpenVINO")
            {
                core = new Core();
                model = core.read_model(model_path);
                compiled = core.compile_model(model, device);
                openvino_infer = compiled.create_infer_request();
            }
        }
        public void Dispose()
        {
            openvino_infer.Dispose();
            compiled.Dispose();
            model.Dispose();
            core.Dispose();
            GC.Collect();

        }

        public List<float[]> infer(float[] input_data, List<string> input_names, int[] input_size, List<string> output_names, List<int[]> output_sizes)
        {

            List<float[]> returns = new List<float[]>();
            var input_tensor = openvino_infer.get_input_tensor();
            input_tensor.set_data(input_data);
            openvino_infer.infer();
            foreach (var name in output_names)
            {
                var output_tensor = openvino_infer.get_tensor(name);
                returns.Add(output_tensor.get_data<float>((int)output_tensor.get_size()));
            }
            return returns;
        }
    }
}

创建一个名为yolo的cs文件用于 将yolov10模型结构做引用

//using Microsoft.VisualBasic.Logging;
using OpenCvSharp;
using OpenVinoSharp.Extensions.model;
using OpenVinoSharp.Extensions.process;
using OpenVinoSharp.Extensions.result;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Yolov10_DLLnet;
using static OpenVinoSharp.Node;

namespace Yolov10_DLLnet
{
    public class YOLO : IDisposable
    {
        protected int m_categ_nums;
        protected float m_det_thresh;
        protected float m_det_nms_thresh;
        protected float m_factor;
        protected int[] m_input_size;
        protected List<int[]> m_output_sizes;
        protected List<string> m_input_names;
        protected List<string> m_output_names;

        protected List<int> m_image_size = new List<int>();

        private Predictor m_predictor;
        Stopwatch sw = new Stopwatch();
        public YOLO()
        {
            m_predictor = new Predictor();
        }
        public YOLO(string model_path, string engine, string device, int categ_nums, float det_thresh,
            float det_nms_thresh, int[] input_size, List<string> input_names, List<int[]> output_sizes, List<string> output_names)
        {
            m_predictor = new Predictor(model_path, engine, device);
            m_categ_nums = categ_nums;
            m_det_thresh = det_thresh;
            m_det_nms_thresh = det_nms_thresh;
            m_input_size = input_size;
            m_output_sizes = output_sizes;
            m_input_names = input_names;
            m_output_names = output_names;
        }
        float[] preprocess(Mat img)
        {
            m_image_size = new List<int> { (int)img.Size().Width, (int)img.Size().Height };
            Mat mat = new Mat();
            Cv2.CvtColor(img, mat, ColorConversionCodes.BGR2RGB);
            mat = Resize.letterbox_img(mat, (int)m_input_size[2], out m_factor);
            mat = Normalize.run(mat, true);
            return Permute.run(mat);
        }

        List<float[]> infer(Mat img)
        {
            List<float[]> re;
            float[] data = preprocess(img);
            re = m_predictor.infer(data, m_input_names, m_input_size, m_output_names, m_output_sizes);
            return re;
        }


        public BaseResult predict(Mat img)
        {
            List<float[]> result_data = infer(img);
            BaseResult re = postprocess(result_data);
            return re;
        }



        protected virtual BaseResult postprocess(List<float[]> results)
        {
            return new BaseResult();
        }

        public void Dispose()
        {
            m_predictor.Dispose();
        }

        public static YOLO GetYolo(string model_type, string model_path, string engine, string device,
            int categ_nums, float det_thresh, float det_nms_thresh, int input_size)
        {
            return new YOLOv10Det(model_path, engine, device, categ_nums, det_thresh, det_nms_thresh, input_size);
        }


        protected static float sigmoid(float a)
        {
            float b = 1.0f / (1.0f + (float)Math.Exp(-a));
            return b;
        }
    }
}

配置好引用后就可以生成dll了  再创建一个控件,作为显示 net framework 4.8版本的

再nuget工具箱里下载 opencvsharp4  以及openvino 

然后主流程代码

//using Microsoft.VisualBasic.Logging;
using OpenCvSharp;
using OpenVinoSharp.Extensions.process;
using OpenVinoSharp.Extensions.result;
using OpenVinoSharp.Extensions.utility;
using SharpCompress.Common;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using static OpenVinoSharp.Node;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Point = OpenCvSharp.Point;

using Yolov10_DLLnet;
using System.Drawing;
using ZstdSharp.Unsafe;


namespace YOLOV10_WinformDemo
{
    public partial class Form1 : Form
    {
        //string filePath = "";

        private YOLO yolo;
        public Form1()
        {
            InitializeComponent();
            yolo = new YOLO();
            //string model_path = "best_0613.onnx";
        }
        /// <summary>
        /// yolov10 onnx模型文件路径
        /// </summary>
        private string model_path = "H:\\YCDandPCB_Yolov5_net\\Yolov10_and_Yolov5Seg\\yolov10_Detztest\\YOLOV10_WinformDemo\\bestV10det.onnx";

        /// <summary>
        /// 开始识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            Stopwatch sw = new Stopwatch();
            OpenFileDialog openFile = new OpenFileDialog();
            string filePath = "";
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                
                filePath = openFile.FileName;
            }

            //目标检测
            //string model_path = "best_0613.onnx";
            classesLabel label = new classesLabel();
            string model_type = "YOLOv10Det";
            string engine_type = "OpenVINO";
            string device = "CPU";

            //#################   阈值   #######################################
            float score = label.Score_Threshold;
            float nms = label.NMS_Threshold;
            int categ_num = label.classes_count_1;
            int input_size = label.W_H_size_1;

            yolo = YOLO.GetYolo(model_type, model_path, engine_type, device, categ_num, score, nms, input_size);
          
            //#####################  图片推理阶段  #######################

            //System.Drawing.Image image = Image.FromFile(openFile.FileName);
            //string input_path = openFile;
            Mat img = Cv2.ImRead(filePath);
            pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(img);
            sw.Restart();
            (Mat, BaseResult) re_img = image_predict(img);
            sw.Stop();
            pictureBox2.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(re_img.Item1);
            DetResult detResult = re_img.Item2 as DetResult;
            for (int i = 0; i < detResult.count; i++)
            {
                //textBox1.Text = detResult.datas[i].lable;

                //置信度
                //textBox2.Text = detResult.datas[i].score.ToString("0.00");

                int X = detResult.datas[i].box.TopLeft.X;
                int Y = detResult.datas[i].box.TopLeft.Y;
                int W = detResult.datas[i].box.Width;
                int H = detResult.datas[i].box.Height;
                //textBox3.Text = X.ToString();
                //textBox4.Text = Y.ToString();
                //textBox5.Text = W.ToString();
                //textBox6.Text = H.ToString();
                Console.WriteLine(X);
                Console.WriteLine(Y);
            }
            // 获取并打印运行时间
            //TimeSpan ts = sw.Elapsed;
            textBox7.Text = sw.ElapsedMilliseconds.ToString();
        }
        (Mat, BaseResult) image_predict(Mat img, bool is_video = false)
        {
            Mat re_img = new Mat();

            //#############################  classes  ###################################
            classesLabel label = new classesLabel();
            List<string> class_names = label.class_names;

            //开始识别,并返回识别结果
            BaseResult result = yolo.predict(img);
            result.update_lable(class_names);
            re_img = Visualize.draw_det_result(result, img);
            return (re_img, result);
        }

        
    }
}

效果

我的yolov10 训练源码

【免费】yolov10优化代码,包含,train.py,detect.py,export.py脚本以及预训练模型资源-CSDN文库

C#部署yolov10源码

C#部署YoloV10目标检测.netframework4.8,打开即用内有(主程序和dll生成程序)资源-CSDN文库

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

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

相关文章

thinkphp6开发的通用网站系统源码

thinkphp6开发的通用网站系统源码。 基于ThinkPHP6框架开发的通用后台权限管理系统&#xff0c;底层采用国内最流行的ThinkPHP6框架&#xff0c; 支持内容管理、文章管理、用户管理、权限管理、角色管理等功能。 代码下载

Cookie和Session的对比

Cookie和Sesion 一、cookie和session创建对象 2024/9/15 10:23:59 你想了解的是如何在某种编程语言中创建和管理 cookies 和 sessions 吗&#xff1f;如果是的话&#xff0c;具体是哪个语言或框架呢&#xff1f; 2024/9/15 10:24:09 二、创建对象是客户端还是服务器 2024/…

20Kg载重30分钟续航多旋翼无人机技术详解

一、机架与结构设计 1. 材料选择&#xff1a;为了确保无人机能够承载20Kg的负载&#xff0c;同时实现30分钟的续航&#xff0c;其机架材料需选用轻质高强度的材料&#xff0c;如碳纤维或铝合金。这些材料不仅具有良好的承重能力&#xff0c;还能有效减轻无人机的整体重量&…

一步一步搭建AI智能体应用

您可以在百炼控制台以零代码的方式快速创建智能体应用&#xff0c;并将RAG&#xff08;Retrieval-Augmented Generation&#xff0c;检索增强生成&#xff09;以及插件能力集成进来。应用创建完成后&#xff0c;您可以通过控制台或API的方式来使用。 以下均以 大模型应用指代 智…

微信小程序使用 ==== 粘性布局

目录 Chrome杀了个回马枪 position:sticky简介 你可能不知道的position:sticky 深入理解粘性定位的计算规则 粘性定位其他特征 代码实现 微信小程序在scroll-view中使用sticky Chrome杀了个回马枪 position:sticky早有耳闻也有所了解&#xff0c;后来&#xff0c;Chro…

通过API接口获取下来的数据需要怎样应用?

在当今数字化时代&#xff0c;通过API接口获取数据已成为企业获取、处理和分析信息的重要手段。API接口不仅能够提高数据交互的效率&#xff0c;还能促进数据的安全性和灵活性。以下是如何将通过API接口获取的数据有效应用的一些方法和策略。 数据整合与分析 企业可以通过API接…

QPS和TPS的区别简单理解

QPS&#xff08;Queries Per Second&#xff09; QPS是指每秒查询率&#xff0c;它是衡量服务器处理能力的一个指标&#xff0c;表示服务器在一秒钟内能够响应的查询次数。这个指标通常用于数据库或服务器的性能测试&#xff0c;反映了服务器在规定时间内处理流量的能力。QPS …

浮动元素详解

浮动元素 代码实现&#xff1a; <!DOCTYPE html> <html><head><meta charset"utf-8"><title>浮动元素</title><style>#container1 {width: 400px;height: 50px;background-color: lightgrey;border: 1px solid;}#contai…

世界杯足球赛网站---附源码73185

摘 要 随着互联网的普及和足球运动的全球性影响力&#xff0c;建立一个专门的世界杯足球赛网站成为了与球迷互动和传播赛事信息的重要途径。本论文聚焦于世界杯足球赛网站的设计与实现&#xff0c;旨在探讨如何利用现代技术为球迷提供一个全方位的足球赛事体验。 通过对 Spring…

上传头像,访问本地图片

文件大坑&#xff1a; web项目&#xff1a;首先不能直接访问本地资源&#xff0c;只能够访问服务器上的资源。 所以我想就储存数据到服务器&#xff0c;但是这样有个问题就是&#xff0c;当重新启动程序时&#xff0c;服务器上的所有文件会被重新编译&#xff0c;导致之前的文…

HarmonyOS开发实战( Beta5.0)自动生成动态路由实践

鸿蒙HarmonyOS开发往期必看&#xff1a; HarmonyOS NEXT应用开发性能实践总结 最新版&#xff01;“非常详细的” 鸿蒙HarmonyOS Next应用开发学习路线&#xff01;&#xff08;从零基础入门到精通&#xff09; 介绍 本示例将介绍如何使用装饰器和插件&#xff0c;自动生成动…

【UE5】使用2DFlipbook图作为体积纹理,实现实时绘制体积纹理

这是一篇对“Creating a Volumetric Ray Marcher-Shader Bits”的学习心得 文章时间很早&#xff0c;因此这里针对UE5对原文做出兼容性修正&#xff08;为避免累赘不做出注明。链接如上&#xff0c;有需要自行学习&#xff09; 以及最后对Custom做可能的蓝图移植&#xff0c;做…

Qt中样式表常用的属性名称定义

Qt中&#xff0c;用好样式表&#xff0c;不但可以做出意想不到的酷炫效果&#xff0c;有时候也能减轻开发量&#xff0c;可能由于你不了解某些样式使用&#xff0c;想破脑袋通过代码实现的效果&#xff0c;反倒不如别人用样式&#xff0c;一两句样式脚本就搞定。 Qt中&#xff…

第T8周:猫狗识别

本文为365天深度学习训练营 中的学习记录博客原作者&#xff1a;K同学啊 ●难度&#xff1a;夯实基础⭐⭐ ●语言&#xff1a;Python3、TensorFlow2 要求&#xff1a; 1.了解model.train_on_batch()并运用 2.了解tqdm&#xff0c;并使用tqdm实现可视化进度条 拔高&#xff08…

Day11-K8S日志收集及搭建高可用的kubernetes集群实战案例

Day11-K8S日志收集及搭建高可用的kubernetes集群实战案例 0、昨日内容回顾1、日志收集1.1 K8S日志收集项目之架构图解三种方案1.2 部署ES1.3 部署kibana1.4 部署filebeat 2、监控系统2.1 部署prometheus 3、K8S二进制部署3.1 K8S二进制部署准备环境3.2 基础组件安装3.3 生成K8S…

OpenCV-Python笔记(上)

安装 全局安装 pip install opencv-python项目虚拟环境安装 # 进入项目根路径执行 .venv/bin/pip install opencv-python计算机眼中的图像 一张图片由大小比如&#xff08;100*100&#xff09;决定&#xff0c;说明存在100*100的像素点&#xff0c;每个像素点存在颜色通道&…

Science:学术大咖揭秘审稿内幕,你的稿件在审稿人那里经历了什么?

我是娜姐 迪娜学姐 &#xff0c;一个SCI医学期刊编辑&#xff0c;探索用AI工具提效论文写作和发表。 同行评审是每篇论文能够顺利发表的必经之路。Science期刊采访了来自全球各领域研究人员&#xff0c;分享关于他们作为审稿人&#xff0c;为什么接受审稿、给出审稿意见的依据、…

怎么让手机ip地址变化?介绍几种实用方法

随着网络技术的发展&#xff0c;IP地址作为网络设备的唯一标识&#xff0c;其变动对于保护个人隐私、规避网络限制等方面具有重要意义。本文将介绍几种实用的方法&#xff0c;帮助用户实现手机IP地址的变化&#xff0c;并提醒注意事项。 一、连接不同的WiFi网络‌ 连接不同的W…

记一次实战中对fastjson waf的绕过

最近遇到一个fastjson的站&#xff0c;很明显是有fastjson漏洞的&#xff0c;因为type这种字符&#xff0c;fastjson特征很明显的字符都被过滤了 于是开始了绕过之旅&#xff0c;顺便来学习一下如何waf 编码绕过 去网上搜索还是有绕过waf的文章&#xff0c;下面来分析一手&a…

ICM20948 DMP代码详解(21)

接前一篇文章&#xff1a;ICM20948 DMP代码详解&#xff08;20&#xff09; 上一回终于解析完了inv_icm20948_read_mems_reg函数&#xff0c;本回回到inv_icm20948_initialize_lower_driver函数中&#xff0c;继续往下解析该函数接下来的内容。为了便于理解和分析&#xff0c;在…