xml转YOLO的txt格式(一次必成版!)

废话少说,直接上干货!

首先,我先介绍一下代码的使用,编程语言为“Python”,共有三处需按照自己的需求修改的,我都放在代码最下面了。

xml_root_path:输入你的xml格式的文件存放位置,建议全部用绝对路径
txt_save_path:输入你的txt格式的文件导出后的存放位置
classes_path:输入你的labels.txt格式的文件的存放位置(这里注意,在随便哪个地方新建一个labels.txt文件,必须叫这个名哈不然错了别找我,输入你数据集的类别名,有几类输几类,一行一个类别名,不需要加任何标点符号,逗号冒号的统统不要加,大小写一定要对,空格也不要多加,和你xml里面的类别名必须一样,不知道类别名的打开你的xml文件自己看看确认,不然输出的txt文件内容为空你也别找我,自己好好看)
import os
import glob
import xml.etree.ElementTree as ET


def get_classes(classes_path):
    with open(classes_path, encoding='utf-8') as f:
        class_names = f.readlines()
    class_names = [c.strip() for c in class_names]
    print("Classes loaded:", class_names)
    return class_names, len(class_names)


def convert(size, box):
    dw = 1.0 / size[0]
    dh = 1.0 / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    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_xml_to_yolo(xml_root_path, txt_save_path, classes_path):
    print("XML root path:", xml_root_path)
    print("TXT save path:", txt_save_path)
    print("Classes path:", classes_path)

    if not os.path.exists(txt_save_path):
        os.makedirs(txt_save_path)
    print("Directory created:", txt_save_path)

    xml_paths = glob.glob(os.path.join(xml_root_path, '*.xml'))
    print("XML files found:", xml_paths)

    classes, _ = get_classes(classes_path)

    for xml_id in xml_paths:
        print("Processing file:", xml_id)
        txt_id = os.path.join(txt_save_path, os.path.basename(xml_id)[:-4] + '.txt')
        txt = open(txt_id, 'w')
        xml = open(xml_id, encoding='utf-8')
        tree = ET.parse(xml)
        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 = 0
            if obj.find('difficult') is not None:
                difficult = obj.find('difficult').text
            cls = obj.find('name').text
            print("Class found:", cls)
            if cls not in classes or int(difficult) == 1:
                continue
            cls_id = classes.index(cls)
            xmlbox = obj.find('bndbox')
            b = (int(float(xmlbox.find('xmin').text)), int(float(xmlbox.find('xmax').text)),
                 int(float(xmlbox.find('ymin').text)), int(float(xmlbox.find('ymax').text)))
            box = convert((w, h), b)
            txt.write(str(cls_id) + ' ' + ' '.join([str(a) for a in box]) + '\n')
        txt.close()
        print("TXT file created:", txt_id)
if __name__ == '__main__':
    # 用户输入XML文件路径和TXT文件存放路径
    xml_root_path = r"C:\Users\DELL\Desktop\seaships\Annotations"
    txt_save_path = r"C:\Users\DELL\Desktop\Seaships(7000)\labels"
    classes_path = r"C:\Users\DELL\Desktop\labels.txt"
    convert_xml_to_yolo(xml_root_path, txt_save_path, classes_path)
 
你可以参考以下代码来进行xml格式yolo txt格式换: ```python import xml.etree.ElementTree as ET import os def convert(size, box): dw = 1. / size[0] dh = 1. / size[1] x = (box[0] + box[1]) / 2.0 y = (box[2] + box[3]) / 2.0 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(xml_path, txt_path): in_file = open(xml_path) out_file = open(txt_path, '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') xml_folder = '/path/to/xml/folder' txt_folder = '/path/to/txt/folder' classes = ['class1', 'class2', 'class3'] for xml_file in os.listdir(xml_folder): xml_path = os.path.join(xml_folder, xml_file) txt_file = os.path.splitext(xml_file)[0] + '.txt' txt_path = os.path.join(txt_folder, txt_file) convert_annotation(xml_path, txt_path) ``` 这段代码可以将指定文件夹中的所有xml格式的标注文件换成yolo txt格式的标注文件,其中classes变量需要根据实际情况修改。
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值