xml data format to txt data format

I have marked a batch of data sets in xml format before, but I want to use other models to train the following, and then the model needs txt type tags, so I will convert the following code by myself! ! !

1. My folder directory

images: store original images

labels: store labels in xml format

labelstxt: Store labels converted into txt format

2.xml data format

   

3. Converted txt data format

4. Code

import os
import xml.etree.ElementTree as ET


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)
classes = ["0","1"] #标签名


def convert_annotation(fileName):
    #in_file写入xml标签文件夹路径
    in_file = open(r'C:\Users\Desktop\class\labels\\'+fileName,encoding='utf-8')
    #out_file写入输出txt标签类型的存放文件夹位置
    out_file = open(r'C:\Users\Desktop\class\labelstxt\\'+fileName[:-4]+'.txt', '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'):
        cls = obj.find('name').text
        if cls not in classes:
            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')


if __name__ == '__main__':
    #xml标签文件夹路径
    files = os.listdir(r'C:\Users\Desktop\class\labels')
    for item in files:
        print(item)
        convert_annotation(item)

Guess you like

Origin blog.csdn.net/JulyLH/article/details/127875472