使用Yolov5训练自己制作的数据集,快速上手(详细图文教程)

欢迎学习yolo、ncnn系列相关文章,从训练、模型转换、精度分析,评估到部署Android端,推荐好资源:

一、YoloV5训练自己数据集并测试
二、ncnn编译和安装
三、onnx模型转ncnn模型并推理可执行程序(resnet18例子)
四、yolov5-6.0Pyotorch模型转onxx模型再转ncnn模型部署
五、训练自己YOLOv5模型转ncnn模型并部署到Android手机端


在这里插入图片描述

总结了快速上手Yolov5训练自己制作的数据集的方法,步骤都很详细,学者耐心看。

一、准备好Yolov5框架

我提供了一个已经调试好的源码包,后面的教程也都是基于我自己提供的源码包讲解的,学习者自行下载,下载源码包的方法为:文章末扫码到公众号中回复关键字:目标检测YoloV5。获取下载链接。

当然也可以下载官方给出最原始的Yolov5框架,在Github上下载,下载链接为:官网
打开链接后的样纸见下,下载5.0,对应的就是yolov5框架:

在这里插入图片描述

二、关于数据集的问题

Yolov5训练用的数据集格式是yolo格式,Yolov3训练用的数据集格式是VOC格式,这是两种训练模型使用数据集不同的地方,关于数据集格式的选择,我推荐VOC格式,在打标签的时候就直接制作为VOC数据集格式,后期可以用一段代码就直接将VOC数据集转换为yolo数据集,特别的方便,这样就可以打一次标签的数据集用在多种训练模型上,省事。

VOC数据集的制作详见我另外的一篇博客,里面我详细介绍了VOC数据集的制作,链接为:VOC数据集制作

三、VOC格式数据集转yolo格式数据集

VOC格式数据集转yolo格式数据集,还是采用Yolov3存放数据集的文件,将包含VOC数据集的文件直接复制到Yolov5的根目录下,运行下面代码就可以直接将VOC格式数据集转为yolo格式数据集,代码会自动的分出训练集,验证集,分配比例可以自定义设置。怎么复制文件?见下:

在这里插入图片描述

在文件VOCdevkit中包含的内容见下:

在这里插入图片描述

在Yolov5项目中直接运行以下代码,就可以将VOC格式数据集转为yolo格式数据集了,代码见下:

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import random
from shutil import copyfile

classes = ["Before a whole","After a whole","Chest former","Chest after","Raise hand before","Raise hand after","Global left position","Global right position","Front face","Left face","Right face"]        ##这里要写好标签对应的类
# classes=["ball"]

TRAIN_RATIO = 80     #表示将数据集划分为训练集和验证集,按照2:8比例来的


def clear_hidden_files(path):
    dir_list = os.listdir(path)
    for i in dir_list:
        abspath = os.path.join(os.path.abspath(path), i)
        if os.path.isfile(abspath):
            if i.startswith("._"):
                os.remove(abspath)
        else:
            clear_hidden_files(abspath)


def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(image_id):
    in_file = open('VOCdevkit/VOC2007/Annotations/%s.xml' % image_id)
    out_file = open('VOCdevkit/VOC2007/YOLOLabels/%s.txt' % image_id, 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
             float(xmlbox.find('ymax').text))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    in_file.close()
    out_file.close()


wd = os.getcwd()
wd = os.getcwd()
data_base_dir = os.path.join(wd, "VOCdevkit/")
if not os.path.isdir(data_base_dir):
    os.mkdir(data_base_dir)
work_sapce_dir = os.path.join(data_base_dir, "VOC2007/")
if not os.path.isdir(work_sapce_dir):
    os.mkdir(work_sapce_dir)
annotation_dir = os.path.join(work_sapce_dir, "Annotations/")
if not os.path.isdir(annotation_dir):
    os.mkdir(annotation_dir)
clear_hidden_files(annotation_dir)
image_dir = os.path.join(work_sapce_dir, "JPEGImages/")
if not os.path.isdir(image_dir):
    os.mkdir(image_dir)
