-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convert_ICDAR2015_to_VOC_2.py
187 lines (161 loc) · 7.65 KB
/
Convert_ICDAR2015_to_VOC_2.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#coding=utf-8
from xml.dom.minidom import Document
import cv2
import os
import glob
import shutil
import numpy as np
import sys
def view_bar(image, num, total):
rate = num / total
rate_num = int(rate * 40)
rate_nums = math.ceil(rate * 100)
r = '\r%s:[%s%s]%d%%\t%d/%d' % (image, ">" * rate_num, " " * (40 - rate_num), rate_nums, num, total,)
sys.stdout.write(r)
sys.stdout.flush()
def generate_xml(name, lines, img_size, class_sets, doncateothers=True):
doc = Document()
def append_xml_node_attr(child, parent=None, text=None):
ele = doc.createElement(child)
if not text is None:
text_node = doc.createTextNode(text)
ele.appendChild(text_node)
parent = doc if parent is None else parent
parent.appendChild(ele)
return ele
img_name = name + '.jpg'
# create header
annotation = append_xml_node_attr('annotation')
append_xml_node_attr('folder', parent=annotation, text='text')
append_xml_node_attr('filename', parent=annotation, text=img_name)
source = append_xml_node_attr('source', parent=annotation)
append_xml_node_attr('database', parent=source, text='icdar2015')
append_xml_node_attr('annotation', parent=source, text='text')
append_xml_node_attr('image', parent=source, text='text')
append_xml_node_attr('flickrid', parent=source, text='000000')
owner = append_xml_node_attr('owner', parent=annotation)
append_xml_node_attr('name', parent=owner, text='sws')
size = append_xml_node_attr('size', annotation)
append_xml_node_attr('width', size, str(img_size[1]))
append_xml_node_attr('height', size, str(img_size[0]))
append_xml_node_attr('depth', size, str(img_size[2]))
append_xml_node_attr('segmented', parent=annotation, text='0')
# create objects
objs = []
for line in lines:
splitted_line = line.strip().lower().split()
cls = splitted_line[0].lower()
if not doncateothers and cls not in class_sets:
continue
cls = 'dontcare' if cls not in class_sets else cls
if cls == 'dontcare':
continue
obj = append_xml_node_attr('object', parent=annotation)
occlusion = int(0)
x1, y1, x2, y2 = int(float(splitted_line[1]) + 1), int(float(splitted_line[2]) + 1), \
int(float(splitted_line[3]) + 1), int(float(splitted_line[4]) + 1)
x0,y0,x1,y1,x2,y2,x3,y3 = int(float(splitted_line[1])+1),int(float(splitted_line[2])+1),\
int(float(splitted_line[3])+1),int(float(splitted_line[4])+1),int(float(splitted_line[5])+1),\
int(float(splitted_line[6])+1),int(float(splitted_line[7])+1),int(float(splitted_line[8])+1)
truncation = float(0)
difficult = 1 if _is_hard(cls, truncation, occlusion, x1, y1, x2, y2) else 0
truncted = 0 if truncation < 0.5 else 1
append_xml_node_attr('name', parent=obj, text=cls)
append_xml_node_attr('pose', parent=obj, text='none')
append_xml_node_attr('truncated', parent=obj, text=str(truncted))
append_xml_node_attr('difficult', parent=obj, text=str(int(difficult)))
bb = append_xml_node_attr('bndbox', parent=obj)
append_xml_node_attr('x0', parent=bb, text=str(int(x0)))
append_xml_node_attr('y0', parent=bb, text=str(y0))
append_xml_node_attr('x1', parent=bb, text=str(x1))
append_xml_node_attr('y1', parent=bb, text=str(y1))
append_xml_node_attr('x2', parent=bb, text=str(x2))
append_xml_node_attr('y2', parent=bb, text=str(y2))
append_xml_node_attr('x3', parent=bb, text=str(x3))
append_xml_node_attr('y3', parent=bb, text=str(y3))
o = {'class': cls, 'box': np.asarray([x0, y0,x1,y1, x2, y2,x3,y3], dtype=float), \
'truncation': truncation, 'difficult': difficult, 'occlusion': occlusion}
objs.append(o)
return doc, objs
def _is_hard(cls, truncation, occlusion, x1, y1, x2, y2):
hard = False
if y2 - y1 < 25 and occlusion >= 2:
hard = True
return hard
if occlusion >= 3:
hard = True
return hard
if truncation > 0.8:
hard = True
return hard
return hard
def build_voc_dirs(outdir):
mkdir = lambda dir: os.makedirs(dir) if not os.path.exists(dir) else None
mkdir(outdir)
mkdir(os.path.join(outdir, 'Annotations'))
mkdir(os.path.join(outdir, 'ImageSets'))
mkdir(os.path.join(outdir, 'ImageSets', 'Layout'))
mkdir(os.path.join(outdir, 'ImageSets', 'Main'))
mkdir(os.path.join(outdir, 'ImageSets', 'Segmentation'))
mkdir(os.path.join(outdir, 'JPEGImages'))
mkdir(os.path.join(outdir, 'SegmentationClass'))
mkdir(os.path.join(outdir, 'SegmentationObject'))
return os.path.join(outdir, 'Annotations'), os.path.join(outdir, 'JPEGImages'), os.path.join(outdir, 'ImageSets',
'Main')
if __name__ == '__main__':
_outdir = '/home/xxx/VOC_train'
_draw = bool(0)
_dest_label_dir, _dest_img_dir, _dest_set_dir = build_voc_dirs(_outdir)
_doncateothers = bool(1)
for dset in ['train']:
_labeldir = '/home/xxx/label_tmp'
_imagedir = '/home/xxx/img_result'
class_sets = ('text', 'dontcare')
class_sets_dict = dict((k, i) for i, k in enumerate(class_sets))
allclasses = {}
fs = [open(os.path.join(_dest_set_dir, cls + '_' + dset + '.txt'), 'w') for cls in class_sets]
ftrain = open(os.path.join(_dest_set_dir, dset + '.txt'), 'w')
files = glob.glob(os.path.join(_labeldir, '*.txt'))
files.sort()
num = 0
total = len(files)
for file in files:
path, basename = os.path.split(file)
stem, ext = os.path.splitext(basename)
with open(file, 'r') as f:
lines = f.readlines()
img_file = os.path.join(_imagedir, stem + '.jpg')
print(img_file)
img = cv2.imread(img_file)
img_size = img.shape
doc, objs = generate_xml(stem, lines, img_size, class_sets=class_sets, doncateothers=_doncateothers)
cv2.imwrite(os.path.join(_dest_img_dir, stem + '.jpg'), img)
xmlfile = os.path.join(_dest_label_dir, stem + '.xml')
with open(xmlfile, 'w') as f:
f.write(doc.toprettyxml(indent=' '))
ftrain.writelines(stem + '\n')
cls_in_image = set([o['class'] for o in objs])
for obj in objs:
cls = obj['class']
allclasses[cls] = 0 \
if not cls in list(allclasses.keys()) else allclasses[cls] + 1
for cls in cls_in_image:
if cls in class_sets:
fs[class_sets_dict[cls]].writelines(stem + ' 1\n')
for cls in class_sets:
if cls not in cls_in_image:
fs[class_sets_dict[cls]].writelines(stem + ' -1\n')
view_bar(stem+'.jpg', num, total)
num += 1
(f.close() for f in fs)
ftrain.close()
print('~~~~~~~~~~~~~~~~~~~')
print(allclasses)
print('~~~~~~~~~~~~~~~~~~~')
shutil.copyfile(os.path.join(_dest_set_dir, 'train.txt'), os.path.join(_dest_set_dir, 'val.txt'))
shutil.copyfile(os.path.join(_dest_set_dir, 'train.txt'), os.path.join(_dest_set_dir, 'trainval.txt'))
for cls in class_sets:
shutil.copyfile(os.path.join(_dest_set_dir, cls + '_train.txt'),
os.path.join(_dest_set_dir, cls + '_trainval.txt'))
shutil.copyfile(os.path.join(_dest_set_dir, cls + '_train.txt'),
os.path.join(_dest_set_dir, cls + '_val.txt'))