txt文件转换为XML python

很多目标检测的模型都是默认需要VOC的文件输入格式
手上数据label是txt文件。为了避免不必要的bug,还是选择转换下格式

将数据按VOC形式放置
在这里插入图片描述

文件夹内容
Annotations存放生成的XML文件
JPEGImagesJPG图片
ImageSets标明训练集测试集的txt文件
Labelsstxt格式的Label文件
# -*- coding: utf-8 -*-

from xml.dom.minidom import Document
import os
import os.path
from PIL import Image
import importlib
import sys
importlib.reload(sys)


xml_path = "Annotations\\"
img_path = "JPEGImages\\"
ann_path = "Labelss\\"

if not os.path.exists(xml_path):
    os.mkdir(xml_path)


def writeXml(tmp, imgname, w, h, objbud, wxml):
    doc = Document()
    # owner
    annotation = doc.createElement('annotation')
    doc.appendChild(annotation)
    # owner
    folder = doc.createElement('folder')
    annotation.appendChild(folder)
    folder_txt = doc.createTextNode("VOC2007")
    folder.appendChild(folder_txt)

    filename = doc.createElement('filename')
    annotation.appendChild(filename)
    filename_txt = doc.createTextNode(imgname)
    filename.appendChild(filename_txt)
    # ones#
    source = doc.createElement('source')
    annotation.appendChild(source)

    database = doc.createElement('database')
    source.appendChild(database)
    database_txt = doc.createTextNode("The VOC2007 Database")
    database.appendChild(database_txt)

    annotation_new = doc.createElement('annotation')
    source.appendChild(annotation_new)
    annotation_new_txt = doc.createTextNode("PASCAL VOC2007 ")
    annotation_new.appendChild(annotation_new_txt)

    image = doc.createElement('image')
    source.appendChild(image)
    image_txt = doc.createTextNode("flickr")
    image.appendChild(image_txt)
    # onee#
    # twos#
    size = doc.createElement('size')
    annotation.appendChild(size)

    width = doc.createElement('width')
    size.appendChild(width)
    width_txt = doc.createTextNode(str(w))
    width.appendChild(width_txt)

    height = doc.createElement('height')
    size.appendChild(height)
    height_txt = doc.createTextNode(str(h))
    height.appendChild(height_txt)

    depth = doc.createElement('depth')
    size.appendChild(depth)
    depth_txt = doc.createTextNode("3")
    depth.appendChild(depth_txt)
    # twoe#
    segmented = doc.createElement('segmented')
    annotation.appendChild(segmented)
    segmented_txt = doc.createTextNode("0")
    segmented.appendChild(segmented_txt)


    # threes#
    object_new = doc.createElement("object")
    annotation.appendChild(object_new)

    name = doc.createElement('name')
    object_new.appendChild(name)
    name_txt = doc.createTextNode('cancer')
    name.appendChild(name_txt)

    pose = doc.createElement('pose')
    object_new.appendChild(pose)
    pose_txt = doc.createTextNode("Unspecified")
    pose.appendChild(pose_txt)

    truncated = doc.createElement('truncated')
    object_new.appendChild(truncated)
    truncated_txt = doc.createTextNode("0")
    truncated.appendChild(truncated_txt)

    difficult = doc.createElement('difficult')
    object_new.appendChild(difficult)
    difficult_txt = doc.createTextNode("0")
    difficult.appendChild(difficult_txt)
    # threes-1#
    bndbox = doc.createElement('bndbox')
    object_new.appendChild(bndbox)

    xmin = doc.createElement('xmin')
    bndbox.appendChild(xmin)
    
    #objbud存放[类别,xmin,ymin,xmax,ymax]
    xmin_txt = doc.createTextNode(objbud[1])
    xmin.appendChild(xmin_txt)

    ymin = doc.createElement('ymin')
    bndbox.appendChild(ymin)
    ymin_txt = doc.createTextNode(objbud[2])
    ymin.appendChild(ymin_txt)

    xmax = doc.createElement('xmax')
    bndbox.appendChild(xmax)
    xmax_txt = doc.createTextNode(objbud[3])
    xmax.appendChild(xmax_txt)

    ymax = doc.createElement('ymax')
    bndbox.appendChild(ymax)
    ymax_txt = doc.createTextNode(objbud[4])
    ymax.appendChild(ymax_txt)
    # threee-1#
    # threee#

    tempfile = tmp + "test.xml"
    with open(tempfile, "wb") as f:
        f.write(doc.toprettyxml(indent="\t", newl="\n", encoding="utf-8"))

    rewrite = open(tempfile, "r")
    lines = rewrite.read().split('\n')
    newlines = lines[1:len(lines) - 1]

    fw = open(wxml, "w")
    for i in range(0, len(newlines)):
        fw.write(newlines[i] + '\n')

    fw.close()
    rewrite.close()
    os.remove(tempfile)
    return



