python实现批量修改Pascal VOC数据集Annotation

    学习DL过程中,各位同学一定会经历数据的标定工作,本篇按照Pascal VOC数据集格式,通过python实现Annotation文件的批量修改.    举个例子

<?xml version="1.0" ?><annotation>
	<folder>HK</folder>
	<filename>101.jpg</filename>
	<path>/home/li//home/li/101.jpg</path>
	<source>
		<database>Unknown</database>
	</source>
	<size>
		<width>1280</width>
		<height>720</height>
		<depth>3</depth>
	</size>
	<segmented>0</segmented>
	<object>
		<name>Person</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>46</xmin>
			<ymin>220</ymin>
			<xmax>109</xmax>
			<ymax>402</ymax>
		</bndbox>
	</object>
	<object>
		<name>Person</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>237</xmin>
			<ymin>227</ymin>
			<xmax>300</xmax>
			<ymax>424</ymax>
		</bndbox>
	</object>
	<object>
		<name>Person</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>283</xmin>
			<ymin>143</ymin>
			<xmax>325</xmax>
			<ymax>295</ymax>
		</bndbox>
	</object>
	<object>
		<name>Person</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>312</xmin>
			<ymin>171</ymin>
			<xmax>372</xmax>
			<ymax>296</ymax>
		</bndbox>
	</object>
</annotation>

   在上述的xml文件中,可能我们在标定数据的过程中,换了设备,如何实现修改xml文件,假如一个一个打开修改,嗯....是个很大的工作量.

    python批量操作代码:

#coding=utf-8  
import os  
import os.path  
import xml.dom.minidom  
  
path="/home/li/HK_img/"  
files=os.listdir(path)  #得到文件夹下所有文件名称  
s=[]  
for xmlFile in files: #遍历文件夹  
    if not os.path.isdir(xmlFile): #判断是否是文件夹,不是文件夹才打开  
        print xmlFile  
    #TODO  
    #xml文件读取操作  
  
    #将获取的xml文件名送入到dom解析  
    dom=xml.dom.minidom.parse(os.path.join(path,xmlFile))  ###最核心的部分,路径拼接,输入的是具体路径  
    root=dom.documentElement  
    name=root.getElementsByTagName('path')  #在这里我们修改的是path 节点的内容

    n0=name[0]  
    print n0.firstChild.data  
  
    #p0=pose[0]  
    #print p0.firstChild.data  
      
    #修改  
    a=n0.firstChild.data[:-4]+'.jpg'
    n0.firstChild.data='/home/li/'+a 
    #p0.firstChild.data='ok'  
    #打印输出  
    print '修改后的 name'  
    print n0.firstChild.data  
  
    print '修改后的 pose'  
    #print p0.firstChild.data  
    #print '~~~~~'  


    with open(os.path.join(path,xmlFile),'w') as fh:  
    	dom.writexml(fh)  
    	print('写入name/pose OK!')     #一定要记住该部分,否则只是改了局部变量,并不会写入文件.

  博主亲测有效,由于python的字符串拼接功能简易上手,大家可以根据自己的需求,进行更改.

  PS:若代码运行失败,原因大概会有两个:

  1.没有python的xml管理包,采用pip install 功能进行安装

  2.python与C++完全不同,需要考虑代码的缩进,一定要注意代码的缩进.

猜你喜欢

转载自blog.csdn.net/weixin_41399111/article/details/83306520