import json
import os
from xml.dom.minidom import parse
import xml.dom.minidom
path = '/home/zqf/bridge/VOC2007/Annotations'
def convert(size, box):
dw = 1. /float(size[0])
dh = 1. /float(size[1])
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
original_name = os.listdir(path)
print(original_name)
for i in original_name:
filename=os.path.join(path,i)
bret = filename.endswith(".xml")
if bret:
savename = os.path.splitext(filename)[0]
print(savename)
savename=savename+".txt"
print(filename)
print(savename)
savename=os.path.join(path,savename)
DOMTree = xml.dom.minidom.parse(filename)
collection = DOMTree.documentElement
size = collection.getElementsByTagName("size")
xwidth = size[0].getElementsByTagName('width')[0]
width=xwidth.childNodes[0].data
print(width)
xheight = size[0].getElementsByTagName('height')[0]
height=xheight.childNodes[0].data
print(height)
objects = collection.getElementsByTagName("object")
for object in objects:
bndbox = object.getElementsByTagName('bndbox')[0]
xmin = bndbox.getElementsByTagName('xmin')[0]
x1=xmin.childNodes[0].data
ymin = bndbox.getElementsByTagName('ymin')[0]
y1=ymin.childNodes[0].data
xmax = bndbox.getElementsByTagName('xmax')[0]
x2=xmax.childNodes[0].data
ymax = bndbox.getElementsByTagName('ymax')[0]
y2=ymax.childNodes[0].data
b = (float(x1), float(x2), float(y1),float(y2))
bb = convert((width, height), b)
#retstr='0 '+'%.6f'%a1+' '+'%.6f'%b1+' '+'%.6f'%a2+' '+'%.6f'%b2+'\n'
#print(retstr)
with open(savename, 'a') as f:
f.write("0 " + " ".join([str(a) for a in bb]) + '\n')
标签:xml,box,savename,getElementsByTagName,print,coco,path,size From: https://www.cnblogs.com/kn-zheng/p/17044498.html