【存档】Autodl训练yolov5自标数据集(helmet为例)

环境配置

镜像选择:
PyTorch 1.9.0
Python 3.8(ubuntu18.04)
Cuda 11.1

source activate
create -n yolo python=3.8
conda activate yolo
pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html

代码下载

git config --global url.https://github.com/.insteadOf git://github.com/
git clone git://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt

数据集

上传数据集zip

  1. 生成文件
import os
import random
 
trainval_percent = 0.9  # 训练和验证集所占比例,剩下的0.1就是测试集的比例
train_percent = 0.8  # 训练集所占比例,可自己进行调整
xmlfilepath = '../yolov5/helmet/Annotations'
txtsavepath = '../yolov5/helmet/ImageSets/Main'
total_xml = os.listdir(xmlfilepath)
# print(total_xml)
num = len(total_xml)
list = range(num)
# print(list)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)
 
ftrainval = open('../yolov5/helmet/ImageSets/Main/trainval.txt', 'w')
ftest = open('../yolov5/helmet/ImageSets/Main/test.txt', 'w')
ftrain = open('../yolov5/helmet/ImageSets/Main/train.txt', 'w')
fval = open('../yolov5/helmet/ImageSets/Main/val.txt', 'w')
 
for i in list:
    name = total_xml[i][:-4] + '\n'
    # print(name)
    if i in trainval:
        ftrainval.write(name)
        if i in train:
            ftrain.write(name)
        else:
            fval.write(name)
    else:
        ftest.write(name)
 
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

  1. xml_txt格式转换
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
#sets设置的就是
sets=['train', 'val', 'test']
 
 
# classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
classes = ["hat", "person"]  # 修改为自己的label
 
def convert(size, box):
    dw = 1./(size[0])  # 有的人运行这个脚本可能报错,说不能除以0什么的,你可以变成dw = 1./((size[0])+0.1)
    dh = 1./(size[1])  # 有的人运行这个脚本可能报错,说不能除以0什么的,你可以变成dh = 1./((size[0])+0.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(image_id):
    in_file = open('../yolov5/helmet/Annotations/%s.xml'%(image_id))
    out_file = open('../yolov5/helmet/labels/%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')
 
wd = getcwd()
 
for image_set in sets:
    if not os.path.exists('../yolov5/helmet/labels/'):  # 修改路径(最好使用全路径)
        os.makedirs('../yolov5/helmet/labels/')  # 修改路径(最好使用全路径)
    image_ids = open('../yolov5/helmet/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()  # 修改路径(最好使用全路径)
    list_file = open('../yolov5/helmet/%s.txt' % (image_set), 'w')  # 修改路径(最好使用全路径)
    for image_id in image_ids:
        list_file.write('../yolov5/helmet/JPEGImages/%s.jpg\n' % (image_id))  # 修改路径(最好使用全路径)
        convert_annotation(image_id)
    list_file.close()
 
  1. 新建yaml文件
train: ../yolov5/helmet/train.txt #此处是xml_2_txt.py生成的train.txt的路径,不要弄成Main文件夹下的.txt
val: ../yolov5/helmet/val.txt #此处是xml_2_txt.py生成的train.txt的路径,不要弄成Main文件夹下的.txt
test: ../yolov5/helmet/test.txt #此处是xml_2_txt.py生成的train.txt的路径,不要弄成Main文件夹下的.txt
 
# Classes
nc: 2  # number of classes 数据集类别数量
names: ['hat', 'person']  # class names 数据集类别名称,注意和标签的顺序对应
  1. 因为初始的放图片的文件夹是JPEGImages,而yolov5默认的图片和标签对应的文件夹叫做images,所以要改动dataloader.py中的代码
def img2label_paths(img_paths):
    # Define label paths as a function of image paths
    sa, sb = f'{os.sep}JPEGImages{os.sep}', f'{os.sep}labels{os.sep}'  # /images/, /labels/ substrings
    return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
  1. 修改yolov5s.yaml
在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值