转自:https://blog.csdn.net/pwtd_huran/article/details/80724730
#coding=utf-8
import xml.dom.minidom
import xml.etree.cElementTree as ET
from lxml import etree, objectify
import cv2
import os
def trasnform(old_path,new_path,image_path):
#image_path_list = os.listdir(image_path)
dom = xml.dom.minidom.parse(old_path)
#得到文档元素对象
root = dom.documentElement
itemlist = root.getElementsByTagName('image')
for item in itemlist[:]:
name=item.getAttribute("file")
print(image_path+'/'+name[:-4]+'.jpg')
image = cv2.imread(image_path+'/'+name[:-4]+'.jpg')
if image is None:
continue
gao,kuan,shendu = image.shape
#print un
ii = item.getElementsByTagName('box')
top1 =[]
left1 =[]
width1 = []
height1 =[]
for i in ii:
top=i.getAttribute("top")
top1.append(top)
left=i.getAttribute("left")
left1.append(left)
width=i.getAttribute("width")
width1.append(width)
height=i.getAttribute("height")
height1.append(height)
print top,left,width,height
E = objectify.ElementMaker(annotate=False)
anno_tree = E.annotation(
E.filename(name),
E.size(
E.height(gao),
E.width(kuan),
E.depth(shendu)))
for i in range(len(top1)):
print(left1[i])
print(width1[i])
#print(left1[i]+width1[i])
anno_tree2 =E.object(
E.name('car'),
E.label('1'),
E.ignore('0'),
E.bndbox(
E.xmin(left1[i]),
E.ymin(top1[i]),
E.xmax(str(int(left1[i])+int(width1[i]))),
E.ymax(str(int(top1[i])+int(height1[i])))))
anno_tree.append(anno_tree2)
file_name = new_path+ '/' + name[0 : -4] + ".xml"
print(file_name)
etree.ElementTree(anno_tree).write(file_name, pretty_print=True)
old_path = r"/home/huran/workspace/shell/dlib_front_and_rear_vehicles_v1/training.xml"
new_path = r"/home/huran/workspace/shell/dlib_front_and_rear_vehicles_v1"
image_path = r"/home/huran/workspace/shell/dlib_front_and_rear_vehicles_v1"
trasnform(old_path,new_path,image_path)