python解析xml文件,以目标检测的bbox为例,提取物体框的label, xmin, ymin (box的左上点); xmax, ymax (box的右上点), 并将其转化为 class center_x center_y box_width box_height
关键:
- xml.etree.ElementTree as ET
- tree.getroot()
- root.find()
- root.find().text
- root.iter()
import os
from glob import glob
import xml.etree.ElementTree as ET
classes = ['crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale', 'scratches']
def xyxytoxywh(x_min, y_min, x_max, y_max, img_w, img_h):
cx = (x_max + x_min) / 2.
cy = (y_max + y_min) / 2.
w = (x_max - x_min)
h = (y_max - y_min)
return str(cx / img_w), str(cy / img_h), str(w / img_w), str(h / img_h)
def decode_xml(xml_file, save_dir):
txt_file = os.path.join(save_dir, os.path.basename(xml_file)[:-3]+"txt")
with open(txt_file, 'w', encoding='utf-8') as f:
tree = ET.parse(xml_file)
root = tree.getroot()
size = root.find('size')
img_w = int(size.find('width').text)
img_h = int(size.find('height').text)
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
print(cls)
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
x_min = (float(xmlbox.find('xmin').text))
y_min = (float(xmlbox.find('ymin').text))
x_max = (float(xmlbox.find('xmax').text))
y_max = (float(xmlbox.find('ymax').text))
txt = str(cls_id) + ' ' + ' '.join(xyxytoxywh(x_min, y_min, x_max, y_max, img_w, img_h))+'\n'
f.write(txt)
if __name__ == "__main__":
dir = "./ANNOTATIONS" # path to load .xml file
save_dir = "./labels" # path to save .txt file
os.makedirs(save_dir, exist_ok=True)
xml_file_list = glob(dir+"/*.xml")
for xml_file in xml_file_list:
decode_xml(xml_file, save_dir)
一个xml的内容示例
<annotation>
<folder>cr</folder>
<filename>crazing_2.jpg</filename>
<source>
<database>NEU-DET</database>
</source>
<size>
<width>200</width>
<height>200</height>
<depth>1</depth>
</size>
<segmented>0</segmented>
<object>
<name>crazing</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>99</xmin>
<ymin>120</ymin>
<xmax>200</xmax>
<ymax>174</ymax>
</bndbox>
</object>
<object>
<name>crazing</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>8</xmin>
<ymin>16</ymin>
<xmax>200</xmax>
<ymax>111</ymax>
</bndbox>
</object>
</annotation>