Python生成PASCAL VOC格式的xml标注文件

<annotation>
  <folder>GTSDB</folder>
  <filename>000001.jpg</filename>
  <size>
    <width>500</width>
    <height>375</height>
    <depth>3</depth>
  </size>
  <object>
    <name>mouse</name>
    <difficult>0</difficult>
    <bndbox>
      <xmin>99</xmin>
      <ymin>358</ymin>
      <xmax>135</xmax>
      <ymax>375</ymax>
    </bndbox>
  </object>
</annotation>

怎样从csv或者txt格式的文件,读取bbox信息,生成xml格式的annotation文件呢?直接逐行写文件肯定可以,但是以后改起来并不太方便,\t和空格的替换也不太方便。

xml.etree.ElementTree这个包似乎挺好用的,解析和生成xml都可以。但是会产生<?xml version="1.0" ?>这样一行头部版本信息。我们不需要这个信息。使用lxml包替代xml,可以去掉它。

下面给出了一个例子

#!/usr/bin/env python
# coding:utf-8

#from xml.etree.ElementTree import Element, SubElement, tostring
from lxml.etree import Element, SubElement, tostring
import pprint
from xml.dom.minidom import parseString

node_root = Element('annotation')

node_folder = SubElement(node_root, 'folder')
node_folder.text = 'GTSDB'

node_filename = SubElement(node_root, 'filename')
node_filename.text = '000001.jpg'

node_size = SubElement(node_root, 'size')
node_width = SubElement(node_size, 'width')
node_width.text = '500'

node_height = SubElement(node_size, 'height')
node_height.text = '375'

node_depth = SubElement(node_size, 'depth')
node_depth.text = '3'

node_object = SubElement(node_root, 'object')
node_name = SubElement(node_object, 'name')
node_name.text = 'mouse'
node_difficult = SubElement(node_object, 'difficult')
node_difficult.text = '0'
node_bndbox = SubElement(node_object, 'bndbox')
node_xmin = SubElement(node_bndbox, 'xmin')
node_xmin.text = '99'
node_ymin = SubElement(node_bndbox, 'ymin')
node_ymin.text = '358'
node_xmax = SubElement(node_bndbox, 'xmax')
node_xmax.text = '135'
node_ymax = SubElement(node_bndbox, 'ymax')
node_ymax.text = '375'

xml = tostring(node_root, pretty_print=True)  #格式化显示,该换行的换行
dom = parseString(xml)
print xml

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值