python中的txt文件转换为XML

 更新时间:2022年12月14日 17:11:34   作者:LGDDDDDD  
这篇文章主要介绍了python中的txt文件转换为XML问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

txt文件转换为XML

很多目标检测的模型都是默认需要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节点处加入循环

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • python实现静态服务器

    python实现静态服务器

    这篇文章主要为大家详细介绍了python实现静态服务器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-09-09
  • Python中pickle模块的使用详解

    Python中pickle模块的使用详解

    这篇文章主要介绍了Python中pickle模块的使用详解,python的pickle模块提供了一个简答的持久化功能,可以将对象以文件的形式存放在磁盘上,pickle模块实现了基本的数据序列化和反序列化,需要的朋友可以参考下
    2023-08-08
  • django orm模糊查询、正则匹配多个值方式

    django orm模糊查询、正则匹配多个值方式

    这篇文章主要介绍了django orm模糊查询、正则匹配多个值方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • python八种降维方法汇总

    python八种降维方法汇总

    在Python中,有多种降维方法可以使用,本文就来介绍八种降维方法以及使用场景,具有一定的参考价值,感兴趣的可以一下,感兴趣的可以了解一下
    2023-10-10
  • Python Pycurl的属性与方法案例详解

    Python Pycurl的属性与方法案例详解

    这篇文章主要介绍了Python Pycurl的属性与方法案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-09-09
  • 利用OpenCV+Tensorflow实现的手势识别

    利用OpenCV+Tensorflow实现的手势识别

    这几天没事,想着再学点一些视觉识别方向的东西,因为之前做了验证码识别,有了机器学习的信心,因此这次打算做个手势识别,下面这篇文章主要给大家介绍了关于利用OpenCV+Tensorflow实现的手势识别的相关资料,需要的朋友可以参考下
    2022-11-11
  • anaconda创建、查看、激活与删除虚拟环境指令总结

    anaconda创建、查看、激活与删除虚拟环境指令总结

    在跑项目时常常会安装很多的包,也通常会遇到需要安装指定版本的包,以及包与包不兼容的问题,下面这篇文章主要给大家介绍了关于anaconda创建、查看、激活与删除虚拟环境指令的相关资料,需要的朋友可以参考下
    2022-11-11
  • 编写Python脚本来获取Google搜索结果的示例

    编写Python脚本来获取Google搜索结果的示例

    这篇文章主要介绍了编写Python脚本来获取Google搜索结果的示例,也是利用Python编写爬虫的一个简单实现,需要的朋友可以参考下
    2015-05-05
  • python实现随机漫步算法

    python实现随机漫步算法

    这篇文章主要为大家详细介绍了python实现随机漫步算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-08-08
  • 一看就懂得Python的math模块

    一看就懂得Python的math模块

    今天小编就为大家分享一篇关于Python的math模块,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10

最新评论