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

目录

一、下载

三、开始训练

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.mfbz.cn/a/875751.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

春之学习:SpringBoot在线教育平台构建

第三章 系统分析 3.1 系统设计目标 在线视频教育平台主要是为了用户方便对首页、个人中心、用户管理、教师管理、课程信息管理、课程类型管理、我的收藏管理、系统管理、订单管理等信息进行查询&#xff0c;也是为了更好的让管理员进行更好存储所有数据信息及快速方便的检索功能…

僵尸网络开发了新的攻击技术和基础设施

臭名昭著的 Quad7 僵尸网络&#xff08;也称为 7777 僵尸网络&#xff09;不断发展其运营&#xff0c;最近的发现表明其目标和攻击方法都发生了重大变化。 根据 Sekoia.io 的最新报告&#xff0c;Quad7 的运营商正在开发新的后门和基础设施&#xff0c;以增强僵尸网络的弹性&a…

K8s利用etcd定时备份集群结合钉钉机器人通知

如何通过脚本的方式进行K8s集群的备份 查看K8s中master节点中etcd集群的状态 kubectl get pods -n kube-system | grep etcd由于使用的etcd服务是K8s搭建时自身携带的,并不是独立搭建的etcd集群信息。使用 K8s 搭建集群时,etcd 是 Kubernetes 集成的一个重要组件因此需要查…

DDR3AXI4接口读写仿真

前文已经介绍了DDR3和AXI4总线的相关知识&#xff0c;我们知道MIG ip核除了可以生成native接口还能生成AXI4接口&#xff0c;今天就练习一下将AXI4接口的DDR3打包成FIFO。首先我们生成一个AXI4接口的MIG ip核&#xff0c;其余步骤与Native接口的ip核相同&#xff0c;如果我们勾…

vue3.0 使用echarts与echarts-gl 实现3D饼图

效果 安装echarts npm install echarts npm install echarts-gl 3d饼图组件&#xff1a; <template><div style"width: 100%; height: 100%" ref"echart"></div> </template><script setup> import { reactive, ref, onMou…

质量追溯管理在MES系统中举足轻重

1. 质量追溯管理概述 质量追溯管理是指通过记录和监控产品在生产过程中的关键信息&#xff0c;确保在产品出现质量问题时&#xff0c;能够迅速追踪到问题源头&#xff0c;并采取相应措施的一种管理方法。在现代制造业中&#xff0c;质量追溯管理对于保障产品质量、提升客户满意…

关于 vue/cli 脚手架实现项目编译运行的源码解析

1.vue项目运行命令解析 在日常开发中&#xff0c;vue 项目通过vue-cli-service脚手架包将项目运行起来&#xff0c;常用的命令例如&#xff1a; npm run serve npm run build 上述执行命令实际一般对应为项目中 package.json 文件的 scripts属性中编写的脚本命令&#xff0c;在…

Python 课程5-NumPy库

在数据处理和科学计算中&#xff0c;NumPy 是一个非常强大且基础的库。除了基本的创建数组功能之外&#xff0c;NumPy 提供了许多强大的函数和方法&#xff0c;用于执行高级的矩阵运算、统计分析、逻辑操作等。以下是一些常用且非常有用的 NumPy 指令&#xff0c;涵盖了创建数组…

java: 程序包org.junit.jupiter.api不存在

明明idea没有报错&#xff0c;引用包也没问题&#xff0c;为啥提示java: 程序包org.junit.jupiter.api不存在&#xff1f; 配置&#xff01;还TMD是配置&#xff01; 如果是引用包的版本不对或者其他&#xff0c;直接就是引用报错或者pom里面飘红了。 这个应该是把generat…

设置使用阿里云服务器DNS

由于云服务器是从腾讯云迁移到阿里云&#xff0c;然后使用ssl验证时一直无法使用dns验证&#xff0c;也无法创建三级域名&#xff0c;原来需要把阿里云服务器改成阿里云的dns使用 如果使用其他服务器DNS会下面会显示当前DNS服务器&#xff0c;

冯诺依曼体结构与系统

