-
Notifications
You must be signed in to change notification settings - Fork 197
/
boxesCvtPascaltoDlib.py
executable file
·81 lines (67 loc) · 2.28 KB
/
boxesCvtPascaltoDlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python
import xml.etree.ElementTree as et
import os
import argparse
def initRootOut():
rootOut = et.Element('dataset')
sub = et.SubElement(rootOut, 'name')
sub.text = 'imglab dataset'
sub = et.SubElement(rootOut, 'comment')
sub.text = 'From Pascal VOC dataset'
et.SubElement(rootOut, 'images')
return rootOut
def addImg(imgs, xmlIn, imgPath):
ele = xmlIn.find('filename')
if ele is None:
return False
fileName = os.path.join(imgPath, ele.text)
img = et.SubElement(imgs, 'image', attrib={'file': fileName})
# add bounding boxes
for obj in xmlIn.findall('object'):
ele = obj.find('name')
if ele is None:
continue
label = ele.text
ele = obj.find('bndbox')
if ele is None:
continue
pts = {}
if ele.find('xmin') is None:
continue
left = float(ele.find('xmin').text)
if ele.find('ymin') is None:
continue
top = float(ele.find('ymin').text)
if ele.find('xmax') is None:
continue
right = float(ele.find('xmax').text)
if ele.find('ymax') is None:
continue
down = float(ele.find('ymax').text)
pts['left'] = str(int(round(left)))
pts['top'] = str(int(round(top)))
pts['width'] = str(int(round(right - left + 1)))
pts['height'] = str(int(round(down - top + 1)))
ele = et.SubElement(img, 'box', pts)
ele = et.SubElement(ele, 'label')
ele.text = label
if __name__ == '__main__':
p = argparse.ArgumentParser(description='Convert Pascal format to Dlib format')
p.add_argument('bboxes', help='Folder of bounding boxes files')
p.add_argument('imgPath', help='Path of images')
p.add_argument('--out', help='Output file', default='out.xml')
args = p.parse_args()
imgExt = '.jpg'
rootOut = initRootOut()
imgs = rootOut.find('images')
for f in os.listdir(args.bboxes):
if not f.endswith('.xml'):
continue
try:
rootIn = et.parse(os.path.join(args.bboxes, f)).getroot()
except:
print('Fail to open ' + f + '!')
continue
addImg(imgs, rootIn, args.imgPath)
tree = et.ElementTree(rootOut)
tree.write(args.out)