clear_hidden_files(image_dir)
yolo_labels_dir = os.path.join(work_sapce_dir, "YOLOLabels/")
if not os.path.isdir(yolo_labels_dir):
    os.mkdir(yolo_labels_dir)
clear_hidden_files(yolo_labels_dir)
yolov5_images_dir = os.path.join(data_base_dir, "images/")
if not os.path.isdir(yolov5_images_dir):
    os.mkdir(yolov5_images_dir)
clear_hidden_files(yolov5_images_dir)
yolov5_labels_dir = os.path.join(data_base_dir, "labels/")
if not os.path.isdir(yolov5_labels_dir):
    os.mkdir(yolov5_labels_dir)
clear_hidden_files(yolov5_labels_dir)
yolov5_images_train_dir = os.path.join(yolov5_images_dir, "train/")
if not os.path.isdir(yolov5_images_train_dir):
    os.mkdir(yolov5_images_train_dir)
clear_hidden_files(yolov5_images_train_dir)
yolov5_images_test_dir = os.path.join(yolov5_images_dir, "val/")
if not os.path.isdir(yolov5_images_test_dir):
    os.mkdir(yolov5_images_test_dir)
clear_hidden_files(yolov5_images_test_dir)
yolov5_labels_train_dir = os.path.join(yolov5_labels_dir, "train/")
if not os.path.isdir(yolov5_labels_train_dir):
    os.mkdir(yolov5_labels_train_dir)
clear_hidden_files(yolov5_labels_train_dir)
yolov5_labels_test_dir = os.path.join(yolov5_labels_dir, "val/")
if not os.path.isdir(yolov5_labels_test_dir):
    os.mkdir(yolov5_labels_test_dir)
clear_hidden_files(yolov5_labels_test_dir)

train_file = open(os.path.join(wd, "yolov5_train.txt"), 'w')
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'w')
train_file.close()
test_file.close()
train_file = open(os.path.join(wd, "yolov5_train.txt"), 'a')
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'a')
list_imgs = os.listdir(image_dir)  # list image files
prob = random.randint(1, 100)
print("Probability: %d" % prob)
for i in range(0, len(list_imgs)):
    path = os.path.join(image_dir, list_imgs[i])
    if os.path.isfile(path):
        image_path = image_dir + list_imgs[i]
        voc_path = list_imgs[i]
        (nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))
        (voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))
        annotation_name = nameWithoutExtention + '.xml'
        annotation_path = os.path.join(annotation_dir, annotation_name)
        label_name = nameWithoutExtention + '.txt'
        label_path = os.path.join(yolo_labels_dir, label_name)
    prob = random.randint(1, 100)
    print("Probability: %d" % prob)
    if (prob < TRAIN_RATIO):  # train dataset
        if os.path.exists(annotation_path):
            train_file.write(image_path + '\n')
            convert_annotation(nameWithoutExtention)  # convert label
            copyfile(image_path, yolov5_images_train_dir + voc_path)
            copyfile(label_path, yolov5_labels_train_dir + label_name)
    else:  # test dataset
        if os.path.exists(annotation_path):
            test_file.write(image_path + '\n')
            convert_annotation(nameWithoutExtention)  # convert label
            copyfile(image_path, yolov5_images_test_dir + voc_path)
            copyfile(label_path, yolov5_labels_test_dir + label_name)
train_file.close()
test_file.close()

运行上面代码后,新转换得到的yolo数据集见下:

在这里插入图片描述

上图中,我已经标明了哪个文件中存放训练用的数据集,验证集和哪个文件存放标签等的对应文件位置。

四、训练模型

数据集制作好后就可以开始训练我们自己的模型了,这里我提供一个我自己已经调试通的源码包,建议学习者下载后按照我下面的步骤调试,训练成功的概率也较大些,我也是在官方的原始框架基础上进行改进后运行的,中间也有很多坑,这些坑在我代码中已经补好了,学习者可以放心下载使用,另外我的源码包中还提供了数据集,学习者可以直接使用。

