eval_utils.py
12.3 KB
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
from __future__ import division, print_function
import tensorflow as tf
import numpy as np
import cv2
from collections import Counter
from data_utils import parse_record
from nms_utils import cpu_nms, gpu_nms
from tfrecord_utils import TFRecordIterator
def calc_iou(pred_boxes, true_boxes):
pred_boxes = np.expand_dims(pred_boxes, -2)
true_boxes = np.expand_dims(true_boxes, 0)
intersect_mins = np.maximum(pred_boxes[..., :2], true_boxes[..., :2])
intersect_maxs = np.minimum(pred_boxes[..., 2:], true_boxes[..., 2:])
intersect_wh = np.maximum(intersect_maxs - intersect_mins, 0.)
intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]
pred_box_wh = pred_boxes[..., 2:] - pred_boxes[..., :2]
pred_box_area = pred_box_wh[..., 0] * pred_box_wh[..., 1]
true_boxes_wh = true_boxes[..., 2:] - true_boxes[..., :2]
true_boxes_area = true_boxes_wh[..., 0] * true_boxes_wh[..., 1]
iou = intersect_area / (pred_box_area + true_boxes_area - intersect_area + 1e-10)
return iou
def evaluate_on_cpu(y_pred, y_true, num_classes, calc_now=True, max_boxes=50, score_thresh=0.5, iou_thresh=0.5):
num_images = y_true[0].shape[0]
true_labels_dict = {i: 0 for i in range(num_classes)}
pred_labels_dict = {i: 0 for i in range(num_classes)}
true_positive_dict = {i: 0 for i in range(num_classes)}
for i in range(num_images):
true_labels_list, true_boxes_list = [], []
for j in range(3):
true_probs_temp = y_true[j][i][..., 5:-1]
true_boxes_temp = y_true[j][i][..., 0:4]
object_mask = true_probs_temp.sum(axis=-1) > 0
true_probs_temp = true_probs_temp[object_mask]
true_boxes_temp = true_boxes_temp[object_mask]
true_labels_list += np.argmax(true_probs_temp, axis=-1).tolist()
true_boxes_list += true_boxes_temp.tolist()
if len(true_labels_list) != 0:
for cls, count in Counter(true_labels_list).items():
true_labels_dict[cls] += count
true_boxes = np.array(true_boxes_list)
box_centers, box_sizes = true_boxes[:, 0:2], true_boxes[:, 2:4]
true_boxes[:, 0:2] = box_centers - box_sizes / 2.
true_boxes[:, 2:4] = true_boxes[:, 0:2] + box_sizes
pred_boxes = y_pred[0][i:i + 1]
pred_confs = y_pred[1][i:i + 1]
pred_probs = y_pred[2][i:i + 1]
pred_boxes, pred_confs, pred_labels = cpu_nms(pred_boxes, pred_confs * pred_probs, num_classes, max_boxes=max_boxes, score_thresh=score_thresh, iou_thresh=iou_thresh)
pred_labels_list = [] if pred_labels is None else pred_labels.tolist()
if pred_labels_list == []:
continue
# calc iou
iou_matrix = calc_iou(pred_boxes, true_boxes)
max_iou_idx = np.argmax(iou_matrix, axis=-1)
correct_idx = []
correct_conf = []
for k in range(max_iou_idx.shape[0]):
pred_labels_dict[pred_labels_list[k]] += 1
match_idx = max_iou_idx[k] # V level
if iou_matrix[k, match_idx] > iou_thresh and true_labels_list[match_idx] == pred_labels_list[k]:
if match_idx not in correct_idx:
correct_idx.append(match_idx)
correct_conf.append(pred_confs[k])
else:
same_idx = correct_idx.index(match_idx)
if pred_confs[k] > correct_conf[same_idx]:
correct_idx.pop(same_idx)
correct_conf.pop(same_idx)
correct_idx.append(match_idx)
correct_conf.append(pred_confs[k])
for t in correct_idx:
true_positive_dict[true_labels_list[t]] += 1
if calc_now:
# avoid divided by 0
recall = sum(true_positive_dict.values()) / (sum(true_labels_dict.values()) + 1e-6)
precision = sum(true_positive_dict.values()) / (sum(pred_labels_dict.values()) + 1e-6)
return recall, precision
else:
return true_positive_dict, true_labels_dict, pred_labels_dict
def evaluate_on_gpu(sess, gpu_nms_op, pred_boxes_flag, pred_scores_flag, y_pred, y_true, num_classes, iou_thresh=0.5, calc_now=True):
num_images = y_true[0].shape[0]
true_labels_dict = {i: 0 for i in range(num_classes)}
pred_labels_dict = {i: 0 for i in range(num_classes)}
true_positive_dict = {i: 0 for i in range(num_classes)}
for i in range(num_images):
true_labels_list, true_boxes_list = [], []
for j in range(3):
true_probs_temp = y_true[j][i][..., 5:-1]
true_boxes_temp = y_true[j][i][..., 0:4]
object_mask = true_probs_temp.sum(axis=-1) > 0
true_probs_temp = true_probs_temp[object_mask]
true_boxes_temp = true_boxes_temp[object_mask]
true_labels_list += np.argmax(true_probs_temp, axis=-1).tolist()
true_boxes_list += true_boxes_temp.tolist()
if len(true_labels_list) != 0:
for cls, count in Counter(true_labels_list).items():
true_labels_dict[cls] += count
true_boxes = np.array(true_boxes_list)
box_centers, box_sizes = true_boxes[:, 0:2], true_boxes[:, 2:4]
true_boxes[:, 0:2] = box_centers - box_sizes / 2.
true_boxes[:, 2:4] = true_boxes[:, 0:2] + box_sizes
pred_boxes = y_pred[0][i:i + 1]
pred_confs = y_pred[1][i:i + 1]
pred_probs = y_pred[2][i:i + 1]
pred_boxes, pred_confs, pred_labels = sess.run(gpu_nms_op, feed_dict={pred_boxes_flag: pred_boxes, pred_scores_flag: pred_confs * pred_probs})
pred_labels_list = [] if pred_labels is None else pred_labels.tolist()
if pred_labels_list == []:
continue
# calc iou
iou_matrix = calc_iou(pred_boxes, true_boxes)
max_iou_idx = np.argmax(iou_matrix, axis=-1)
correct_idx = []
correct_conf = []
for k in range(max_iou_idx.shape[0]):
pred_labels_dict[pred_labels_list[k]] += 1
match_idx = max_iou_idx[k] # V level
if iou_matrix[k, match_idx] > iou_thresh and true_labels_list[match_idx] == pred_labels_list[k]:
if match_idx not in correct_idx:
correct_idx.append(match_idx)
correct_conf.append(pred_confs[k])
else:
same_idx = correct_idx.index(match_idx)
if pred_confs[k] > correct_conf[same_idx]:
correct_idx.pop(same_idx)
correct_conf.pop(same_idx)
correct_idx.append(match_idx)
correct_conf.append(pred_confs[k])
for t in correct_idx:
true_positive_dict[true_labels_list[t]] += 1
if calc_now:
# avoid divided by 0
recall = sum(true_positive_dict.values()) / (sum(true_labels_dict.values()) + 1e-6)
precision = sum(true_positive_dict.values()) / (sum(pred_labels_dict.values()) + 1e-6)
return recall, precision
else:
return true_positive_dict, true_labels_dict, pred_labels_dict
def get_preds_gpu(sess, gpu_nms_op, pred_boxes_flag, pred_scores_flag, image_ids, y_pred):
image_id = image_ids[0]
pred_boxes = y_pred[0][0:1]
pred_confs = y_pred[1][0:1]
pred_probs = y_pred[2][0:1]
boxes, scores, labels = sess.run(gpu_nms_op, feed_dict={pred_boxes_flag: pred_boxes, pred_scores_flag: pred_confs * pred_probs})
pred_content = []
for i in range(len(labels)):
x_min, y_min, x_max, y_max = boxes[i]
score = scores[i]
label = labels[i]
pred_content.append([image_id, x_min, y_min, x_max, y_max, score, label])
return pred_content
gt_dict = {} # key: img_id, value: gt object list
def parse_gt_rec(gt_filename, compression_type, target_img_size, letterbox_resize=True):
global gt_dict
if not gt_dict:
new_width, new_height = target_img_size
with TFRecordIterator(gt_filename, compression_type) as reader:
for data in reader:
img_id, image, boxes, labels, ori_width, ori_height = parse_record(data)
objects = []
for i in range(len(labels)):
x_min, y_min, x_max, y_max = boxes[i]
label = labels[i]
if letterbox_resize:
resize_ratio = min(new_width / ori_width, new_height / ori_height)
resize_w = int(resize_ratio * ori_width)
resize_h = int(resize_ratio * ori_height)
dw = int((new_width - resize_w) / 2)
dh = int((new_height - resize_h) / 2)
objects.append([x_min * resize_ratio + dw,
y_min * resize_ratio + dh,
x_max * resize_ratio + dw,
y_max * resize_ratio + dh,
label])
else:
objects.append([x_min * new_width / ori_width,
y_min * new_height / ori_height,
x_max * new_width / ori_width,
y_max * new_height / ori_height,
label])
gt_dict[img_id] = objects
return gt_dict
# The following two functions are modified from FAIR's Detectron repo to calculate mAP:
# https://github.com/facebookresearch/Detectron/blob/master/detectron/datasets/voc_eval.py
def voc_ap(rec, prec, use_07_metric=False):
if use_07_metric:
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap = ap + p / 11.
else:
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
i = np.where(mrec[1:] != mrec[:-1])[0]
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def voc_eval(gt_dict, val_preds, classidx, iou_thres=0.5, use_07_metric=False):
# 1.obtain gt: extract all gt objects for this class
class_recs = {}
npos = 0
for img_id in gt_dict:
R = [obj for obj in gt_dict[img_id] if obj[-1] == classidx]
bbox = np.array([x[:4] for x in R])
det = [False] * len(R)
npos += len(R)
class_recs[img_id] = {'bbox': bbox, 'det': det}
# 2. obtain pred results
pred = [x for x in val_preds if x[-1] == classidx]
img_ids = [x[0] for x in pred]
confidence = np.array([x[-2] for x in pred])
BB = np.array([[x[1], x[2], x[3], x[4]] for x in pred])
# 3. sort by confidence
sorted_ind = np.argsort(-confidence)
try:
BB = BB[sorted_ind, :]
except:
print('no box, ignore')
return 1e-6, 1e-6, 0, 0, 0
img_ids = [img_ids[x] for x in sorted_ind]
# 4. mark TPs and FPs
nd = len(img_ids)
tp = np.zeros(nd)
fp = np.zeros(nd)
for d in range(nd):
R = class_recs[img_ids[d]]
bb = BB[d, :]
ovmax = -np.Inf
BBGT = R['bbox']
if BBGT.size > 0:
ixmin = np.maximum(BBGT[:, 0], bb[0])
iymin = np.maximum(BBGT[:, 1], bb[1])
ixmax = np.minimum(BBGT[:, 2], bb[2])
iymax = np.minimum(BBGT[:, 3], bb[3])
iw = np.maximum(ixmax - ixmin + 1., 0.)
ih = np.maximum(iymax - iymin + 1., 0.)
inters = iw * ih
uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + (BBGT[:, 2] - BBGT[:, 0] + 1.) * (
BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)
overlaps = inters / uni
ovmax = np.max(overlaps)
jmax = np.argmax(overlaps)
if ovmax > iou_thres:
# gt not matched yet
if not R['det'][jmax]:
tp[d] = 1.
R['det'][jmax] = 1
else:
fp[d] = 1.
else:
fp[d] = 1.
fp = np.cumsum(fp)
tp = np.cumsum(tp)
rec = tp / float(npos)
# avoid divide by zero in case the first detection matches a difficult
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
ap = voc_ap(rec, prec, use_07_metric)
# return rec, prec, ap
return npos, nd, tp[-1] / float(npos), tp[-1] / float(nd), ap