Python读取XML部分信息,并写入文件,代码如下
import xml.etree.ElementTree as ET
import os
from os import listdir
from os.path import join
classes = ["face"]
def convert_annotation(image_id):
in_file = open('E:/fddb/Annotations/%s.xml'%image_id)
out_file = open('C:/Users/1/Desktop/fddb_ground_truth/%s.txt'%image_id, 'w')
tree=ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
out_file.write(" ".join([str(a) for a in b]) + '\n')
image_ids = open('E:/fddb/ImageSets/Main/test.txt').read().strip().split()
for image_id in image_ids:
convert_annotation(image_id)
XML文件示例:
fddb
2002_07_19_big_img_18.jpg
yanyu
yanyu
348
450
3
0