xml转换txt格式代码

介绍

只需要有一个xml文件即可直接转换为txt,简单方便又快捷,而且有进度条。默认保存路径是这个这个转换文件路径下的txt文件夹。

在这里插入图片描述

代码

import os
import re
from tqdm import tqdm
classes = []
classes_dict = {}
def convert(Imgsize, box):
    width, height = Imgsize
    xmin, ymin, xmax, ymax = box
    dw = max(xmin, xmax) - min(xmin, xmax)
    dh = max(ymin, ymax) - min(ymin, ymax)
    x_ = (xmin + xmax) / 2.0
    y_ = (ymin + ymax) / 2.0
    cx = round(x_ / width, 6)
    cy = round(y_ / height, 6)
    w = round(dw / width, 6)
    h = round(dh / height, 6)
    return [cx, cy, w, h]

def save_txt(namepath, text):
    with open(namepath, 'w') as f:
        f.write(text)

def convert_annotation(xml_path, name):
    xml_name = os.path.join(xml_path, name)
    with open(xml_name, "r", encoding="utf-8") as f1:
        text = f1.read().replace("\n", "")
        text = text.replace(" ", "")
    img_size = re.findall("<width>([0-9]+)</width>.*?<height>([0-9]+)</height>", text)[0]
    # find_datas = re.findall(
    #     "<object>.*?<name>([a-z|A-Z]*?)</name>.*?<xmin>([0-9]+?)</xmin>.*?<ymin>([0-9]+?)</ymin>.*?<xmax>([0-9]+?)</xmax>.*?<ymax>([0-9]+?)</ymax>",
    #     text)
    find_datas = re.findall(
        "<object>.*?<name>([^<]+)</name>.*?<xmin>([0-9]+?)</xmin>.*?<ymin>([0-9]+?)</ymin>.*?<xmax>([0-9]+?)</xmax>.*?<ymax>([0-9]+?)</ymax>",
        text)

    savetext = ""
    for item in find_datas:
        class_ = item[0]
        if class_ not in classes:
            classes.append(class_)
            classes_dict[class_] = len(classes) - 1

        imgsize = [int(img_size[0]), int(img_size[1])]
        box = [int(item[1]), int(item[2]), int(item[3]), int(item[4])]
        site = convert(imgsize, box)
        savetext += "{0} {1} {2} {3} {4}".format(classes_dict[class_], site[0], site[1], site[2], site[3])
        savetext += "\n"
    name = name.split(".")[0]
    save_txt(labels_p + "/" + name + ".txt", savetext.strip())
    # print(classes_dict)
    # print(classes)
if __name__ == "__main__":
    # root_path = os.getcwd()
    xml_DIR = r"E:\data\jinjudata\VOCdevkit\VOC2023\Annotations"
    OUTPUT_DIR = r"E:\data\jinjudata\VOCdevkit\txt"

    labels_p = os.path.join(OUTPUT_DIR)  # txt保存输出路径
    try:
        os.makedirs(labels_p)
    except:
        pass
    xml_path = os.path.join(xml_DIR)  # xml的源文件夹
    xml_list = sorted(os.listdir(xml_path))
    #进度条
    total_files = len(xml_list)
    with tqdm(total=total_files, desc="Processing XML Files") as pbar:
        for name in xml_list:
            convert_annotation(xml_path, name)
            pbar.update(1)

参考
将xml文件转yolov5训练数据txt标签文件

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以参考以下代码来进行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变量需要根据实际情况修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值