欢迎光临
我们一直在努力

Python如何实现xml格式转txt格式

本篇内容介绍了“Python如何实现xml格式转txt格式”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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、最后结果对比

创建成功

与真实数据对比误差很小

“Python如何实现xml格式转txt格式”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注云搜网网站,小编将为大家输出更多高质量的实用文章!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。