-
Notifications
You must be signed in to change notification settings - Fork 3
/
AICity.py
558 lines (489 loc) · 23.1 KB
/
AICity.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# --------------------------------------------------------
# Deformable Convolutional Networks
# Copyright (c) 2017 Microsoft
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Modified by Shuo Wang
# --------------------------------------------------------
"""
Pascal VOC database
This class loads ground truth notations from standard Pascal VOC XML data formats
and transform them into IMDB format. Selective search is used for proposals, see roidb
function. Results are written as the Pascal VOC format. Evaluation is based on mAP
criterion.
"""
import cPickle
import cv2
import os
import numpy as np
import PIL
from imdb import IMDB
from pascal_voc_eval import voc_eval, voc_eval_sds
from ds_utils import unique_boxes, filter_small_boxes
class AICity(IMDB):
def __init__(self, image_set, root_path, devkit_path, result_path=None, mask_size=-1, binary_thresh=None):
"""
fill basic information to initialize imdb
:param image_set: 2007_trainval, 2007_test, etc
:param root_path: 'selective_search_data' and 'cache'
:param devkit_path: data and results
:return: imdb object
"""
year = image_set.split('_')[0]
image_set = image_set[len(year) + 1 : len(image_set)]
super(AICity, self).__init__('voc_' + year, image_set, root_path, devkit_path, result_path) # set self.name
self.year = year
self.root_path = root_path
self.devkit_path = devkit_path
self.data_path = os.path.join(devkit_path, 'VOC' + year)
self.classes = ['__DontCare__', # always index 0
'car', 'suv', 'smalltruck', 'mediumtruck',
'largetruck','pedestrian', 'bus', 'van', 'groupofpeople',
'bicycle', 'motorcycle', 'trafficsignal-green', 'trafficsignal-yellow',
'trafficsignal-red']
self.num_classes = len(self.classes)
self.image_set_index = self.load_image_set_index()
self.num_images = len(self.image_set_index)
print 'num_images', self.num_images
self.mask_size = mask_size
self.binary_thresh = binary_thresh
self.config = {'comp_id': 'comp4',
'use_diff': False,
'min_size': 2}
def load_image_set_index(self):
"""
find out which indexes correspond to given image set (train or val)
:return:
"""
image_set_index_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')
assert os.path.exists(image_set_index_file), 'Path does not exist: {}'.format(image_set_index_file)
with open(image_set_index_file) as f:
image_set_index = [x.strip() for x in f.readlines()]
return image_set_index
def image_path_from_index(self, index):
"""
given image index, find out full path
:param index: index of a specific image
:return: full path of this image
"""
image_file = os.path.join(self.data_path, 'JPEGImages', index + '.jpeg')
assert os.path.exists(image_file), 'Path does not exist: {}'.format(image_file)
return image_file
def segmentation_path_from_index(self, index):
"""
given image index, find out the full path of segmentation class
:param index: index of a specific image
:return: full path of segmentation class
"""
seg_class_file = os.path.join(self.data_path, 'SegmentationClass', index + '.png')
assert os.path.exists(seg_class_file), 'Path does not exist: {}'.format(seg_class_file)
return seg_class_file
def gt_roidb(self):
"""
return ground truth image regions database
:return: imdb[image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
"""
cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{} gt roidb loaded from {}'.format(self.name, cache_file)
return roidb
gt_roidb = [self.load_pascal_annotation(index) for index in self.image_set_index]
with open(cache_file, 'wb') as fid:
cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL)
print 'wrote gt roidb to {}'.format(cache_file)
return gt_roidb
def gt_roidb_Shuo(self):
"""
return ground truth image regions database
:return: imdb[image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{} gt roidb loaded from {}'.format(self.name, cache_file)
return roidb
"""
gt_roidb = [self.load_pascal_annotation_Shuo(index) for index in self.image_set_index]
"""
with open(cache_file, 'wb') as fid:
cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL)
print 'wrote gt roidb to {}'.format(cache_file)
"""
return gt_roidb
def gt_segdb(self):
"""
return ground truth image regions database
:return: imdb[image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
"""
cache_file = os.path.join(self.cache_path, self.name + '_gt_segdb.pkl')
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
segdb = cPickle.load(fid)
print '{} gt segdb loaded from {}'.format(self.name, cache_file)
return segdb
gt_segdb = [self.load_pascal_segmentation_annotation(index) for index in self.image_set_index]
with open(cache_file, 'wb') as fid:
cPickle.dump(gt_segdb, fid, cPickle.HIGHEST_PROTOCOL)
print 'wrote gt segdb to {}'.format(cache_file)
return gt_segdb
def load_pascal_annotation(self, index):
"""
for a given index, load image and bounding boxes info from XML file
:param index: index of a specific image
:return: record['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
"""
import xml.etree.ElementTree as ET
roi_rec = dict()
roi_rec['image'] = self.image_path_from_index(index)
filename = os.path.join(self.data_path, 'Annotations', index + '.txt')
tree = ET.parse(filename)
size = tree.find('size')
roi_rec['height'] = float(size.find('height').text)
roi_rec['width'] = float(size.find('width').text)
#im_size = cv2.imread(roi_rec['image'], cv2.IMREAD_COLOR|cv2.IMREAD_IGNORE_ORIENTATION).shape
#assert im_size[0] == roi_rec['height'] and im_size[1] == roi_rec['width']
objs = tree.findall('object')
notinterested_classes = []
#'pedestrian','groupofpeople','bicycle', 'motorcycle','trafficsignal-green', 'trafficsignal-yellow', 'trafficsignal-red'
cared_objs = [obj for obj in objs if not obj.find('name').text.lower().strip() in notinterested_classes]
objs = cared_objs
#if not self.config['use_diff']:
# non_diff_objs = [obj for obj in objs if int(obj.find('difficult').text) == 0]
# objs = non_diff_objs
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)
class_to_index = dict(zip(self.classes, range(self.num_classes)))
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
if not obj.find('name').text.lower().strip() in notinterested_classes:
bbox = obj.find('bndbox')
# Make pixel indexes 0-based
x1 = float(bbox.find('xmin').text) - 1
y1 = float(bbox.find('ymin').text) - 1
x2 = float(bbox.find('xmax').text) - 1
y2 = float(bbox.find('ymax').text) - 1
cls = class_to_index[obj.find('name').text.lower().strip()]
#print cls, obj.find('name').text.lower().strip()
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
roi_rec.update({'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'max_classes': overlaps.argmax(axis=1),
'max_overlaps': overlaps.max(axis=1),
'flipped': False})
#print roi_rec
return roi_rec
def load_pascal_annotation_Shuo(self, index):
"""
for a given index, load image and bounding boxes info from XML file
:param index: index of a specific image
:return: record['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
"""
import xml.etree.ElementTree as ET
roi_rec = dict()
roi_rec['image'] = self.image_path_from_index(index)
#filename = os.path.join(self.data_path, 'Annotations', index + '.txt')
#tree = ET.parse(filename)
#size = tree.find('size')
#roi_rec['height'] = float(size.find('height').text)
#roi_rec['width'] = float(size.find('width').text)
im_size = cv2.imread(roi_rec['image'], cv2.IMREAD_COLOR|cv2.IMREAD_IGNORE_ORIENTATION).shape
roi_rec['height'] = float(im_size[0])
roi_rec['width'] = float(im_size[1])
#assert im_size[0] == roi_rec['height'] and im_size[1] == roi_rec['width']
"""
objs = tree.findall('object')
notinterested_classes = ['pedestrian','groupofpeople','bicycle', 'motorcycle','trafficsignal-green', 'trafficsignal-yellow', 'trafficsignal-red']
cared_objs = [obj for obj in objs if not obj.find('name').text.lower().strip() in notinterested_classes]
objs = cared_objs
#if not self.config['use_diff']:
# non_diff_objs = [obj for obj in objs if int(obj.find('difficult').text) == 0]
# objs = non_diff_objs
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)
class_to_index = dict(zip(self.classes, range(self.num_classes)))
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
if not obj.find('name').text.lower().strip() in notinterested_classes:
bbox = obj.find('bndbox')
# Make pixel indexes 0-based
x1 = float(bbox.find('xmin').text) - 1
y1 = float(bbox.find('ymin').text) - 1
x2 = float(bbox.find('xmax').text) - 1
y2 = float(bbox.find('ymax').text) - 1
cls = class_to_index[obj.find('name').text.lower().strip()]
#print cls, obj.find('name').text.lower().strip()
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
roi_rec.update({'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'max_classes': overlaps.argmax(axis=1),
'max_overlaps': overlaps.max(axis=1),
'flipped': False})
"""
overlaps = np.ones((1, self.num_classes), dtype=np.float32)
roi_rec.update({'boxes': np.zeros((1, 4), dtype=np.uint16),
'gt_classes': np.ones((1), dtype=np.int32),
'gt_overlaps': overlaps,
'max_classes': overlaps.argmax(axis=1),
'max_overlaps': overlaps.max(axis=1),
'flipped': False})
#print roi_rec
return roi_rec
def load_selective_search_roidb(self, gt_roidb):
"""
turn selective search proposals into selective search roidb
:param gt_roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
:return: roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
"""
import scipy.io
matfile = os.path.join(self.root_path, 'selective_search_data', self.name + '.mat')
assert os.path.exists(matfile), 'selective search data does not exist: {}'.format(matfile)
raw_data = scipy.io.loadmat(matfile)['boxes'].ravel() # original was dict ['images', 'boxes']
box_list = []
for i in range(raw_data.shape[0]):
boxes = raw_data[i][:, (1, 0, 3, 2)] - 1 # pascal voc dataset starts from 1.
keep = unique_boxes(boxes)
boxes = boxes[keep, :]
keep = filter_small_boxes(boxes, self.config['min_size'])
boxes = boxes[keep, :]
box_list.append(boxes)
return self.create_roidb_from_box_list(box_list, gt_roidb)
def selective_search_roidb(self, gt_roidb, append_gt=False):
"""
get selective search roidb and ground truth roidb
:param gt_roidb: ground truth roidb
:param append_gt: append ground truth
:return: roidb of selective search
"""
cache_file = os.path.join(self.cache_path, self.name + '_ss_roidb.pkl')
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
print '{} ss roidb loaded from {}'.format(self.name, cache_file)
return roidb
if append_gt:
print 'appending ground truth annotations'
ss_roidb = self.load_selective_search_roidb(gt_roidb)
roidb = IMDB.merge_roidbs(gt_roidb, ss_roidb)
else:
roidb = self.load_selective_search_roidb(gt_roidb)
with open(cache_file, 'wb') as fid:
cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL)
print 'wrote ss roidb to {}'.format(cache_file)
return roidb
def load_pascal_segmentation_annotation(self, index):
"""
for a given index, load image and bounding boxes info from XML file
:param index: index of a specific image
:return: record['seg_cls_path', 'flipped']
"""
import xml.etree.ElementTree as ET
seg_rec = dict()
seg_rec['image'] = self.image_path_from_index(index)
size = cv2.imread(seg_rec['image']).shape
seg_rec['height'] = size[0]
seg_rec['width'] = size[1]
seg_rec['seg_cls_path'] = self.segmentation_path_from_index(index)
seg_rec['flipped'] = False
return seg_rec
def evaluate_detections(self, detections):
"""
top level evaluations
:param detections: result matrix, [bbox, confidence]
:return: None
"""
# make all these folders for results
result_dir = os.path.join(self.result_path, 'results')
if not os.path.exists(result_dir):
os.mkdir(result_dir)
year_folder = os.path.join(self.result_path, 'results', 'VOC' + self.year)
if not os.path.exists(year_folder):
os.mkdir(year_folder)
res_file_folder = os.path.join(self.result_path, 'results', 'VOC' + self.year, 'Main')
if not os.path.exists(res_file_folder):
os.mkdir(res_file_folder)
self.write_pascal_results(detections)
info = self.do_python_eval()
return info
def evaluate_segmentations(self, pred_segmentations=None):
"""
top level evaluations
:param pred_segmentations: the pred segmentation result
:return: the evaluation results
"""
# make all these folders for results
if not (pred_segmentations is None):
self.write_pascal_segmentation_result(pred_segmentations)
info = self._py_evaluate_segmentation()
return info
def write_pascal_segmentation_result(self, pred_segmentations):
"""
Write pred segmentation to res_file_folder
:param pred_segmentations: the pred segmentation results
:param res_file_folder: the saving folder
:return: [None]
"""
result_dir = os.path.join(self.result_path, 'results')
if not os.path.exists(result_dir):
os.mkdir(result_dir)
year_folder = os.path.join(self.result_path, 'results', 'VOC' + self.year)
if not os.path.exists(year_folder):
os.mkdir(year_folder)
res_file_folder = os.path.join(self.result_path, 'results', 'VOC' + self.year, 'Segmentation')
if not os.path.exists(res_file_folder):
os.mkdir(res_file_folder)
result_dir = os.path.join(self.result_path, 'results', 'VOC' + self.year, 'Segmentation')
if not os.path.exists(result_dir):
os.mkdir(result_dir)
pallete = self.get_pallete(256)
for i, index in enumerate(self.image_set_index):
segmentation_result = np.uint8(np.squeeze(np.copy(pred_segmentations[i])))
segmentation_result = PIL.Image.fromarray(segmentation_result)
segmentation_result.putpalette(pallete)
segmentation_result.save(os.path.join(result_dir, '%s.png'%(index)))
def get_pallete(self, num_cls):
"""
this function is to get the colormap for visualizing the segmentation mask
:param num_cls: the number of visulized class
:return: the pallete
"""
n = num_cls
pallete = [0]*(n*3)
for j in xrange(0,n):
lab = j
pallete[j*3+0] = 0
pallete[j*3+1] = 0
pallete[j*3+2] = 0
i = 0
while (lab > 0):
pallete[j*3+0] |= (((lab >> 0) & 1) << (7-i))
pallete[j*3+1] |= (((lab >> 1) & 1) << (7-i))
pallete[j*3+2] |= (((lab >> 2) & 1) << (7-i))
i = i + 1
lab >>= 3
return pallete
def get_confusion_matrix(self, gt_label, pred_label, class_num):
"""
Calcute the confusion matrix by given label and pred
:param gt_label: the ground truth label
:param pred_label: the pred label
:param class_num: the nunber of class
:return: the confusion matrix
"""
index = (gt_label * class_num + pred_label).astype('int32')
label_count = np.bincount(index)
confusion_matrix = np.zeros((class_num, class_num))
for i_label in range(class_num):
for i_pred_label in range(class_num):
cur_index = i_label * class_num + i_pred_label
if cur_index < len(label_count):
confusion_matrix[i_label, i_pred_label] = label_count[cur_index]
return confusion_matrix
def _py_evaluate_segmentation(self):
"""
This function is a wrapper to calculte the metrics for given pred_segmentation results
:param pred_segmentations: the pred segmentation result
:return: the evaluation metrics
"""
confusion_matrix = np.zeros((self.num_classes,self.num_classes))
result_dir = os.path.join(self.result_path, 'results', 'VOC' + self.year, 'Segmentation')
for i, index in enumerate(self.image_set_index):
seg_gt_info = self.load_pascal_segmentation_annotation(index)
seg_gt_path = seg_gt_info['seg_cls_path']
seg_gt = np.array(PIL.Image.open(seg_gt_path)).astype('float32')
seg_pred_path = os.path.join(result_dir, '%s.png'%(index))
seg_pred = np.array(PIL.Image.open(seg_pred_path)).astype('float32')
seg_gt = cv2.resize(seg_gt, (seg_pred.shape[1], seg_pred.shape[0]), interpolation=cv2.INTER_NEAREST)
ignore_index = seg_gt != 255
seg_gt = seg_gt[ignore_index]
seg_pred = seg_pred[ignore_index]
confusion_matrix += self.get_confusion_matrix(seg_gt, seg_pred, self.num_classes)
pos = confusion_matrix.sum(1)
res = confusion_matrix.sum(0)
tp = np.diag(confusion_matrix)
IU_array = (tp / np.maximum(1.0, pos + res - tp))
mean_IU = IU_array.mean()
return {'meanIU':mean_IU, 'IU_array':IU_array}
def get_result_file_template(self):
"""
this is a template
VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt
:return: a string template
"""
res_file_folder = os.path.join(self.result_path, 'results', 'VOC' + self.year, 'Main')
comp_id = self.config['comp_id']
filename = comp_id + '_det_' + self.image_set + '_{:s}.txt'
path = os.path.join(res_file_folder, filename)
return path
def write_pascal_results(self, all_boxes):
"""
write results files in pascal devkit path
:param all_boxes: boxes to be processed [bbox, confidence]
:return: None
"""
for cls_ind, cls in enumerate(self.classes):
if cls == '__background__':
continue
print 'Writing {} VOC results file'.format(cls)
filename = self.get_result_file_template().format(cls)
with open(filename, 'wt') as f:
for im_ind, index in enumerate(self.image_set_index):
dets = all_boxes[cls_ind][im_ind]
if len(dets) == 0:
continue
# the VOCdevkit expects 1-based indices
for k in range(dets.shape[0]):
f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.
format(index, dets[k, -1],
dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1))
def do_python_eval(self):
"""
python evaluation wrapper
:return: info_str
"""
info_str = ''
annopath = os.path.join(self.data_path, 'Annotations', '{0!s}.txt')
imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')
annocache = os.path.join(self.cache_path, self.name + '_annotations.pkl')
aps = []
# The PASCAL VOC metric changed in 2010
# use_07_metric = True if self.year == 'SDS' or int(self.year) < 2010 else False
use_07_metric = True if int(self.year) == 2007 else False
print 'VOC07 metric? ' + ('Y' if use_07_metric else 'No')
info_str += 'VOC07 metric? ' + ('Y' if use_07_metric else 'No')
info_str += '\n'
for cls_ind, cls in enumerate(self.classes):
if cls == '__background__':
continue
filename = self.get_result_file_template().format(cls)
rec, prec, ap = voc_eval(filename, annopath, imageset_file, cls, annocache,
ovthresh=0.5, use_07_metric=use_07_metric)
aps += [ap]
print('AP for {} = {:.4f}'.format(cls, ap))
info_str += 'AP for {} = {:.4f}\n'.format(cls, ap)
print('Mean [email protected] = {:.4f}'.format(np.mean(aps)))
info_str += 'Mean [email protected] = {:.4f}\n\n'.format(np.mean(aps))
# @0.7
aps = []
for cls_ind, cls in enumerate(self.classes):
if cls == '__background__':
continue
filename = self.get_result_file_template().format(cls)
rec, prec, ap = voc_eval(filename, annopath, imageset_file, cls, annocache,
ovthresh=0.7, use_07_metric=use_07_metric)
aps += [ap]
print('AP for {} = {:.4f}'.format(cls, ap))
info_str += 'AP for {} = {:.4f}\n'.format(cls, ap)
print('Mean [email protected] = {:.4f}'.format(np.mean(aps)))
info_str += 'Mean [email protected] = {:.4f}'.format(np.mean(aps))
return info_str