Python xml转txt

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python xml转txt

l。Ve   2022-05-28 我要评论

1、前言

最近学习Yolo v5是遇见了个问题,找的数据集全是xml文件,VOC 的标注是 xml 格式的,而YOLO是.txt格式,那么问题就来了,手动提取肯定是不可能的,那只能借用程序解决咯。

2、分析xml、txt数据

这是xml树形结构

这是txt格式

总结:

1.提取object->name、bndbox->xmin,ymin,xmax,ymin

2.格式转化需要用公式转换

YOLO数据集txt格式:

x_center :归一化后的中心点x坐标

y_center : 归一化后的中心点y坐标

w:归一化后的目标框宽度

h: 归一化后的目标况高度

(此处归一化指的是除以图片宽和高)

VOC数据集xml格式

yolo的四个数据xml->txt公式
x_center((x_min+x_max)/2-1)/w_image
y_center((y_min+y_max)/2-1)/h_image
w(x_max-x_min)/w_image
h(y_max-y_min)/h_image

3、转换过程

定义两个文件夹,train放xml数据, labels放txt数据。

代码解析:

import os
import xml.etree.ElementTree as ET
import io
find_path = './train/'    #xml所在的文件
savepath='./labels/'   #保存文件

class Voc_Yolo(object):
    def __init__(self, find_path):
        self.find_path = find_path
    def Make_txt(self, outfile):
        out = open(outfile,'w') 
        print("创建成功:{}".format(outfile))
        return out
    def Work(self, count):
    #找到文件路径
        for root, dirs, files in os.walk(self.find_path):
        #找到文件目录中每一个xml文件
            for file in files:
            #记录处理过的文件
                count += 1
                #输入、输出文件定义
                input_file = find_path + file
                outfile = savepath+file[:-4]+'.txt'
                #新建txt文件,确保文件正常保存
                out = self.Make_txt(outfile)
                #分析xml树,取出w_image、h_image
                tree=ET.parse(input_file)
                root=tree.getroot()
                size=root.find('size')
                w_image=float(size.find('width').text)
                h_image=float(size.find('height').text)
                #继续提取有效信息来计算txt中的四个数据
                for obj in root.iter('object'):
                #将类型提取出来,不同目标类型不同,本文仅有一个类别->0
                    classname=obj.find('name').text
                    cls_id = classname
                    xmlbox=obj.find('bndbox')
                    x_min=float(xmlbox.find('xmin').text)
                    x_max=float(xmlbox.find('xmax').text)
                    y_min=float(xmlbox.find('ymin').text)
                    y_max=float(xmlbox.find('ymax').text)
                    #计算公式
                    x_center=((x_min+x_max)/2-1)/w_image
                    y_center=((y_min+y_max)/2-1)/h_image
                    w=(x_max-x_min)/w_image
                    h=(y_max-y_min)/h_image
                    #文件写入
                    out.write(str(cls_id)+" "+str(x_center)+" "+str(y_center)+" "+str(w)+" "+str(h)+'\n')
                out.close()
        return count
if __name__ == "__main__":
    data = Voc_Yolo(find_path)
    number = data.Work(0)
    print(number)

4、最后结果对比

创建成功

与真实数据对比误差很小

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们