下载好解压后的文件夹样纸见下:

在这里插入图片描述

在正式开始训练前需要修改一些地方,见下:

(1)修改data里配置文件的参数:

在这里插入图片描述

(2)修改models文件中的配置文件:

在这里插入图片描述

在这里插入图片描述

(3)配置文件修改好后,修改train.py文件中的参数:

在这里插入图片描述

修改好以上参数后就可以直接运行train.py文件开始训练了。

五、启用tensorboard查看训练过程的参数变化情况

在控制面板终端输入以下命令,运行后会生成一个网址,打开这个网址就可以实时查看训练过程的变化了,见下:

tensorboard --logdir=runs

如果打开网址的端口被占用了,也可以自定义端口号,输入以下命令:

tensorboard --logdir=runs --port==6007

在这里插入图片描述

打开生成网址后的样纸见下,从图中就可以看到每一轮训练过程的变化情况:

在这里插入图片描述

六、在训练时可能会遇到的问题

6.1 虚拟内存不够

问题1:虚拟内存不够,解决方法见下:

在这里插入图片描述

6.2 显存溢出

问题2:显存爆了(溢出了),解决办法修改batch-size,电脑配置一般的话就改小一些,见下:

在这里插入图片描述

在这里插入图片描述

或者也可以通过下面的办法解决,修改CPU的核心数,配置高的话可以改高一点,训练的快,配置低的话改低一点就不会溢出了:

在这里插入图片描述

七、检测训练好的模型

训练完成后,用训练好的模型检测图片或视频。

7.1 图片检测

修改文件detect.py中的一些参数,见下:

在这里插入图片描述

在这里插入图片描述

运行上面修改后的detect.py文件,检测好后会将检测结果存放到runs–>detect–>exp路径下,到这个路径下查看训练好的模型检测的检测结果,如下:

在这里插入图片描述

7.2 视频实时检测

需要修改的参数见下:

在这里插入图片描述

检测结果同样会存在路径runs–>detect–>exp下,按照提示去查看即可。

7.2.1 电脑摄像头报错问题

补:在调用电脑自带摄像头时可能会报一个错误,见下:

在这里插入图片描述

解决方法,修改utils中文件datasets.py文件中280行代码,见下:

在这里插入图片描述

修改好后再运行代码,就可以正常调用电脑自带摄像头检测了,如下:

在这里插入图片描述

八、总结

以上就是使用Yolov5训练自己制作的数据集快速上手的方法,提前准备好数据集,只需要修改源码包中的几个文件参数就可以训练使用了。
想学习YoloV3的,可以看另外一篇博文:YoloV3

总结不易,多多支持,谢谢!

  • 44
    点赞
  • 249
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 22
    评论
