批量将xml文件转换为txt文件

本文介绍了一个Python脚本,用于将目标检测数据集中的XML文件中的标签信息转换为TXT文件,便于进一步训练模型,包括标签名、边界框坐标及其在图像中的比例信息。
摘要由CSDN通过智能技术生成

将目标检测数据集中的xml标签转换为txt文件,方便训练

import os
import xml.etree.ElementTree as ET

dirpath = './1/'  # 原始XML文件的目录
newdir = './3/'  # 存放转换后TXT文件的目录

if not os.path.exists(newdir):
    os.makedirs(newdir)

for xml_file in os.listdir(dirpath):
    xml_path = os.path.join(dirpath, xml_file)
    tree = ET.parse(xml_path)
    root = tree.getroot()
    filename = root.find('filename').text

    with open(os.path.join(newdir, xml_file.split('.')[0] + '.txt'), 'w') as txt_file:
        for obj in root.findall('object'):
            label = obj.find('name').text
            bbox = obj.find('bndbox')
            xmin = float(bbox.find('xmin').text)
            ymin = float(bbox.find('ymin').text)
            xmax = float(bbox.find('xmax').text)
            ymax = float(bbox.find('ymax').text)

            width = float(root.find('size').find('width').text)
            height = float(root.find('size').find('height').text)

            x_center = (xmin + xmax) / (2 * width)
            y_center = (ymin + ymax) / (2 * height)
            w = (xmax - xmin) / width
            h = (ymax - ymin) / height

            txt_file.write(f"{label} {x_center} {y_center} {w} {h}\n")

print('转换完成!')

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值