冯诺依曼结构 我们的计算机&#xff0c;以及服务器&#xff0c;还有我我们日常使用的洗衣机都遵循冯诺依曼体结构。 以我们日常使用qq聊天时举例&#xff0c;冯诺依曼体结构可以这样画 截至目前&#xff0c;我们所认识的计算机&#xff0c;都是有一个个的硬件组件组成 输入单元…

基于SpringBoot+Vue+MySQL的美术馆管理系统

系统展示 用户前台界面 管理员后台界面 系统背景 随着文化艺术产业的蓬勃发展&#xff0c;美术馆作为展示与传播艺术的重要场所&#xff0c;其管理工作变得日益复杂。为了提升美术馆的运营效率、优化参观体验并加强艺术品管理&#xff0c;我们开发了基于SpringBootVueMySQL的美…

SAP B1 营销单据 - 单据字段介绍(中)

背景 营销单据&#xff0c;SAP B1 中一群神秘的单据&#xff0c;在官方说明文档中并未指明【营销单据】范围&#xff0c;却经常使用这一说法。它们结构相似&#xff0c;在 用户定义字段(UDF) 功能里统一受【营销单据】部分增加字段的影响&#xff0c;可以相互复制&#xff08;…

POI生成Excel文件增加数据验证(下拉序列)

POI版本为5.2.2 正常的如果不超过255字符的数据验证可以参照如下代码&#xff1a; /*** <p>设置某列的数据验证</p>* param Sheet 作用于哪一个sheet* param colIndex 需要增加数据验证的列的索引* String[] names 数据验证的序列&#xff0c;就是excel下拉列表的内…

codesys将自定义的功能块或者函数保存到本地库

将通过ST代码实现的自定义功能保存到codesys的本地库&#xff0c;其他project可以直接实现调用。提高灵活性和效率。 1、创建库工程 这里可能会提示涉及个别库没有安装或版本更新&#xff0c;根据提示安装对应库或更新即可。 2、添加功能块和函数 3、编写功能块和函数的参数定…

【Linux】查看操作系统开机时初始化的驱动模块列表的一个方法

这个方法是摸索出来的&#xff0c;也不一定对&#xff1a; 1、驱动层module_init(module_init_function)作为模块初始化&#xff0c;并且提供模块内部初始化的函数名&#xff1b; 2、找到所有驱动目录drivers下所有module_init(module_init_function)&#xff0c;在内核6.9.0…

js 深入理解生成器

目录 概述1 . 生成器基础2. 与普通函数的区别3. 通过 yield 中断执行3.1 yield 是干嘛的&#xff1f;3.2 yield 和 return 的区别3.3 每个生成器对象作用域都是独立的3.4 yeild 的使用位置3.5 生成器对象作为可迭代对象3.6 使用 yield 实现输入和输出3.6.1 yield实现输入3.6.1 …

4G物联网智能电表是什么?什么叫4G物联网智能电表?

4G物联网智能电表是一种结合了4G无线通信技术的新型电能计量设备&#xff0c;用于实时采集和传输用户的用电数据。它通过集成现代信息技术和电力电子技术&#xff0c;不仅能够精确测量电力消耗&#xff0c;还能实现远程数据传输、数据分析、远程控制等多种功能。本文将详细介绍…

【运维监控】influxdb 2.0+grafana 监控java 虚拟机以及方法耗时情况(2)

运维监控系列文章入口&#xff1a;【运维监控】系列文章汇总索引 文章目录 四、grafana集成influxdb监控java 虚拟机以及方法耗时情况1、添加grafana数据源2、添加grafana的dashboard1&#xff09;、选择新建dashboard方式2&#xff09;、导入dashboard 3、验证 关于java应用的…

CSS学习17--CSS3 过渡、2D变形、3D变形、动画

CSS3 过渡、2D变形、3D变形、动画 一、过渡二、2D变形 transform1.移动 translate2.缩放 scale3. 旋转 rotate4. 倾斜 skew 三、3D变形1. rotateX&#xff08;&#xff09;rotateY&#xff08;&#xff09; rotateZ&#xff08;&#xff09;2. 体会透视 perspective3. translat…