手把书教你使用YOLOv8训练自己的数据集(附YOLOv8模型结构图)



前言

YOLOv8 是由Ultralytics团队开发的,2023 年发布。YOLO系列模型以其快速和准确的目标检测能力而闻名,并且YOLOv8继承了前几代YOLO模型的优点,同时进行了多方面的改进和优化,以提高检测性能和效率。YOLOv8 常用于目标检测、分割、关键点检测和分类。


🎓一、YOLOv8代码下载地址

源码下载地址 :链接: link
源码提取码: rpe7
注意注意注意:如果在我之前的文章下载过YOLOv8源码,不用重新下载了,没有特殊说明都是用同一个版本的源码

🍀🍀1.yolov8模型结构图

根据yolov8n.yaml画出yolo整体结构图,如下图所示
在这里插入图片描述

🎓二、YOLO环境配置教程

YOLOv9/YOLOv8/YOLOv7/YOLOv5环境都是通用的,只需要安装一次就行,如果以前安装过,可以忽略本章的环境安装

🍀🍀1.pytorch环境安装

手把书安装教程链接参考:链接: link

🍀🍀2.其他依赖安装

安装requirements.txt文件的环境,需要注释掉下面两行,前面的步骤已经单独安装pytorch了,不注释的话就会安装最新版本的pytorch,导致pytorch版本与电脑显卡不匹配,所以注释掉
在这里插入图片描述
手把书安装教程链接参考:链接: link


🎓三、数据集准备

🍀🍀1.数据集标注软件

数据集使用标注软件标注好,我这里推荐两个标注软件,一个是labelimg,另外一个是labelme,可以在python环境,使用pip install labelimg或者pip install labelme进行安装,看你选择哪个标注工具标注了,我使用labelimg标注工具

安装完成在终端输入命令启动标注软件
在这里插入图片描述
下面是软件界面
在这里插入图片描述
设置自动保存标注生成的标注文件
在这里插入图片描述

🍀🍀2.voc数据集格式转换

标注格式如果选择VOC格式,后面需要代码转换格式,如果选择yolo格式就不用转换,voc格式转换yolo格式代码如下:

import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join

classes = []

def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    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(xmlpath, xmlname):
    with open(xmlpath, "r", encoding='utf-8') as in_file:
        txtname = xmlname[:-4] + '.txt'
        txtfile = os.path.join(txtpath, txtname)
        tree = ET.parse(in_file)
        root = tree.getroot()
        filename = root.find('filename')
        img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
        h, w = img.shape[:2]
        res = []
        for obj in root.iter('object'):
            cls = obj.find('name').text
            if cls not in classes:
                classes.append(cls)
            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)
            res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
        if len(res) != 0:
            with open(txtfile, 'w+') as f:
                f.write('\n'.join(res))


if __name__ == "__main__":
    postfix = 'png'    # 图像后缀
    imgpath = r'E:\A-毕业设计代做数据\helmet\test\images'    # 图像文件路径
    xmlpath = r'E:\A-毕业设计代做数据\helmet\test\annotations'   # xml文件文件路径
    txtpath = r'E:\A-毕业设计代做数据\helmet\test\labels'      # 生成的txt文件路径
    
    if not os.path.exists(txtpath):
        os.makedirs(txtpath, exist_ok=True)
    
    list = os.listdir(xmlpath)
    error_file_list = []
    for i in range(0, len(list)):
        try:
            path = os.path.join(xmlpath, list[i])
            if ('.xml' in path) or ('.XML' in path):
                convert_annotation(path, list[i])
                print(f'file {list[i]} convert success.')
            else:
                print(f'file {list[i]} is not xml format.')
        except Exception as e:
            print(f'file {list[i]} convert error.')
            print(f'error message:\n{e}')
            error_file_list.append(list[i])
    print(f'this file convert failure\n{error_file_list}')
    print(f'Dataset Classes:{classes}')

代码需要修改的地方如下:
1.postfix参数填图片的后缀,需要注意图片格式要统一,是png格式就写png,是jpg格式就写jpg
2.imgpath参数填图片所在的路径
3.xmlpath参数填标注文件的路径
4.txtpath参数填生成的yolo格式的文件
在这里插入图片描述

🍀🍀3.数据集划分

划分训练集和验证集代码如下:

import os, shutil
from sklearn.model_selection import train_test_split


val_size = 0.2
#test_size = 0.2
postfix = 'jpg'
imgpath = r'E:\A-毕业设计代做数据\datasets\images'
txtpath =  r'E:\A-毕业设计代做数据\datasets\labels'



output_train_img_folder =r'E:\A-毕业设计代做数据\datasets\dataset_kengwa/images/train'
output_val_img_folder =  r'E:\A-毕业设计代做数据\datasets\dataset_kengwa/images/val'
output_train_txt_folder =  r'E:\A-毕业设计代做数据\datasets\dataset_kengwa\labels/train'
output_val_txt_folder =  r'E:\A-毕业设计代做数据\datasets\dataset_kengwa\labels/val'

os.makedirs(output_train_img_folder, exist_ok=True)
os.makedirs(output_val_img_folder, exist_ok=True)
os.makedirs(output_train_txt_folder, exist_ok=True)
os.makedirs(output_val_txt_folder, exist_ok=True)


listdir = [i for i in os.listdir(txtpath) if 'txt' in i]
train, val = train_test_split(listdir, test_size=val_size, shuffle=True, random_state=0)

#todo:需要test放开

# train, test = train_test_split(listdir, test_size=test_size, shuffle=True, random_state=0)
# train, val = train_test_split(train, test_size=val_size, shuffle=True, random_state=0)

