python 实现对应图片名合并二个的xml文件
例如:A.xml
<annotation>
<folder>JPEGImages</folder>
<filename>dog.jpg</filename>
<path>/home/ycc/darknet-master/data/JPEGImages/dog.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>768</width>
<height>576</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>dog</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>125</xmin>
<ymin>215</ymin>
<xmax>308</xmax>
<ymax>545</ymax>
</bndbox>
</object>
</annotation>
B.xml
<annotation>
<folder>JPEGImages</folder>
<filename>dog.jpg</filename>
<path>/home/ycc/darknet-master/data/JPEGImages/dog.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>768</width>
<height>576</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>bicycle</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>115</xmin>
<ymin>135</ymin>
<xmax>568</xmax>
<ymax>427</ymax>
</bndbox>
</object>
<object>
<name>car</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>466</xmin>
<ymin>70</ymin>
<xmax>688</xmax>
<ymax>177</ymax>
</bndbox>
</object>
</annotation>
批量图片合并:将想要合并的xml分别置于Annotations和Annotations,out用于保存合并的xml。
from xml.etree.ElementTree import ElementTree, Element, parse
import xml.etree.ElementTree as ET
import os
import shutil
hole_path = './Annotations'
arm_path = './Annotations1'
out_path = './out'
# 格式化
def __indent(elem, level=0):
i = "\n" + level*"\t"
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + "\t"
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
__indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
for hole_xml in os.listdir(hole_path):
# 将同名xml合并
if os.path.exists(os.path.join(arm_path,hole_xml)):
print('fusing',hole_xml)
tree_hole = parse(os.path.join(hole_path,hole_xml))
root_hole = tree_hole.getroot() # annotation
new_hole = tree_hole
tree_arm = parse(os.path.join(arm_path,hole_xml))
root_arm = tree_arm.getroot() # annotation
object = (tree_arm.findall('object'))
for i in range(len(object)):
root_hole.append(object[i])
__indent(root_hole)
new_hole.write(os.path.join(out_path,hole_xml))
# 不同名xml复制
else:
print('copying',hole_xml)
shutil.copy(os.path.join(hole_path,hole_xml), out_path)
# 将不同名xml复制
for arm_xml in os.listdir(arm_path):
if not os.path.exists(os.path.join(out_path,arm_xml)):
print('copying')
shutil.copy(os.path.join(arm_path, arm_xml), out_path)
?
|