VOC格式标签与yolo格式标签互相转换代码

1.yolo格式转换为voc格式

import os
import glob
from PIL import Image

# 将yolo格式(txt)转换为voc格式(xml)

img_path = 'JPEGImages'
yolo_txt = 'labels'
voc_annotations = 'Annotations'

# 目标类别
labels = ['Pinhole', 'Scratch', 'Dirty', 'Fold']
# labels = ['zhen_kong', 'ca_shang', 'zang_wu', 'zhe_zhou']
# 图像存储位置
src_img_dir = img_path  # 添加你的路径
# 图像的txt文件存放位置
src_txt_dir = yolo_txt
src_xml_dir = voc_annotations

img_Lists = glob.glob(src_img_dir + '/*.jpg')

img_basenames = []
for item in img_Lists:
    img_basenames.append(os.path.basename(item))

img_names = []
for item in img_basenames:
    temp1, temp2 = os.path.splitext(item)
    img_names.append(temp1)

for img in img_names:
    im = Image.open((src_img_dir + '/' + img + '.jpg'))
    width, height = im.size

    # 打开txt文件
    gt = open(src_txt_dir + '/' + img + '.txt').read().splitlines()
    print(gt)
    if gt:
        # 将主干部分写入xml文件中
        xml_file = open((src_xml_dir + '/' + img + '.xml'), 'w')
        xml_file.write('<annotation>\n')
        xml_file.write('    <folder>VOC2007</folder>\n')
        xml_file.write('    <filename>' + str(img) + '.jpg' + '</filename>\n')
        xml_file.write('    <size>\n')
        xml_file.write('        <width>' + str(width) + '</width>\n')
        xml_file.write('        <height>' + str(height) + '</height>\n')
        xml_file.write('        <depth>3</depth>\n')
        xml_file.write('    </size>\n')
        xml_file.write('<source>\n')
        xml_file.write('    <database>Unknown</database>\n')
        xml_file.write('</source>\n')
        xml_file.write('<segmented>0</segmented>\n')
        # write the region of image on xml file
        for img_each_label in gt:
            spt = img_each_label.split(' ')  # 这里如果txt里面是以逗号‘,’隔开的,那么就改为spt = img_each_label.split(',')。
            print(f'spt:{spt}')
            xml_file.write('    <object>\n')
            xml_file.write('        <name>' + str(labels[int(spt[0])]) + '</name>\n')
            xml_file.write('        <pose>Unspecified</pose>\n')
            xml_file.write('        <truncated>0</truncated>\n')
            xml_file.write('        <difficult>0</difficult>\n')
            xml_file.write('        <bndbox>\n')

            center_x = round(float(spt[1].strip()) * width)
            center_y = round(float(spt[2].strip()) * height)
            bbox_width = round(float(spt[3].strip()) * width)
            bbox_height = round(float(spt[4].strip()) * height)
            xmin = str(int(center_x - bbox_width / 2))
            ymin = str(int(center_y - bbox_height / 2))
            xmax = str(int(center_x + bbox_width / 2))
            ymax = str(int(center_y + bbox_height / 2))

            xml_file.write('            <xmin>' + xmin + '</xmin>\n')
            xml_file.write('            <ymin>' + ymin + '</ymin>\n')
            xml_file.write('            <xmax>' + xmax + '</xmax>\n')
            xml_file.write('            <ymax>' + ymax + '</ymax>\n')
            xml_file.write('        </bndbox>\n')
            xml_file.write('    </object>\n')

        xml_file.write('</annotation>')

2.voc格式转换为yolo格式

import xml.etree.ElementTree as ET
import os

# voc格式转换为yolo格式

def convert(size, box):

    x_center = (box[0] + box[1]) / 2.0
    y_center = (box[2] + box[3]) / 2.0
    x = x_center / size[0]
    y = y_center / size[1]

    w = (box[1] - box[0]) / size[0]
    h = (box[3] - box[2]) / size[1]

    # print(x, y, w, h)
    return (x, y, w, h)


def convert_annotation(xml_files_path, save_txt_files_path, classes):
    xml_files = os.listdir(xml_files_path)
    # print(xml_files)
    for xml_name in xml_files:
        # print(xml_name)
        xml_file = os.path.join(xml_files_path, xml_name)
        out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')
        out_txt_f = open(out_txt_path, 'w')
        tree = ET.parse(xml_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))
            # b=(xmin, xmax, ymin, ymax)
            # print(w, h, b)
            bb = convert((w, h), b)
            out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')


