yolo的数据集txt转xml格式

对于一些用于yolo系列算法的训练中,常会用到yolo格式进行标注,yolo格式多保存为txt格式,但是用于数据增强很多代码采用xml格式才能进行数据增强,所以这个代码可以有效提供txt转成xml格式,方便使用。 

import os
import xml.etree.ElementTree as ET


def convert_txt_to_xml(txt_folder_path, xml_output_folder):
    txt_files = os.listdir(txt_folder_path)
    for txt_file in txt_files:
        if not txt_file.endswith(".txt"):
            continue

        txt_path = os.path.join(txt_folder_path, txt_file)
        xml_output_path = os.path.join(xml_output_folder, os.path.splitext(txt_file)[0] + ".xml")

        with open(txt_path, 'r') as f:
            lines = f.readlines()

        root = ET.Element("annotation")

        # Parse image file name from txt path
        image_name = os.path.splitext(txt_file)[0] + ".jpg"

        # Add image filename to XML
        filename = ET.SubElement(root, "filename")
        filename.text = image_name

        # Add image size to XML
        size = ET.SubElement(root, "size")
        width = ET.SubElement(size, "width")
        height = ET.SubElement(size, "height")
        depth = ET.SubElement(size, "depth")
        width.text = "416"  # Replace with actual image width
        height.text = "416"  # Replace with actual image height
        depth.text = "3"  # Replace with actual image depth (number of channels)

        for line in lines:
            line = line.strip().split()
            if len(line) != 5:
                continue

            class_id = line[0]
            try:
                x_center = float(line[1])
                y_center = float(line[2])
                width = float(line[3])
                height = float(line[4])
            except ValueError:
                continue

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

            object_elem = ET.SubElement(root, "object")
            name = ET.SubElement(object_elem, "name")
            bndbox = ET.SubElement(object_elem, "bndbox")

            name.text = class_id

            xmin_elem = ET.SubElement(bndbox, "xmin")
            ymin_elem = ET.SubElement(bndbox, "ymin")
            xmax_elem = ET.SubElement(bndbox, "xmax")
            ymax_elem = ET.SubElement(bndbox, "ymax")

            xmin_elem.text = str(xmin)
            ymin_elem.text = str(ymin)
            xmax_elem.text = str(xmax)
            ymax_elem.text = str(ymax)

        tree = ET.ElementTree(root)
        tree.write(xml_output_path)


# Example usage
txt_folder_path = "path/to/txt_folder"
xml_output_folder = "path/to/txt_folder"

convert_txt_to_xml(txt_folder_path, xml_output_folder)




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值