-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
339 lines (274 loc) · 12.2 KB
/
test.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
from utils.compute_overlap import compute_overlap
from utils.visualization import draw_detections, draw_annotations
import numpy as np
import cv2
import progressbar
import time
assert (callable(progressbar.progressbar)), "Using wrong progressbar module, install 'progressbar2' instead."
def _compute_ap(recall, precision):
"""
Compute the average precision, given the recall and precision curves.
Code originally from https://github.com/rbgirshick/py-faster-rcnn.
Args:
recall: The recall curve (list).
precision: The precision curve (list).
Returns:
The average precision as computed in py-faster-rcnn.
"""
# correct AP calculation
# first append sentinel values at the end
mrec = np.concatenate(([0.], recall, [1.]))
mpre = np.concatenate(([0.], precision, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes value
i = np.where(mrec[1:] != mrec[:-1])[0]
# and sum (delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def _get_detections(generator, model, score_threshold=0.05, max_detections=1, visualize=False):
"""
Get the detections from the model using the generator.
The result is a list of lists such that the size is:
all_detections[num_images][num_classes] = detections[num_class_detections, 5]
Args:
generator: The generator used to run images through the model.
model: The model to run on the images.
score_threshold: The score confidence threshold to use.
max_detections: The maximum number of detections to use per image.
save_path: The path to save the images with visualized detections to.
Returns:
A list of lists containing the detections for each image in the generator.
"""
all_detections = [[None for i in range(generator.num_classes()) if generator.has_label(i)] for j in
range(generator.size())]
for i in progressbar.progressbar(range(generator.size()), prefix='Running network: '):
image = generator.load_image(i)
src_image = image.copy()
h, w = image.shape[:2]
anchors = generator.anchors
image, scale = generator.preprocess_image(image)
# run network
boxes, scores, *_, labels = model.predict_on_batch([np.expand_dims(image, axis=0)])
boxes /= scale
boxes[:, :, 0] = np.clip(boxes[:, :, 0], 0, w - 1)
boxes[:, :, 1] = np.clip(boxes[:, :, 1], 0, h - 1)
boxes[:, :, 2] = np.clip(boxes[:, :, 2], 0, w - 1)
boxes[:, :, 3] = np.clip(boxes[:, :, 3], 0, h - 1)
# select indices which have a score above the threshold
indices = np.where(scores[0, :] > score_threshold)[0]
# select those scores
scores = scores[0][indices]
# find the order with which to sort the scores
scores_sort = np.argsort(-scores)[:max_detections]
# select detections
# (n, 4)
image_boxes = boxes[0, indices[scores_sort], :]
# (n, )
image_scores = scores[scores_sort]
# (n, )
image_labels = labels[0, indices[scores_sort]]
# (n, 6)
detections = np.concatenate(
[image_boxes, np.expand_dims(image_scores, axis=1), np.expand_dims(image_labels, axis=1)], axis=1)
# print(detections)
# draw_annotations(src_image, generator.load_annotations(i), label_to_name=generator.label_to_name)
# draw_detections(src_image, detections[:5, :4], detections[:5, 4], detections[:5, 5].astype(np.int32),
# label_to_name=generator.label_to_name,
# score_threshold=score_threshold)
# # cv2.imwrite(os.path.join(save_path, '{}.png'.format(i)), raw_image)
# cv2.namedWindow('{}'.format(i), cv2.WINDOW_NORMAL)
# cv2.imshow('{}'.format(i), src_image)
# cv2.waitKey(0)
# copy detections to all_detections
for class_id in range(generator.num_classes()):
all_detections[i][class_id] = detections[detections[:, -1] == class_id, :-1]
# print(all_detections)
f=open("/ssd3/u1/NBI_NET/EfficientDet-master/bbox.txt",'a+')
# print("image_boxes= ",image_boxes)
count=0
bbox_temp=[]
temp_single_position=0
# print("max_detections= ",max_detections)
for i in range(4):
# if count<2:
# if image_boxes[0][count]>=image_boxes[1][count]:
# bbox_temp.append(image_boxes[1][count])
# else:
# bbox_temp.append(image_boxes[0][count])
# else:
# if image_boxes[0][count]<=image_boxes[1][count]:
# bbox_temp.append(image_boxes[1][count])
# else:
# bbox_temp.append(image_boxes[0][count])
# print("max_detections",max_detections)
for j in range(max_detections):
temp_single_position=temp_single_position+image_boxes[j][count]
temp_single_position=temp_single_position/(max_detections)
if temp_single_position>480:
temp_single_position=480
bbox_temp.append(temp_single_position)
count+=1
bbox_temp=np.array(bbox_temp)
# print(bbox_temp.shape)
# print("image_boxes_append",bbox_temp)
count=0
for i in range(4):
if count!=3:
f.write(str(bbox_temp[count])+',')
else:
f.write(str(bbox_temp[count]))
count+=1
f.write('\n')
f.close()
return all_detections
def _get_annotations(generator):
"""
Get the ground truth annotations from the generator.
The result is a list of lists such that the size is:
all_annotations[num_images][num_classes] = annotations[num_class_annotations, 5]
Args:
generator: The generator used to retrieve ground truth annotations.
Returns:
A list of lists containing the annotations for each image in the generator.
"""
all_annotations = [[None for i in range(generator.num_classes())] for j in range(generator.size())]
for i in progressbar.progressbar(range(generator.size()), prefix='Parsing annotations: '):
# load the annotations
annotations = generator.load_annotations(i)
# copy detections to all_annotations
for label in range(generator.num_classes()):
if not generator.has_label(label):
continue
all_annotations[i][label] = annotations['bboxes'][annotations['labels'] == label, :].copy()
return all_annotations
def evaluate(
generator,
model,
iou_threshold=0.5,
score_threshold=0.01,
max_detections=5,
visualize=True,
epoch=0
):
"""
Evaluate a given dataset using a given model.
Args:
generator: The generator that represents the dataset to evaluate.
model: The model to evaluate.
iou_threshold: The threshold used to consider when a detection is positive or negative.
score_threshold: The score confidence threshold to use for detections.
max_detections: The maximum number of detections to use per image.
visualize: Show the visualized detections or not.
Returns:
A dict mapping class names to mAP scores.
"""
# gather all detections and annotations
all_detections= _get_detections(generator, model, score_threshold=score_threshold, max_detections=max_detections,
visualize=visualize)
all_annotations = _get_annotations(generator)
average_precisions = {}
num_tp = 0
num_fp = 0
# process detections and annotations
for label in range(generator.num_classes()):
if not generator.has_label(label):
continue
false_positives = np.zeros((0,))
true_positives = np.zeros((0,))
scores = np.zeros((0,))
num_annotations = 0.0
for i in range(generator.size()):
detections = all_detections[i][label]
annotations = all_annotations[i][label]
num_annotations += annotations.shape[0]
detected_annotations = []
for d in detections:
scores = np.append(scores, d[4])
if annotations.shape[0] == 0:
false_positives = np.append(false_positives, 1)
true_positives = np.append(true_positives, 0)
continue
overlaps = compute_overlap(np.expand_dims(d, axis=0), annotations)
assigned_annotation = np.argmax(overlaps, axis=1)
max_overlap = overlaps[0, assigned_annotation]
if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations:
false_positives = np.append(false_positives, 0)
true_positives = np.append(true_positives, 1)
detected_annotations.append(assigned_annotation)
else:
false_positives = np.append(false_positives, 1)
true_positives = np.append(true_positives, 0)
# no annotations -> AP for this class is 0 (is this correct?)
if num_annotations == 0:
average_precisions[label] = 0, 0
continue
# sort by score
indices = np.argsort(-scores)
false_positives = false_positives[indices]
true_positives = true_positives[indices]
# compute false positives and true positives
false_positives = np.cumsum(false_positives)
true_positives = np.cumsum(true_positives)
if false_positives.shape[0] == 0:
num_fp += 0
else:
num_fp += false_positives[-1]
if true_positives.shape[0] == 0:
num_tp += 0
else:
num_tp += true_positives[-1]
# compute recall and precision
recall = true_positives / num_annotations
precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps)
# compute average precision
average_precision = _compute_ap(recall, precision)
average_precisions[label] = average_precision, num_annotations
print('num_fp={}, num_tp={}'.format(num_fp, num_tp))
return average_precisions,recall,precision,iou_threshold
if __name__ == '__main__':
from generators.pascal import PascalVocGenerator
from model import efficientdet
import os
f=open("/ssd3/u1/NBI_NET/EfficientDet-master/bbox.txt","w")
f.close()
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
phi = 1
weighted_bifpn = False
common_args = {
'batch_size': 1,
'phi': phi,
}
test_generator = PascalVocGenerator(
'datasets/VOCdevkit/VOC2007',
'test',
shuffle_groups=False,
skip_truncated=False,
skip_difficult=True,
**common_args
)
model_path = 'checkpoint/fpi3-test01_RW_ann2/pascal_15_0.0452_1.3134.h5'
input_shape = (test_generator.image_size, test_generator.image_size)
anchors = test_generator.anchors
num_classes = test_generator.num_classes()
model, prediction_model = efficientdet(phi=phi, num_classes=num_classes, weighted_bifpn=weighted_bifpn)
prediction_model.load_weights(model_path, by_name=True)
tStart = time.time()
average_precisions,recall,precison,iou_threshold= evaluate(test_generator, prediction_model, visualize=False)
tEnd = time.time()
print("It cost %f sec" % (tEnd - tStart))
# compute per class average precision
total_instances = []
precisions = []
for label, (average_precision, num_annotations) in average_precisions.items():
print('{:.0f} instances of class'.format(num_annotations), test_generator.label_to_name(label),
'with average precision: {:.4f}'.format(average_precision))
total_instances.append(num_annotations)
precisions.append(average_precision)
mean_ap = sum(precisions) / sum(x > 0 for x in total_instances)
print("IOU Threshold",iou_threshold)
print('mAP: {:.4f}'.format(mean_ap))
print('recall: ',np.mean(recall))
print('precison: ',np.mean(precison))