if __name__ == "__main__":
    # 把voc的xml标签文件转化为yolo的txt标签文件
    # 1、需要转化的类别
    classes = ['pinhole', 'scratch', 'dirty', 'fold']  # 注意:这里根据自己的类别名称及种类自行更改
    # 2、voc格式的xml标签文件路径
    xml_files1 = r'Annotations'
    # 3、转化为yolo格式的txt标签文件存储路径
    save_txt_files1 = r'test'

    convert_annotation(xml_files1, save_txt_files1, classes)

参考:VOC格式xml标签与YOLO格式txt标签相互转换_ID茉莉的博客-CSDN博客_voc xml格式

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将voc标签格式转换yolo格式的步骤如下: 1. 读取voc标签文件,获取每个标注框的坐标信息和类别信息。 2. 将坐标信息转换yolo格式的相对坐标,即中心点坐标和宽高的比例。 3. 将类别信息转换yolo格式的类别编号,从开始。 4. 将转换后的标签信息保存到对应的yolo标签文件中。 划分训练集和测试集的步骤如下: 1. 将所有数据集按照一定比例分为训练集和测试集,通常是将数据集的70%作为训练集,30%作为测试集。 2. 将训练集和测试集的图像和标签文件分别存放在不同的文件夹中。 3. 在训练时,使用训练集进行模型训练,测试集用于测试模型的性能。 ### 回答2: 介绍 VOC标签格式YOLO标签格式目标检测任务中最常见的两种标签格式VOC标签格式是指PASCAL VOC数据集使用的标签格式,通常为XML格式。而YOLO标签格式是指Darknet团队开发的YOLO算法使用的标签格式,通常为txt格式。本文将介绍如何将VOC标签格式转换YOLO标签格式,并且如何划分训练集和测试集。 VOC标签格式YOLO标签格式 VOC标签格式包含每个图像中的所有目标的信息,并且每个目标都包含类别、边界框位置和部分属性(如难度)等信息。从VOC标签格式转换YOLO标签格式的关键是要将边界框位置信息归一化为0到1之间的值。YOLO标签格式只需要目标类别和边界框的中心坐标和宽度/高度比例即可。具体步骤如下: 1. 读取VOC标签格式文件,获取每张图像中的目标数量、类别、位置和部分属性等信息。 2. 对每个目标进行边界框位置信息的归一化,计算边界框中心坐标和宽度/高度比例。 3. 将每个目标的类别和边界框信息转换YOLO标签格式并保存为txt格式的文件。 划分训练集和测试集 划分训练集和测试集的目的是为了评估模型的性能。训练集用于训练模型,而测试集用于评估模型在新数据上的表现。一般来说,训练集和测试集应该互不重叠,并且测试集应该具有与训练集相似的数据分布。 划分训练集和测试集的方法很多,常见的有随机划分、按文件名划分和按目录划分等。其中,按目录划分是最常见的方法。一般来说,数据集应该先按类别分组,然后再按目录划分。例如,对于VOC数据集,可以将JPEGImages目录下的图像和Annotations目录下的标签文件分别放在同一个目录中,并按类别分组。然后,可以将每个类别的数据集划分为训练集和测试集,建议将测试集的比例设置为20-30%。 总结 将VOC标签格式转换YOLO标签格式并划分训练集和测试集是目标检测任务中非常重要的一步。这可以使得我们能够使用更多的数据来训练模型,并且能够准确评估模型在新数据上的表现。划分训练集和测试集的方法很多,需要根据数据集的特点进行选择。 ### 回答3: 首先,VOC标签格式YOLO标签格式有一些不同之处,需要进行转换VOC标签格式是一种XML文件格式,其中包含图片的基本信息、标注信息以及对象的类别、坐标等信息。而YOLO标签格式是一种txt文件格式,每一行都表示一张图片,包含该图片中物体的类别以及bounding box坐标信息等。 转换VOC格式标签YOLO格式标签可以使用Python编程语言来完成。具体操作步骤如下: 1、读取XML格式VOC标签文件,获取图片的基本信息和对象的类别、坐标信息等。 2、根据YOLO标签格式的要求,将图片基本信息和对象类别信息分别存储到txt文件的不同行中。 3、将VOC标签格式中的坐标信息转换YOLO标签格式的坐标信息。 4、将所有信息存储到txt文件中。 划分训练集和测试集也需要一定的步骤: 1、将所有图片按比例分配给训练集和测试集。 2、根据所选比例,将标签文件也分配到训练集和测试集的文件夹中。 3、在训练和测试之前,可以随机化数据集的顺序。 4、在使用YOLO进行训练和测试时,需要使用train.txt和val.txt来载入训练和测试集。 在实际的操作中,可以使用Python编写脚本来自动完成上述操作,节省时间和减少人工操作的误差。同时,开发者还可以根据需要进行自定义,如结合TensorFlow、Keras等框架进行模型训练和优化,以获得更准确的目标检测和分割结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值