使用yolov8训练自己的数据集

使用yolov8训练自己的数据集

默认自己将yolov8的环境配置好了

1.准备自己的数据集

image里面全是图像,txt里面是对应图像的标注文件,以及class.txt文件

image-20240415140849090

2.数据集的划分

创建一个spilt_data.py文件

import os, shutil
from sklearn.model_selection import train_test_split

val_size = 0.1
test_size = 0.2
postfix = 'jpg'
imgpath = 'VOCdevkit/JPEGImages'
txtpath = 'VOCdevkit/txt'

os.makedirs('images/train', exist_ok=True)
os.makedirs('images/val', exist_ok=True)
os.makedirs('images/test', exist_ok=True)
os.makedirs('labels/train', exist_ok=True)
os.makedirs('labels/val', exist_ok=True)
os.makedirs('labels/test', exist_ok=True)

listdir = [i for i in os.listdir(txtpath) if 'txt' in i and i != 'classes.txt']
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:
    shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), 'images/train/{}.{}'.format(i[:-4], postfix))
    shutil.copy('{}/{}'.format(txtpath, i), 'labels/train/{}'.format(i))

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

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))

数据集转化

如果自己的数据集是VOC格式的,需要将xml的标注文件转化成txt格式的,创建一个xml2txt.py文件(注意将路径修改)

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 = 'jpg'
    imgpath = 'VOCdevkit/JPEGImages'   
    xmlpath = 'VOCdevkit/Annotations' #xml标注文件路径
    txtpath = 'VOCdevkit/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}')

训练

yolo detect train data=E:\project\ultralytics\ultralytics\data.yaml model=yolov8n.pt epochs=300

data.yaml为数据信息

指标评价

yolo  model=runs/detect/train/weights/best.pt data=E:\project\ultralytics\ultralytics\data.yaml 

本地文件推理

 yolo predict model=runs/detect/train/weights/best.pt source=test_data    #source为本地文件的路径
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
YOLOv8(You Only Look Once Version 8)是一个实时物体检测算法,它在YOLO系列中是最新的版本之一。要在Python使用YOLOv8训练自己的数据集并进行测试,你需要遵循以下步骤: 1. 准备环境: - 安装必要的库:首先确保已经安装了PyTorch和`torchvision`,以及`yolov8`库。如果还没有,可以使用`pip install torch torchvision yolov8`命令安装。 2. 数据预处理: - 导入数据:将你的数据集划分为训练集、验证集和测试集。使用`pandas`或`cv2`读取图像,并将它们转换为YOLOv8模型所需的格式,通常需要调整尺寸并添加标签。 3. 训练模型: - 加载预训练权重:YOLOv8提供了预训练的权重文件,你可以选择加载这些权重作为起点进行微调。 - 实例化`yolov8`模型:通过`Yolov8()`函数创建一个模型实例。 - 定义损失函数和优化器:YOLOv8训练通常使用预定义的损失函数和优化器。 - 训练循环:遍历训练集,执行前向传播、计算损失、反向传播和更新权重。 ```python from yolov8 import YOLOv8, create_model, optim model = create_model("yolov8s") optimizer = optim(model.parameters(), lr=0.001) for epoch in range(num_epochs): for images, targets in train_dataloader: # ... [训练步骤] ``` 4. 保存训练好的模型: - 定期保存训练过程中的最优模型,以便于后续使用。 5. 测试模型: - 对测试集应用训练好的模型,计算精度和召回率等指标。你可以使用`model.evaluate`方法。 ```python model.eval() for images, _ in test_dataloader: predictions = model(images) # ... [评估步骤,比如非极大抑制(NMS)和指标计算] ``` 6. 检测实时应用: - 如果是实时检测,你可以将模型集成到一个视频流或者摄像头捕获的帧中,展示检测结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值