for files in os.walk('E:\ssd_pytorch_cancer\data\cancer_or_not\Labels'):
    print(files)
    temp = "/temp/"
    if not os.path.exists(temp):
        os.mkdir(temp)
    for file in files[2]:
        print(file + "-->start!")
        img_name = os.path.splitext(file)[0] + '.jpg'
        fileimgpath = img_path + img_name
        im = Image.open(fileimgpath)
        width = int(im.size[0])
        height = int(im.size[1])

        filelabel = open(ann_path + file, "r")
        lines = filelabel.read().split(' ')
        obj = lines[:len(lines)]

        filename = xml_path + os.path.splitext(file)[0] + '.xml'
        writeXml(temp, img_name, width, height, obj, filename)
    os.rmdir(temp)

不过代码只使用于每个label文件只有一个标注框,可在生成bndbox节点处加入循环

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Python中将文本数据集(txt)转换XML格式的过程可以通过以下步骤完成: 1. 读取文本数据集(txt):首先使用Python文件操作功能,打开并读取文本文件。可以使用`open()`函数打开文件,并使用`read()`函数读取文件内容。将读取的内容保存在一个变量中以便后续处理。 2. 解析文本数据集:根据所给定的文本数据集格式,进行解析。可以使用字符串操作函数,例如`split()`,将文本内容按行或按特定分隔符进行切割,将每行或每个字段分割为不同的元素。将解析后的数据保存在适当的数据结构中,例如列表或字典。 3. 创建XML文档:使用Python标准库中的`xml.etree.ElementTree`模块创建一个空的XML文档,并创建根元素。 4. 将解析后的数据填充到XML中:依次遍历解析得到的数据集合,创建对应的XML元素,并将其添加到根元素下。可以使用`Element`类创建元素,然后使用`SubElement`函数将元素添加为子元素。可以通过设置元素的属性值和文本内容来将数据添加到XML中。 5. 将XML保存到文件:使用`ElementTree`类中的`ElementTree`函数将XML文档保存到文件中。可以使用`write()`函数指定保存位置和文件名。 下面是一个简单的示例代码,以说明上述步骤: ```python import xml.etree.ElementTree as ET # 读取文本数据集(txt) with open('data.txt', 'r') as file: data = file.read() # 解析文本数据集 parsed_data = data.split('\n') # 创建XML文档 xml_data = ET.Element('data') # 将解析后的数据填充到XML中 for line in parsed_data: element = ET.SubElement(xml_data, 'item') element.text = line # 将XML保存到文件 tree = ET.ElementTree(xml_data) tree.write('data.xml', encoding='utf-8') ``` 以上代码将会读取名为"data.txt"的文本文件,并将文件内容按行切割为不同的元素。接着,它将创建一个名为"data"的根元素,并将解析后的数据作为子元素添加到XML中。最后,它将保存XML文档到名为"data.xml"的文件中。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值