YOLO系列是基于深度学习的端到端实时目标检测方法。 PyTorch版的YOLOv5轻量而性能高,更加灵活和易用,当前非常流行。 本课程将手把手地教大家使用labelImg标注和使用YOLOv5训练自己的数据集。课程实战分为两个项目:单目标检测(足球目标检测)和多目标检测(足球和梅西同时检测)。 本课程的YOLOv5使用ultralytics/yolov5,在Windows系统上做项目演示。包括:安装YOLOv5、标注自己的数据集、准备自己的数据集、修改配置文件、使用wandb训练可视化工具、训练自己的数据集、测试训练出的网络模型和性能统计。 希望学习Ubuntu上演示的同学,请前往 《YOLOv5(PyTorch)实战:训练自己的数据集(Ubuntu)》课程链接:https://edu.csdn.net/course/detail/30793  本人推出了有关YOLOv5目标检测的系列课程。请持续关注该系列的其它视频课程,包括:《YOLOv5(PyTorch)目标检测实战:训练自己的数据集》Ubuntu系统 https://edu.csdn.net/course/detail/30793Windows系统 https://edu.csdn.net/course/detail/30923《YOLOv5(PyTorch)目标检测:原理与源码解析》课程链接:https://edu.csdn.net/course/detail/31428《YOLOv5目标检测实战:Flask Web部署》课程链接:https://edu.csdn.net/course/detail/31087《YOLOv5(PyTorch)目标检测实战:TensorRT加速部署》课程链接:https://edu.csdn.net/course/detail/32303《YOLOv5目标检测实战:Jetson Nano部署》课程链接:https://edu.csdn.net/course/detail/32451《YOLOv5+DeepSORT多目标跟踪与计数精讲》课程链接:https://edu.csdn.net/course/detail/32669《YOLOv5实战口罩佩戴检测》课程链接:https://edu.csdn.net/course/detail/32744《YOLOv5实战中国交通标志识别》课程链接:https://edu.csdn.net/course/detail/35209《YOLOv5实战垃圾分类目标检测》课程链接:https://edu.csdn.net/course/detail/35284       
YOLO系列是基于深度学习的端到端实时目标检测方法。 PyTorch版的YOLOv5轻量而高性能,更加灵活和易用,当前非常流行。 本课程将手把手地教大家使用labelImg标注和使用YOLOv5训练自己的数据集。课程实战分为两个项目:单目标检测(足球目标检测)和多目标检测(足球和梅西同时检测)。  本课程的YOLOv5使用ultralytics/yolov5,在Windows和Ubuntu系统上分别做项目演示。包括:安装YOLOv5、标注自己的数据集、准备自己的数据集(自动划分训练集和验证集)、修改配置文件、使用wandb训练可视化工具、训练自己的数据集、测试训练出的网络模型和性能统计。 除本课程《YOLOv5实战训练自己的数据集(Windows和Ubuntu演示)》外,本人推出了有关YOLOv5目标检测的系列课程。请持续关注该系列的其它视频课程,包括:《YOLOv5(PyTorch)目标检测:原理与源码解析》课程链接:https://edu.csdn.net/course/detail/31428《YOLOv5目标检测实战:Flask Web部署》课程链接:https://edu.csdn.net/course/detail/31087《YOLOv5(PyTorch)目标检测实战:TensorRT加速部署》课程链接:https://edu.csdn.net/course/detail/32303《YOLOv5目标检测实战:Jetson Nano部署》课程链接:https://edu.csdn.net/course/detail/32451《YOLOv5+DeepSORT多目标跟踪与计数精讲》课程链接:https://edu.csdn.net/course/detail/32669《YOLOv5实战口罩佩戴检测》课程链接:https://edu.csdn.net/course/detail/32744《YOLOv5实战中国交通标志识别》课程链接:https://edu.csdn.net/course/detail/35209 《YOLOv5实战垃圾分类目标检测》课程链接:https://edu.csdn.net/course/detail/35284  
使用Yolov5训练钢铁数据集,你需要准备好Yolov5框架并将数据集转换为Yolo格式。Yolov5训练使用数据集格式是Yolo格式,而不是VOC格式。所以你需要将钢铁数据集转换为Yolo格式。你可以使用一段代码将VOC格式数据集转换为Yolo格式,这样可以方便地在多种训练模型上使用同一个标注好的数据集。一旦你准备好了Yolov5框架和转换好格式的数据集,你可以使用以下命令来训练模型: ``` python train.py --cfg yolov5s.yaml --data your_data.yaml --weights '' --epochs 5 ``` 其中,`yolov5s.yaml`是Yolov5的配置文件,`your_data.yaml`是你的数据集配置文件,`''`表示从头开始训练,`5`表示训练5个epochs。你也可以使用训练的模型来加载并继续训练,命令如下: ``` python train.py --cfg yolov5s.yaml --data your_data.yaml --weights yolov5s.pt --epochs 5 ``` 这样就可以使用Yolov5框架来训练钢铁数据集了。 #### 引用[.reference_title] - *1* *2* [使用Yolov5训练自己制作数据集快速上手](https://blog.csdn.net/qq_40280673/article/details/125168930)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [YOLOv5详细使用教程,以及使用yolov5训练自己的数据集](https://blog.csdn.net/weixin_41010198/article/details/106785253)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

视觉研坊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值