import os
import sys
import xml.etree.ElementTree as ET
import glob
def xml_to_txt(indir,outdir):
os.chdir(indir)
annotations = os.listdir('.')
annotations = glob.glob(str(annotations)+'*.xml')
for i, file in enumerate(annotations):
file_save = file.split('.')[0]+'.txt'
print(file_save)
file_txt = outdir + '/' + file_save
#file_txt=os.path.join(outdir,file_save)
print('**************************')
print(file_txt)
#f_w = open(file_txt,'w')
f_w = open(file_txt,'w',encoding='utf-8')
print('**********************************')
# actual parsing
in_file = open(file)
tree=ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
current = list()
name = obj.find('name').text
xmlbox = obj.find('bndbox')
xn = xmlbox.find('xmin').text
xx = xmlbox.find('xmax').text
yn = xmlbox.find('ymin').text
yx = xmlbox.find('ymax').text
#print xn
width = int(xx)-int(xn)
print(width)
height = int(yx)-int(yn)
print(height)
f_w.write('1:'+' ')
f_w.write(xn+' '+yn+' '+str(width)+' '+str(height)+' ')
f_w.write('\n')
indir='C:/Users/Administrator/Desktop/temp/xml' #xml目录
outdir='C:/Users/Administrator/Desktop/temp/txt' #txt目录
xml_to_txt(indir,outdir)