【最全教程】VOC格式转YOLO格式数据

        在做目标检测时候,都会通过一些方法获得大量的数据集,或是网上下载,或是自己用软件一个一个的打标签。

        不会打标签的可以看下这个文章

Win10下安装LabelImg及使用技巧--全网最快最简单Win10下安装LabelImg及使用--全网最快最简单https://blog.csdn.net/Thebest_jack/article/details/124260693?spm=1001.2014.3001.5501        综合来说,网上的数据集绝大部分也是VOC数据文件

        这是为了标签数据的最大化。在日常生活中,我们也通常会打VOC格式的标签(xml文件),因为它所包含的数据最多。例如下图:

        而在使用YOLO算法的时候,我们需要使用YOLO格式的数据才可以运行代码,训练自己模型。那么什么是YOLO格式的数据呢?可以看下下面图:

        那么接下来,就跟我一起来做这些那个伟大的工作吧!

        代码已经放在了GitHub上,可以去这个【GitHub网址】下载,使用办法看ReadMe.md~

        接下来说下大体怎么使用

        在所有事情之前,你需要将XML数据的标签和图片放置到对应文件下        

        首先,需要给XML文件按照一定的比例分成train、val、test三个数据集。trainval_percent和train_percent 代表trainval和train的占比率,trainval_percent表示的是train+val之和。若不需要test集则改为1。train_percent 代表拿来训练的比例。这里我设置了trainval_percent = 0.9,
train_percent = 0.7。
        修改的话只需要修改这三部分的占比率。运行【images_tag.py】,代码如下:

# 该脚本文件需要修改第11-12行,设置train、val、test的切分的比率
import os
import random
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--xml_path', default='F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/Annotations', type=str, help='input xml label path')
parser.add_argument('--txt_path', default='F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/Imagesets', type=str, help='output txt label path')
opt = parser.parse_args()

trainval_percent = 0.9
train_percent = 0.7  #这里的train_percent 是指占trainval_percent中的
xmlfilepath = opt.xml_path
txtsavepath = opt.txt_path
total_xml = os.listdir(xmlfilepath)
if not os.path.exists(txtsavepath):
    os.makedirs(txtsavepath)

num = len(total_xml)
list_index = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list_index, tv)
train = random.sample(trainval, tr)

file_trainval = open(txtsavepath + '/trainval.txt', 'w')
file_test = open(txtsavepath + '/test.txt', 'w')
file_train = open(txtsavepath + '/train.txt', 'w')
file_val = open(txtsavepath + '/val.txt', 'w')

for i in list_index:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        file_trainval.write(name)
        if i in train:
            file_train.write(name)
        else:
            file_val.write(name)
    else:
        file_test.write(name)

file_trainval.close()
file_train.close()
file_val.close()
file_test.close()

        运行成功之后,会出现这个效果:红圈的就是生成的分类txt

        然后,将xml格式标签转换为txt格式标签。运行【voc_to_yolo.py】,代码如下:        

#该脚本文件需要修改第10行(classes)即可
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
from tqdm import tqdm
import os
from os import getcwd

sets = ['train', 'test','val']
#这里使用要改成自己的类别
classes = ['glass', 'metal', 'paper','plastic']


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
    x = round(x,6)
    w = round(w,6)
    y = round(y,6)
    h = round(h,6)
    return x, y, w, h

#后面只用修改各个文件夹的位置
def convert_annotation(image_id):
     #try:
        in_file = open('F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/Annotations/%s.xml' % (image_id), encoding='utf-8')
        out_file = open('F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/labels/%s.txt' % (image_id), 'w', encoding='utf-8')
        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))
            b1, b2, b3, b4 = b
            # 标注越界修正
            if b2 > w:
                b2 = w
            if b4 > h:
                b4 = h
            b = (b1, b2, b3, b4)
            bb = convert((w, h), b)
            out_file.write(str(cls_id) + " " +
                           " ".join([str(a) for a in bb]) + '\n')
     #except Exception as e:
         #print(e, image_id)

#这一步生成的txt文件写在data.yaml文件里
wd = getcwd()
for image_set in sets:
    if not os.path.exists('F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/labels/'):
        os.makedirs('F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/labels/')
    image_ids = open('F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/Imagesets/%s.txt' %
                     (image_set)).read().strip().split()
    list_file = open('F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/%s.txt' % (image_set), 'w')
    for image_id in tqdm(image_ids):
        list_file.write('F:/Pycharm_Projects/Data_Trans/VOC_To_YOLO/JPEGImages/%s.jpg\n' % (image_id))
        convert_annotation(image_id)
    list_file.close()

然后你会看到你的项目里多了个【labels】文件(用来存放转换后的yolo的标签)和三个txt文件。

        是不是该很简单?不会的留言评论加关注吧~~~ 

### Pascal VOC格式YOLO格式换 #### 换步骤概述 为了将Pascal VOC格式数据换为YOLO格式,需经历几个重要阶段。首先是理解两种格式之间的差异。Pascal VOC采用XML文件存储图像标注信息,而YOLO则偏好更简洁的方式——即每张图对应一个文本文件(.txt),其中每一行代表一个对象及其边界框的位置和大小[^1]。 #### Python代码实现换过程 下面提供一段Python脚本用于自动化完成此换工作: ```python import xml.etree.ElementTree as ET from os import getcwd sets=[('2007', 'train'), ('2007', 'val')] classes = ["aeroplane", "bicycle", "bird", "boat", "bottle"] 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(year, image_id): in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id)) out_file = open('VOCdevkit/VOC%s/labels/%s.txt'%(year, 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 year, image_set in sets: image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split() list_file = open('%s_%s.txt'%(year, image_set), 'w') for image_id in image_ids: list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id)) convert_annotation(year, image_id) list_file.close() ``` 上述代码遍历指定年份与类型的图片集合(训练集或验证集),读取对应的`.xml`标注文件,并将其解析成YOLO所需的格式写入相应的`.txt`文件中[^3]。 #### 结论 通过遵循以上方法,可以有效地把Pascal VOC格式数据变为适合YOLO模型使用的格式。这不仅简化了后续处理流程中的数据准备环节,同时也提高了不同框架间迁移学习的可能性。
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝胖胖▸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值