修改数据集xml改变标注框位置

1.xml.dom.minidom相关知识:

1.parse返回dom对象,使用DOM的documentElement属性可以获得root Element。

DOMTree = xml.dom.minidom.parse(path) 
collection = DOMTree.documentElement

2.DOM为树形结构,每一个node 有nodeName,nodeValue和nodeValue。nodeType有:

'ATTRIBUTE_NODE'
'CDATA_SECTION_NODE'
'COMMENT_NODE'
'DOCUMENT_FRAGMENT_NODE'
'DOCUMENT_NODE'
'DOCUMENT_TYPE_NODE'
'ELEMENT_NODE'
'ENTITY_NODE'
'ENTITY_REFERENCE_NODE'
'NOTATION_NODE'
'PROCESSING_INSTRUCTION_NODE'
'TEXT_NODE'

但是nodeValue只对textNode 有效,对别的节点无效。textNode同样可以使用data属性来获得文本内容,其它节点没有data属性。

<width>zh is smart</width>
for width in collection.getElementsByTagName("width"):
    print(width.nodeValue)     #none
    print(width.firstChild.nodeValue)  #zh is smart
    widthVal = width.firstChild.data
 #width的type为element node,没有data属性,nodeValue属性对其无效
#width.firstChild 为text node,"zh is smart",其data 属性和nodeValue属性均为"zh is smart"

3.getElementsByTagName()可以根据名字来查找elements,可以得到一个nodeList.

widths = collection.getElementByTagName("width")

4.chilsNodes可以得到所有的子nodes,其中所有的文本皆为textNode。firstChild返回第一个子节点。

5.writexml()addindent=’ ‘表示子元素的缩进,newl=’\n’表示元素间的换行,encoding='utf-8’表示生成的xml的编码格式(<?xml version="1.0" encoding="utf-8"?>)。

 f = open( 'image2.xml' , 'w') 
 DOMTree.writexml(f, addindent = ' ' , newl = '\n' ,encoding = 'utf-8' )

2.下面贴应用代码:

应用背景:制作pascal voc数据集之前忘记resize,所以只能修改xml 文件中框的位置来使其匹配resize之后的图片。

import os
import xml.dom.minidom
#resize之后的宽和高
newheight = 256
newwidth = 256 
root = "/home/danale/Desktop/six/"  #视频文件夹
for xmlfile in os.listdir(root):
    DOMTree = xml.dom.minidom.parse(os.path.join(root, xmlfile))
    collection = DOMTree.documentElement
    for width in collection.getElementsByTagName("width"):
        oldwidth = int(width.firstChild.data)
        width.firstChild.data = str(newwidth)
    for height in collection.getElementsByTagName("height"):
        oldheight = int(height.firstChild.data)
        height.firstChild.data = str(newheight)
    for xmin in collection.getElementsByTagName("xmin"):
        xmin.firstChild.data = int(int(xmin.firstChild.data) / 1.0 / oldwidth* newwidth)
    for xmax in collection.getElementsByTagName("xmax"):
        xmax.firstChild.data = int(int(xmax.firstChild.data) / 1.0 / oldwidth * newwidth)
    for ymin in collection.getElementsByTagName("ymin"):
        ymin.firstChild.data = int(int(ymin.firstChild.data) / 1.0 / oldheight * newheight)
    for ymax in collection.getElementsByTagName("ymax"):
        ymax.firstChild.data = int(int(ymax.firstChild.data) / 1.0 / oldheight * newheight)
    with open(os.path.join(root, xmlfile), 'w') as fh:
        DOMTree.writexml(fh)
        print('写入name/pose OK!')
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值