python的xml转txt(linux)

本文介绍了如何使用Python脚本读取XML标注文件,对图像中的对象进行归一化处理,并将其转换为YOLO所需的.txt格式,便于训练模型。脚本中定义了类别标签和相应的坐标转换函数。
摘要由CSDN通过智能技术生成
import os
from glob import glob
import xml.etree.ElementTree as ET

xml_dir = r'D:\llq\yolov5-master\yolov5-master\NEU-DET\ANNOTATIONS'####xml文件夹
output_txt_dir = r'D:\llq\yolov5-master\yolov5-master\NEU-DET\txt'####输出yolo所对应格式的文件夹

###进行归一化操作
def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    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 deconvert(size, (x,y,w,h)):
#     x *= size[0]
#     w *= size[0]
#     y *= size[1]
#     h *= size[1]
#
#     b0 = (x+1)-w/2
#     b1 = (x+1)+w/2
#     b2 = (y+1)-h/2
#     b3 = (y+1)+h/2
#     return b0, b1, b2, b3

def load_xml():####这里是你自己的分类
    classes = ['crazing','inclusion','patches', 'pitted_surface ', 'rolled-in_scale ', 'scratches']

    xml_list = glob(os.path.join(xml_dir, '*.xml'))
    # print(len(xml_list), xml_list)
    count_pictures = {}
    count_detection = {}

    count = 0
    class_num0 = 0
    class_num1 = 0
    class_num2 = 0
    class_num3 = 0
    class_num4 = 0
    class_num5 = 0

    for file in xml_list:
        count = count + 1
        imgName = file.split('\\')[-1][:-4]  # 文件名,不包含后缀
        imglabel = os.path.join(output_txt_dir, imgName + '.txt')  # 创建TXT(文件夹路径加文件名加.TXT)
        # print(imglabel)
        out_file = open(imglabel, 'w', encoding='UTF-8')  # 以写入的方式打开TXT
        tree = ET.parse(file)
        root = tree.getroot()
        for child in root:
            if child.tag == 'size':
                w = child[0].text
                h = child[1].text
            if child.tag == 'object':
                x_min = child[4][0].text
                y_min = child[4][1].text
                x_max = child[4][2].text
                y_max = child[4][3].text

                box = convert((int(w), int(h)), (int(x_min), int(x_max), int(y_min), int(y_max)))
                label = child[0].text
                if label in classes:##按照上面的顺序填写标签,如果超过这些自己增加复制就行了
                    if label == 'crazing':
                        label = '0'
                        class_num0 += 1
                        out_file.write(str(label) + ' ' + ' '.join([str(round(a, 6)) for a in box]) + '\n')  # 把内容写入TXT中
                    if label == 'inclusion':
                        label = '1'
                        class_num1 += 1
                        out_file.write(str(label) + ' ' + ' '.join([str(round(a, 6)) for a in box]) + '\n')
                    if label == 'patches':
                        label = '2'
                        class_num2 += 1
                        out_file.write(str(label) + ' ' + ' '.join([str(round(a, 6)) for a in box]) + '\n')
                    if label == 'pitted_surface':
                        label = '3'
                        class_num3 += 1
                        out_file.write(str(label) + ' ' + ' '.join([str(round(a, 6)) for a in box]) + '\n')
                    if label == 'rolled-in_scale':
                        label = '4'
                        class_num4 += 1
                        out_file.write(str(label) + ' ' + ' '.join([str(round(a, 6)) for a in box]) + '\n')
                    if label == 'scratches':
                        label = '5'
                        class_num5 += 1
                        out_file.write(str(label) + ' ' + ' '.join([str(round(a, 6)) for a in box]) + '\n')
    print('ALL:', count, " crazing:", class_num0, "  inclusion:", class_num1, "  patches:", class_num2,
          "  pitted_surface:", class_num3, "  rolled-in_scale:", class_num4, "  scratches: ", class_num5)
    return len(xml_list), classes, count_pictures, count_detection  # return 用在函数内部表示当调用该函数时,


if __name__ == '__main__':
    classes = load_xml()
    print(classes)

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用readFileToXML模块中的readFileToXML类来将txt文件换为xml文件。首先,你需要在Linux上运行脚本,所以你需要修改调用方式。在代码中,你可以看到通过sys.argv获取命令行输入的文件路径,如果没有输入参数,则提示用户输入文件路径。然后,你可以实例化readFileToXML类,并传入文件路径作为参数。最后,调用makeXML方法将txt文件换为xml文件。\[1\] 如果你想调试代码,你可以使用调试代码部分中的代码。你可以实例化readFileToXML类,并传入文件路径作为参数。然后,你可以调用makeXML方法将txt文件换为xml文件。你还可以打印JSON格式和XML格式的数据,以及路径和文件名。\[2\] 对于换的具体格式,你可以参考引用\[3\]中给出的示例。每个txt文件中的数据表示一个类别,包括xmin、ymin、w和h。你需要将这些数据换为对应的xml格式。 #### 引用[.reference_title] - *1* *2* [使用PythonTXT文本内容读取后生成指定XML格式的文件](https://blog.csdn.net/weixin_34104341/article/details/91746431)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [python 批量txtxml](https://blog.csdn.net/m0_46529214/article/details/124495369)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李烁.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值