将xml转化为yolov5的训练格式txt

import os
from glob import glob
import xml.etree.ElementTree as ET

xml_dir = r'J:\mydata\indata'####xml文件夹
output_txt_dir = r'J:\mydata\labels\train'####输出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)
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用以下步骤将XML文件转换为Yolov5txt格式: 1. 首先,需要安装并配置好Python环境。 2. 使用Python的xml.etree.ElementTree库来解析XML文件。您可以使用以下代码示例: ```python import xml.etree.ElementTree as ET def parse_xml(xml_path): tree = ET.parse(xml_path) root = tree.getroot() annotations = [] for obj in root.findall('object'): name = obj.find('name').text xmin = int(obj.find('bndbox/xmin').text) ymin = int(obj.find('bndbox/ymin').text) xmax = int(obj.find('bndbox/xmax').text) ymax = int(obj.find('bndbox/ymax').text) annotations.append((name, xmin, ymin, xmax, ymax)) return annotations ``` 此函数将返回一个包含每个对象的名称和边界框坐标的列表。 3. 使用上面定义的函数解析XML文件,并将结果保存到一个列表中。假设您有一个名为`annotations`的列表。 ```python annotations = parse_xml('path/to/your/xml/file.xml') ``` 4. 将对象的名称和边界框坐标写入Yolov5txt文件中。每个对象的标签应该以以下格式写入: ``` <class_label> <x_center> <y_center> <width> <height> ``` 其中,`<class_label>`是对象的类别标签,`<x_center>`和`<y_center>`是边界框中心点的相对坐标(相对于图像的宽度和高度),`<width>`和`<height>`是边界框的宽度和高度的相对值(相对于图像的宽度和高度)。 以下是将结果写入txt文件的示例代码: ```python def write_txt(annotations, txt_path): with open(txt_path, 'w') as f: for annotation in annotations: class_label, xmin, ymin, xmax, ymax = annotation x_center = (xmin + xmax) / 2 y_center = (ymin + ymax) / 2 width = xmax - xmin height = ymax - ymin f.write(f"{class_label} {x_center} {y_center} {width} {height}\n") ``` 使用上面定义的函数将结果写入txt文件: ```python write_txt(annotations, 'path/to/your/txt/file.txt') ``` 将`'path/to/your/xml/file.xml'`替换为您的XML文件路径,将`'path/to/your/txt/file.txt'`替换为您想要保存txt文件的路径。 完成以上步骤后,您将获得一个包含对象标签的Yolov5格式txt文件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值