for i in train:
    img_source_path = os.path.join(imgpath, '{}.{}'.format(i[:-4], postfix))
    txt_source_path = os.path.join(txtpath, i)

    img_destination_path = os.path.join(output_train_img_folder, '{}.{}'.format(i[:-4], postfix))
    txt_destination_path = os.path.join(output_train_txt_folder, i)

    shutil.copy(img_source_path, img_destination_path)
    shutil.copy(txt_source_path, txt_destination_path)

for i in val:
    img_source_path = os.path.join(imgpath, '{}.{}'.format(i[:-4], postfix))
    txt_source_path = os.path.join(txtpath, i)

    img_destination_path = os.path.join(output_val_img_folder, '{}.{}'.format(i[:-4], postfix))
    txt_destination_path = os.path.join(output_val_txt_folder, i)

    shutil.copy(img_source_path, img_destination_path)
    shutil.copy(txt_source_path, txt_destination_path)


#
# for i in train:
#     shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/images/train/{}.{}'.format(i[:-4], postfix))
#     shutil.copy('{}/{}'.format(txtpath, i), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/labels/train/{}'.format(i))
#
# for i in val:
#     shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/images/val/{}.{}'.format(i[:-4], postfix))
#     shutil.copy('{}/{}'.format(txtpath, i), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/labels/val/{}'.format(i))

#todo:需要test则放开

# for i in test:
#     shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), 'images/test/{}.{}'.format(i[:-4], postfix))
#     shutil.copy('{}/{}'.format(txtpath, i), 'labels/test/{}'.format(i))

需要修改的地方如下
在这里插入图片描述
下面四个参数只需在自己电脑任意位置新建一个文件夹就行,用于存放生成的训练集和验证集,比如新建一个文件夹叫dataset_kengwa,后面的路径不用动,如下图左边的框出来的路径覆盖成你的就行
在这里插入图片描述
数据集有以下两种方式放置,都可以进行训练,常见的数据集放置是第一种,也有开源的数据集按照第二种方式放置的,我都遇见过,也能训练起来
在这里插入图片描述

🍀🍀4.修改yolo的训练配置文件

我们需要在项目下创建一个data.yaml的文件,文件名根据数据集名称取,我这里方便演示直接叫data.yaml,如下图所示
在这里插入图片描述
代码如下,填你们自己数据集的路径,这个是训练常用模板

train: E:\Desktop\new-yolov9\yolotest\images\train  # train images (relative to 'path') 4 images
val: E:\Desktop\new-yolov9\yolotest\images\val  # val images (relative to 'path') 4 images

nc: 2

# class names
names: ['dog','cat']

🎓四、YOLOv8训练

(1)在根目录新建一个python文件,取名为:train.py,如果之前看过我的文章,已经新建过就不用重新新建了在这里插入图片描述
(2)把训练代码复制到train.py文件,如果之前看过我的文章,已经复制过了就不用重新复制了,只需修改参数就行

注意注意注意:模型配置路径改成你自己的路径,还有数据集配置文件也修改成你自己的路径
在这里插入图片描述

训练的代码如下,如果之前看过我的文章,已经复制过了就不用重新复制了,只需修改参数就行

# -*- coding: utf-8 -*-
"""
@Auth : 挂科边缘
@File :trian.py
@IDE :PyCharm
@Motto:学习新思想,争做新青年
@Email :179958974@qq.com
@qq :179958974
"""
import warnings
warnings.filterwarnings('ignore')
from ultralytics import YOLO

if __name__ == '__main__':
    # model.load('yolov8n.pt') # 加载预训练权重,改进或者做对比实验时候不建议打开,因为用预训练模型整体精度没有很明显的提升
    model = YOLO(model=r'D:\2-Python\1-YOLO\YOLOv8\new-yolov8\ultralytics-main\ultralytics\cfg\models\v8\yolov8.yaml')
    model.train(data=r'data.yaml',
                imgsz=640,
                epochs=50,
                batch=4,
                workers=0,
                device='',
                optimizer='SGD',
                close_mosaic=10,
                resume=False,
                project='runs/train',
                name='exp',
                single_cls=False,
                cache=False,
                )

训练代码的参数解释:
1.model参数:该参数填入模型配置文件的路径,改进的话建议不需要填预训练模型权重
2.data参数:该参数可以填入训练数据集配置文件的路径
3.imgsz参数:该参数代表输入图像的尺寸,指定为 640x640 像素
4.epochs参数:该参数代表训练的轮数
5.batch参数:该参数代表批处理大小,电脑显存越大,就设置越大,根据自己电脑性能设置
6.workers参数:该参数代表数据加载的工作线程数,出现显存爆了的话可以设置为0,默认是8
7.device参数:该参数代表用哪个显卡训练,留空表示自动选择可用的GPU或CPU
8.optimizer参数:该参数代表优化器类型
9.close_mosaic参数:该参数代表在多少个 epoch 后关闭 mosaic 数据增强
10.resume参数:该参数代表是否从上一次中断的训练状态继续训练。设置为False表示从头开始新的训练。如果设置为True,则会加载上一次训练的模型权重和优化器状态,继续训练。这在训练被中断或在已有模型的基础上进行进一步训练时非常有用。
11.project参数:该参数代表项目文件夹,用于保存训练结果
12.name参数:该参数代表命名保存的结果文件夹
13.single_cls参数:该参数代表是否将所有类别视为一个类别,设置为False表示保留原有类别
14.cache参数:该参数代表是否缓存数据,设置为False表示不缓存。

注意注意注意:一般做科研改进工作时候可以不用预训练权重,因为用预训练模型整体精度很难提高

总结

YOLOv9训练自己数据集到此结束,后期出一期推理的教程,有问题可以留言,创作不易,请帮忙点个爱心呗,谢谢

  • 14
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

挂科边缘(毕业版)

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

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

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

打赏作者

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

抵扣说明:

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

余额充值