-
Notifications
You must be signed in to change notification settings - Fork 222
/
eval.py
1490 lines (1255 loc) · 58.6 KB
/
eval.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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Calculate mAP for YOLO model on some annotation dataset
"""
import os, argparse, time
import numpy as np
import operator
from operator import mul
from functools import reduce
from PIL import Image
from collections import OrderedDict
import matplotlib.pyplot as plt
from tqdm import tqdm
from tensorflow.keras.models import load_model
import tensorflow.keras.backend as K
import tensorflow as tf
import MNN
import onnxruntime
from yolo5.postprocess_np import yolo5_postprocess_np
from yolo3.postprocess_np import yolo3_postprocess_np
from yolo2.postprocess_np import yolo2_postprocess_np
from common.data_utils import preprocess_image
from common.utils import get_dataset, get_classes, get_anchors, get_colors, draw_boxes, optimize_tf_gpu, get_custom_objects
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
optimize_tf_gpu(tf, K)
def annotation_parse(annotation_lines, class_names):
'''
parse annotation lines to get image dict and ground truth class dict
image dict would be like:
annotation_records = {
'/path/to/000001.jpg': {'100,120,200,235':'dog', '85,63,156,128':'car', ...},
...
}
ground truth class dict would be like:
classes_records = {
'car': [
['000001.jpg','100,120,200,235'],
['000002.jpg','85,63,156,128'],
...
],
...
}
'''
annotation_records = OrderedDict()
classes_records = OrderedDict({class_name: [] for class_name in class_names})
for line in annotation_lines:
box_records = {}
image_name = line.split(' ')[0]
boxes = line.split(' ')[1:]
for box in boxes:
#strip box coordinate and class
class_name = class_names[int(box.split(',')[-1])]
coordinate = ','.join(box.split(',')[:-1])
box_records[coordinate] = class_name
#append or add ground truth class item
record = [os.path.basename(image_name), coordinate]
if class_name in classes_records:
classes_records[class_name].append(record)
else:
classes_records[class_name] = list([record])
annotation_records[image_name] = box_records
return annotation_records, classes_records
def transform_gt_record(gt_records, class_names):
'''
Transform the Ground Truth records of a image to prediction format, in
order to show & compare in result pic.
Ground Truth records is a dict with format:
{'100,120,200,235':'dog', '85,63,156,128':'car', ...}
Prediction format:
(boxes, classes, scores)
'''
if gt_records is None or len(gt_records) == 0:
return [], [], []
gt_boxes = []
gt_classes = []
gt_scores = []
for (coordinate, class_name) in gt_records.items():
gt_box = [int(x) for x in coordinate.split(',')]
gt_class = class_names.index(class_name)
gt_boxes.append(gt_box)
gt_classes.append(gt_class)
gt_scores.append(1.0)
return np.array(gt_boxes), np.array(gt_classes), np.array(gt_scores)
def yolo_predict_tflite(interpreter, image, anchors, num_classes, conf_threshold, elim_grid_sense, v5_decode):
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# check the type of the input tensor
#if input_details[0]['dtype'] == np.float32:
#floating_model = True
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
model_input_shape = (height, width)
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
interpreter.set_tensor(input_details[0]['index'], image_data)
interpreter.invoke()
prediction = []
for output_detail in output_details:
output_data = interpreter.get_tensor(output_detail['index'])
prediction.append(output_data)
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_mnn(interpreter, session, image, anchors, num_classes, conf_threshold, elim_grid_sense, v5_decode):
# assume only 1 input tensor for image
input_tensor = interpreter.getSessionInput(session)
# get & resize input shape
input_shape = list(input_tensor.getShape())
if input_shape[0] == 0:
input_shape[0] = 1
interpreter.resizeTensor(input_tensor, tuple(input_shape))
interpreter.resizeSession(session)
# check if input layout is NHWC or NCHW
if input_shape[1] == 3:
#print("NCHW input layout")
batch, channel, height, width = input_shape #NCHW
elif input_shape[-1] == 3:
#print("NHWC input layout")
batch, height, width, channel = input_shape #NHWC
else:
# should be MNN.Tensor_DimensionType_Caffe_C4, unsupported now
raise ValueError('unsupported input tensor dimension type')
model_input_shape = (height, width)
# prepare input image
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
# create a temp tensor to copy data
# use TF NHWC layout to align with image data array
# TODO: currently MNN python binding have mem leak when creating MNN.Tensor
# from numpy array, only from tuple is good. So we convert input image to tuple
tmp_input_shape = (batch, height, width, channel)
input_elementsize = reduce(mul, tmp_input_shape)
tmp_input = MNN.Tensor(tmp_input_shape, input_tensor.getDataType(),\
tuple(image_data.reshape(input_elementsize, -1)), MNN.Tensor_DimensionType_Tensorflow)
input_tensor.copyFrom(tmp_input)
interpreter.runSession(session)
def get_tensor_list(output_tensors):
# transform the output tensor dict to ordered tensor list, for further postprocess
#
# output tensor list should be like (for YOLOv3):
# [
# (name, tensor) for (13, 13, 3, num_classes+5),
# (name, tensor) for (26, 26, 3, num_classes+5),
# (name, tensor) for (52, 52, 3, num_classes+5)
# ]
output_list = []
for (output_tensor_name, output_tensor) in output_tensors.items():
tensor_shape = output_tensor.getShape()
dim_type = output_tensor.getDimensionType()
tensor_height, tensor_width = tensor_shape[2:4] if dim_type == MNN.Tensor_DimensionType_Caffe else tensor_shape[1:3]
if len(anchors) == 6:
# Tiny YOLOv3
if tensor_height == height//32:
output_list.insert(0, (output_tensor_name, output_tensor))
elif tensor_height == height//16:
output_list.insert(1, (output_tensor_name, output_tensor))
else:
raise ValueError('invalid tensor shape')
elif len(anchors) == 9:
# YOLOv3
if tensor_height == height//32:
output_list.insert(0, (output_tensor_name, output_tensor))
elif tensor_height == height//16:
output_list.insert(1, (output_tensor_name, output_tensor))
elif tensor_height == height//8:
output_list.insert(2, (output_tensor_name, output_tensor))
else:
raise ValueError('invalid tensor shape')
elif len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(output_tensors) == 1, 'YOLOv2 model should have only 1 output tensor.'
output_list.insert(0, (output_tensor_name, output_tensor))
else:
raise ValueError('invalid anchor number')
return output_list
output_tensors = interpreter.getSessionOutputAll(session)
output_tensor_list = get_tensor_list(output_tensors)
prediction = []
for (output_tensor_name, output_tensor) in output_tensor_list:
output_shape = output_tensor.getShape()
output_elementsize = reduce(mul, output_shape)
# check output channel to confirm if output layout
# is NHWC or NCHW
if len(anchors) == 5:
out_channel = (num_classes + 5) * 5
else:
out_channel = (num_classes + 5) * (len(anchors)//3)
#if output_shape[1] == out_channel:
#print("NCHW output layout")
#elif output_shape[-1] == out_channel:
#print("NHWC output layout")
#else:
#raise ValueError('invalid output layout or shape')
assert output_tensor.getDataType() == MNN.Halide_Type_Float
# copy output tensor to host, for further postprocess
tmp_output = MNN.Tensor(output_shape, output_tensor.getDataType(),\
#np.zeros(output_shape, dtype=float), output_tensor.getDimensionType())
tuple(np.zeros(output_shape, dtype=float).reshape(output_elementsize, -1)), output_tensor.getDimensionType())
output_tensor.copyToHostTensor(tmp_output)
#tmp_output.printTensorData()
output_data = np.array(tmp_output.getData(), dtype=float).reshape(output_shape)
# our postprocess code based on TF NHWC layout, so if the output format
# doesn't match, we need to transpose
if output_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe and output_shape[1] == out_channel: # double check if it's NCHW format
output_data = output_data.transpose((0,2,3,1))
elif output_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe_C4:
raise ValueError('unsupported output tensor dimension type')
prediction.append(output_data)
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_pb(model, image, anchors, num_classes, model_input_shape, conf_threshold, elim_grid_sense, v5_decode):
# NOTE: TF 1.x frozen pb graph need to specify input/output tensor name
# so we hardcode the input/output tensor names here to get them from model
if len(anchors) == 6:
output_tensor_names = ['graph/predict_conv_1/BiasAdd:0', 'graph/predict_conv_2/BiasAdd:0']
elif len(anchors) == 9:
output_tensor_names = ['graph/predict_conv_1/BiasAdd:0', 'graph/predict_conv_2/BiasAdd:0', 'graph/predict_conv_3/BiasAdd:0']
elif len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
output_tensor_names = ['graph/predict_conv/BiasAdd:0']
else:
raise ValueError('invalid anchor number')
# assume only 1 input tensor for image
input_tensor_name = 'graph/image_input:0'
# get input/output tensors
image_input = model.get_tensor_by_name(input_tensor_name)
output_tensors = [model.get_tensor_by_name(output_tensor_name) for output_tensor_name in output_tensor_names]
batch, height, width, channel = image_input.shape
model_input_shape = (int(height), int(width))
# prepare input image
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
with tf.Session(graph=model) as sess:
prediction = sess.run(output_tensors, feed_dict={
image_input: image_data
})
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_onnx(model, image, anchors, num_classes, conf_threshold, elim_grid_sense, v5_decode):
input_tensors = []
for i, input_tensor in enumerate(model.get_inputs()):
input_tensors.append(input_tensor)
# assume only 1 input tensor for image
assert len(input_tensors) == 1, 'invalid input tensor number.'
# check if input layout is NHWC or NCHW
if input_tensors[0].shape[1] == 3:
batch, channel, height, width = input_tensors[0].shape #NCHW
else:
batch, height, width, channel = input_tensors[0].shape #NHWC
model_input_shape = (height, width)
output_tensors = []
for i, output_tensor in enumerate(model.get_outputs()):
output_tensors.append(output_tensor)
# check output channel to confirm if output layout
# is NHWC or NCHW
if len(anchors) == 5:
out_channel = (num_classes + 5) * 5
else:
out_channel = (num_classes + 5) * (len(anchors)//3)
if output_tensors[0].shape[1] == out_channel:
#print("NCHW output layout")
pass
elif output_tensors[0].shape[-1] == out_channel:
#print("NHWC output layout")
pass
else:
raise ValueError('invalid output layout or shape')
# prepare input image
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
if input_tensors[0].shape[1] == 3:
# transpose image for NCHW layout
image_data = image_data.transpose((0,3,1,2))
feed = {input_tensors[0].name: image_data}
prediction = model.run(None, feed)
if output_tensors[0].shape[1] == out_channel:
# transpose prediction array for NCHW layout
prediction = [p.transpose((0,2,3,1)) for p in prediction]
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_keras(model, image, anchors, num_classes, model_input_shape, conf_threshold, elim_grid_sense, v5_decode):
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
prediction = model.predict([image_data])
if type(prediction) is not list:
prediction = [prediction]
if len(anchors) == 5:
# YOLOv2 use 5 anchors
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def get_prediction_class_records(model, model_format, annotation_records, anchors, class_names, model_input_shape, conf_threshold, elim_grid_sense, v5_decode, save_result):
'''
Do the predict with YOLO model on annotation images to get predict class dict
predict class dict would contain image_name, coordinary and score, and
sorted by score:
pred_classes_records = {
'car': [
['000001.jpg','94,115,203,232',0.98],
['000002.jpg','82,64,154,128',0.93],
...
],
...
}
'''
if model_format == 'MNN':
#MNN inference engine need create session
session_config = \
{
'backend': 'CPU', #'CPU'/'OPENCL'/'OPENGL'/'VULKAN'/'METAL'/'TRT'/'CUDA'/'HIAI'
'precision': 'high', #'normal'/'low'/'high'/'lowBF'
'numThread': 2
}
session = model.createSession(session_config)
# create txt file to save prediction result, with
# save format as annotation file but adding score, like:
#
# path/to/img1.jpg 50,100,150,200,0,0.86 30,50,200,120,3,0.95
#
os.makedirs('result', exist_ok=True)
result_file = open(os.path.join('result','detection_result.txt'), 'w')
pred_classes_records = OrderedDict()
pbar = tqdm(total=len(annotation_records), desc='Eval model')
for (image_name, gt_records) in annotation_records.items():
image = Image.open(image_name)
if image.mode != 'RGB':
image = image.convert('RGB')
image_array = np.array(image, dtype='uint8')
# support of tflite model
if model_format == 'TFLITE':
pred_boxes, pred_classes, pred_scores = yolo_predict_tflite(model, image, anchors, len(class_names), conf_threshold, elim_grid_sense, v5_decode)
# support of MNN model
elif model_format == 'MNN':
pred_boxes, pred_classes, pred_scores = yolo_predict_mnn(model, session, image, anchors, len(class_names), conf_threshold, elim_grid_sense, v5_decode)
# support of TF 1.x frozen pb model
elif model_format == 'PB':
pred_boxes, pred_classes, pred_scores = yolo_predict_pb(model, image, anchors, len(class_names), model_input_shape, conf_threshold, elim_grid_sense, v5_decode)
# support of ONNX model
elif model_format == 'ONNX':
pred_boxes, pred_classes, pred_scores = yolo_predict_onnx(model, image, anchors, len(class_names), conf_threshold, elim_grid_sense, v5_decode)
# normal keras h5 model
elif model_format == 'H5':
pred_boxes, pred_classes, pred_scores = yolo_predict_keras(model, image, anchors, len(class_names), model_input_shape, conf_threshold, elim_grid_sense, v5_decode)
else:
raise ValueError('invalid model format')
#print('Found {} boxes for {}'.format(len(pred_boxes), image_name))
image.close()
pbar.update(1)
# save prediction result to txt
result_file.write(image_name)
for box, cls, score in zip(pred_boxes, pred_classes, pred_scores):
xmin, ymin, xmax, ymax = box
box_annotation = " %d,%d,%d,%d,%d,%f" % (
xmin, ymin, xmax, ymax, cls, score)
result_file.write(box_annotation)
result_file.write('\n')
result_file.flush()
if save_result:
gt_boxes, gt_classes, gt_scores = transform_gt_record(gt_records, class_names)
result_dir=os.path.join('result','detection')
os.makedirs(result_dir, exist_ok=True)
colors = get_colors(len(class_names))
image_array = draw_boxes(image_array, gt_boxes, gt_classes, gt_scores, class_names, colors=None, show_score=False)
image_array = draw_boxes(image_array, pred_boxes, pred_classes, pred_scores, class_names, colors)
image = Image.fromarray(image_array)
# here we handle the RGBA image
if(len(image.split()) == 4):
r, g, b, a = image.split()
image = Image.merge("RGB", (r, g, b))
image.save(os.path.join(result_dir, image_name.split(os.path.sep)[-1]))
# Nothing detected
if pred_boxes is None or len(pred_boxes) == 0:
continue
for box, cls, score in zip(pred_boxes, pred_classes, pred_scores):
pred_class_name = class_names[cls]
xmin, ymin, xmax, ymax = box
coordinate = "{},{},{},{}".format(xmin, ymin, xmax, ymax)
#append or add predict class item
record = [os.path.basename(image_name), coordinate, score]
if pred_class_name in pred_classes_records:
pred_classes_records[pred_class_name].append(record)
else:
pred_classes_records[pred_class_name] = list([record])
# sort pred_classes_records for each class according to score
for pred_class_list in pred_classes_records.values():
pred_class_list.sort(key=lambda ele: ele[2], reverse=True)
pbar.close()
result_file.close()
return pred_classes_records
def box_iou(pred_box, gt_box):
'''
Calculate iou for predict box and ground truth box
Param
pred_box: predict box coordinate
(xmin,ymin,xmax,ymax) format
gt_box: ground truth box coordinate
(xmin,ymin,xmax,ymax) format
Return
iou value
'''
# get intersection box
inter_box = [max(pred_box[0], gt_box[0]), max(pred_box[1], gt_box[1]), min(pred_box[2], gt_box[2]), min(pred_box[3], gt_box[3])]
inter_w = max(0.0, inter_box[2] - inter_box[0] + 1)
inter_h = max(0.0, inter_box[3] - inter_box[1] + 1)
# compute overlap (IoU) = area of intersection / area of union
pred_area = (pred_box[2] - pred_box[0] + 1) * (pred_box[3] - pred_box[1] + 1)
gt_area = (gt_box[2] - gt_box[0] + 1) * (gt_box[3] - gt_box[1] + 1)
inter_area = inter_w * inter_h
union_area = pred_area + gt_area - inter_area
return 0 if union_area == 0 else float(inter_area) / float(union_area)
def match_gt_box(pred_record, gt_records, iou_threshold=0.5):
'''
Search gt_records list and try to find a matching box for the predict box
Param
pred_record: with format ['image_file', 'xmin,ymin,xmax,ymax', score]
gt_records: record list with format
[
['image_file', 'xmin,ymin,xmax,ymax', 'usage'],
['image_file', 'xmin,ymin,xmax,ymax', 'usage'],
...
]
iou_threshold:
pred_record and gt_records should be from same annotation image file
Return
matching gt_record index. -1 when there's no matching gt
'''
max_iou = 0.0
max_index = -1
#get predict box coordinate
pred_box = [float(x) for x in pred_record[1].split(',')]
for i, gt_record in enumerate(gt_records):
#get ground truth box coordinate
gt_box = [float(x) for x in gt_record[1].split(',')]
iou = box_iou(pred_box, gt_box)
# if the ground truth has been assigned to other
# prediction, we couldn't reuse it
if iou > max_iou and gt_record[2] == 'unused' and pred_record[0] == gt_record[0]:
max_iou = iou
max_index = i
# drop the prediction if couldn't match iou threshold
if max_iou < iou_threshold:
max_index = -1
return max_index
def voc_ap(rec, prec):
"""
--- Official matlab code VOC2012---
mrec=[0 ; rec ; 1];
mpre=[0 ; prec ; 0];
for i=numel(mpre)-1:-1:1
mpre(i)=max(mpre(i),mpre(i+1));
end
i=find(mrec(2:end)~=mrec(1:end-1))+1;
ap=sum((mrec(i)-mrec(i-1)).*mpre(i));
"""
rec.insert(0, 0.0) # insert 0.0 at begining of list
rec.append(1.0) # insert 1.0 at end of list
mrec = rec[:]
prec.insert(0, 0.0) # insert 0.0 at begining of list
prec.append(0.0) # insert 0.0 at end of list
mpre = prec[:]
"""
This part makes the precision monotonically decreasing
(goes from the end to the beginning)
"""
# matlab indexes start in 1 but python in 0, so I have to do:
# range(start=(len(mpre) - 2), end=0, step=-1)
# also the python function range excludes the end, resulting in:
# range(start=(len(mpre) - 2), end=-1, step=-1)
for i in range(len(mpre) - 2, -1, -1):
mpre[i] = max(mpre[i], mpre[i + 1])
"""
This part creates a list of indexes where the recall changes
"""
# matlab: i=find(mrec(2:end)~=mrec(1:end-1))+1;
i_list = []
for i in range(1, len(mrec)):
if mrec[i] != mrec[i - 1]:
i_list.append(i) # if it was matlab would be i + 1
"""
The Average Precision (AP) is the area under the curve
(numerical integration)
"""
# matlab: ap=sum((mrec(i)-mrec(i-1)).*mpre(i));
ap = 0.0
for i in i_list:
ap += ((mrec[i] - mrec[i - 1]) * mpre[i])
return ap, mrec, mpre
'''
def voc_ap(rec, prec, use_07_metric=False):
if use_07_metric:
# 11 point 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, mrec, mpre
'''
def get_rec_prec(true_positive, false_positive, gt_records):
'''
Calculate precision/recall based on true_positive, false_positive
result.
'''
cumsum = 0
for idx, val in enumerate(false_positive):
false_positive[idx] += cumsum
cumsum += val
cumsum = 0
for idx, val in enumerate(true_positive):
true_positive[idx] += cumsum
cumsum += val
rec = true_positive[:]
for idx, val in enumerate(true_positive):
rec[idx] = (float(true_positive[idx]) / len(gt_records)) if len(gt_records) != 0 else 0
prec = true_positive[:]
for idx, val in enumerate(true_positive):
prec[idx] = float(true_positive[idx]) / (false_positive[idx] + true_positive[idx])
return rec, prec
def draw_rec_prec(rec, prec, mrec, mprec, class_name, ap):
"""
Draw plot
"""
plt.plot(rec, prec, '-o')
# add a new penultimate point to the list (mrec[-2], 0.0)
# since the last line segment (and respective area) do not affect the AP value
area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]]
area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]]
plt.fill_between(area_under_curve_x, 0, area_under_curve_y, alpha=0.2, edgecolor='r')
# set window title
fig = plt.gcf() # gcf - get current figure
if fig.canvas.manager is not None:
fig.canvas.manager.set_window_title('AP ' + class_name)
# set plot title
plt.title('class: ' + class_name + ' AP = {}%'.format(ap*100))
#plt.suptitle('This is a somewhat long figure title', fontsize=16)
# set axis titles
plt.xlabel('Recall')
plt.ylabel('Precision')
# optional - set axes
axes = plt.gca() # gca - get current axes
axes.set_xlim([0.0,1.0])
axes.set_ylim([0.0,1.05]) # .05 to give some extra space
# Alternative option -> wait for button to be pressed
#while not plt.waitforbuttonpress(): pass # wait for key display
# Alternative option -> normal display
#plt.show()
# save the plot
rec_prec_plot_path = os.path.join('result','classes')
os.makedirs(rec_prec_plot_path, exist_ok=True)
fig.savefig(os.path.join(rec_prec_plot_path, class_name + ".png"))
plt.cla() # clear axes for next plot
import bokeh
import bokeh.io as bokeh_io
import bokeh.plotting as bokeh_plotting
def generate_rec_prec_html(mrec, mprec, scores, class_name, ap):
"""
Generate dynamic P-R curve HTML page for each class
Note: for convenince, we support double click on the HTML page
with mouse to capture the rec/prec/score value on curve
"""
# bypass invalid class
if len(mrec) == 0 or len(mprec) == 0 or len(scores) == 0:
return
rec_prec_plot_path = os.path.join('result' ,'classes')
os.makedirs(rec_prec_plot_path, exist_ok=True)
bokeh_io.output_file(os.path.join(rec_prec_plot_path, class_name + '.html'), title='P-R curve for ' + class_name)
# prepare curve data
area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]]
area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]]
score_on_curve = [0.0] + scores[:-1] + [0.0] + [scores[-1]] + [1.0]
source = bokeh.models.ColumnDataSource(data={
'rec' : area_under_curve_x,
'prec' : area_under_curve_y,
'score' : score_on_curve,
})
# prepare plot figure
plt_title = 'class: ' + class_name + ' AP = {}%'.format(ap*100)
plt = bokeh_plotting.figure(plot_height=200 ,plot_width=200, tools="", toolbar_location=None,
title=plt_title, sizing_mode="scale_width")
plt.background_fill_color = "#f5f5f5"
plt.grid.grid_line_color = "white"
plt.xaxis.axis_label = 'Recall'
plt.yaxis.axis_label = 'Precision'
plt.axis.axis_line_color = None
# draw curve data
plt.line(x='rec', y='prec', line_width=2, color='#ebbd5b', source=source, legend_label='double click to copy P&R')
plt.add_tools(bokeh.models.HoverTool(
callback=bokeh.models.CustomJS(
code="""var data=cb_data.renderer.data_source.data;
var line_id=cb_data.index.line_indices[0];
var x=cb_data.geometry.x;
if(data['rec'][line_id+1]-x > x-data['rec'][line_id])
{
window.spr_text=data['score'][line_id]+'\t'+data['prec'][line_id]+'\t'+data['rec'][line_id];
}
else
{
window.spr_text=data['score'][line_id+1]+'\t'+data['prec'][line_id+1]+'\t'+data['rec'][line_id+1];
}
"""),
tooltips=[
( 'score', '@score{0.0000 a}'),
( 'Prec', '@prec'),
( 'Recall', '@rec'),
],
formatters={
'rec' : 'printf',
'prec' : 'printf',
},
mode='vline'
))
plt.js_on_event(bokeh.events.DoubleTap, bokeh.models.CustomJS(code="""navigator.clipboard.writeText(window.spr_text);"""))
bokeh_io.save(plt)
return
def adjust_axes(r, t, fig, axes):
"""
Plot - adjust axes
"""
# get text width for re-scaling
bb = t.get_window_extent(renderer=r)
text_width_inches = bb.width / fig.dpi
# get axis width in inches
current_fig_width = fig.get_figwidth()
new_fig_width = current_fig_width + text_width_inches
propotion = new_fig_width / current_fig_width
# get axis limit
x_lim = axes.get_xlim()
axes.set_xlim([x_lim[0], x_lim[1]*propotion])
def draw_plot_func(dictionary, n_classes, window_title, plot_title, x_label, output_path, to_show, plot_color, true_p_bar):
"""
Draw plot using Matplotlib
"""
# sort the dictionary by decreasing value, into a list of tuples
sorted_dic_by_value = sorted(dictionary.items(), key=operator.itemgetter(1))
# unpacking the list of tuples into two lists
sorted_keys, sorted_values = zip(*sorted_dic_by_value)
#
if true_p_bar != "":
"""
Special case to draw in (green=true predictions) & (red=false predictions)
"""
fp_sorted = []
tp_sorted = []
for key in sorted_keys:
fp_sorted.append(dictionary[key] - true_p_bar[key])
tp_sorted.append(true_p_bar[key])
plt.barh(range(n_classes), fp_sorted, align='center', color='crimson', label='False Predictions')
plt.barh(range(n_classes), tp_sorted, align='center', color='forestgreen', label='True Predictions', left=fp_sorted)
# add legend
plt.legend(loc='lower right')
"""
Write number on side of bar
"""
fig = plt.gcf() # gcf - get current figure
axes = plt.gca()
r = fig.canvas.get_renderer()
for i, val in enumerate(sorted_values):
fp_val = fp_sorted[i]
tp_val = tp_sorted[i]
fp_str_val = " " + str(fp_val)
tp_str_val = fp_str_val + " " + str(tp_val)
# trick to paint multicolor with offset:
# first paint everything and then repaint the first number
t = plt.text(val, i, tp_str_val, color='forestgreen', va='center', fontweight='bold')
plt.text(val, i, fp_str_val, color='crimson', va='center', fontweight='bold')
if i == (len(sorted_values)-1): # largest bar
adjust_axes(r, t, fig, axes)
else:
plt.barh(range(n_classes), sorted_values, color=plot_color)
"""
Write number on side of bar
"""
fig = plt.gcf() # gcf - get current figure
axes = plt.gca()
r = fig.canvas.get_renderer()
for i, val in enumerate(sorted_values):
str_val = " " + str(val) # add a space before
if val < 1.0:
str_val = " {0:.2f}".format(val)
t = plt.text(val, i, str_val, color=plot_color, va='center', fontweight='bold')
# re-set axes to show number inside the figure
if i == (len(sorted_values)-1): # largest bar
adjust_axes(r, t, fig, axes)
# set window title
if fig.canvas.manager is not None:
fig.canvas.manager.set_window_title(window_title)
# write classes in y axis
tick_font_size = 12
plt.yticks(range(n_classes), sorted_keys, fontsize=tick_font_size)
"""
Re-scale height accordingly
"""
init_height = fig.get_figheight()
# comput the matrix height in points and inches
dpi = fig.dpi
height_pt = n_classes * (tick_font_size * 1.4) # 1.4 (some spacing)
height_in = height_pt / dpi
# compute the required figure height
top_margin = 0.15 # in percentage of the figure height
bottom_margin = 0.05 # in percentage of the figure height
figure_height = height_in / (1 - top_margin - bottom_margin)
# set new height
if figure_height > init_height:
fig.set_figheight(figure_height)
# set plot title
plt.title(plot_title, fontsize=14)
# set axis titles
# plt.xlabel('classes')
plt.xlabel(x_label, fontsize='large')
# adjust size of window
fig.tight_layout()
# save the plot
fig.savefig(output_path)
# show image
if to_show:
plt.show()
# close the plot
plt.close()
def calc_AP(gt_records, pred_records, class_name, iou_threshold, show_result):
'''
Calculate AP value for one class records
Param
gt_records: ground truth records list for one class, with format:
[
['image_file', 'xmin,ymin,xmax,ymax'],
['image_file', 'xmin,ymin,xmax,ymax'],
...
]
pred_records: predict records for one class, with format (in score descending order):
[
['image_file', 'xmin,ymin,xmax,ymax', score],
['image_file', 'xmin,ymin,xmax,ymax', score],
...
]
Return
AP value for the class
'''
# append usage flag in gt_records for matching gt search
gt_records = [gt_record + ['unused'] for gt_record in gt_records]
# prepare score list for generating P-R html page
scores = [pred_record[2] for pred_record in pred_records]
# init true_positive and false_positive list
nd = len(pred_records) # number of predict data
true_positive = [0] * nd
false_positive = [0] * nd
true_positive_count = 0
# assign predictions to ground truth objects
for idx, pred_record in enumerate(pred_records):
# filter out gt record from same image
image_gt_records = [ gt_record for gt_record in gt_records if gt_record[0] == pred_record[0]]
i = match_gt_box(pred_record, image_gt_records, iou_threshold=iou_threshold)
if i != -1:
# find a valid gt obj to assign, set
# true_positive list and mark image_gt_records.
#
# trick: gt_records will also be marked
# as 'used', since image_gt_records is a
# reference list
image_gt_records[i][2] = 'used'
true_positive[idx] = 1
true_positive_count += 1
else:
false_positive[idx] = 1
# compute precision/recall
rec, prec = get_rec_prec(true_positive, false_positive, gt_records)
ap, mrec, mprec = voc_ap(rec, prec)
if show_result:
draw_rec_prec(rec, prec, mrec, mprec, class_name, ap)
generate_rec_prec_html(mrec, mprec, scores, class_name, ap)
return ap, true_positive_count
def plot_Pascal_AP_result(count_images, count_true_positives, num_classes,
gt_counter_per_class, pred_counter_per_class,
precision_dict, recall_dict, mPrec, mRec,
APs, mAP, iou_threshold):
'''
Plot the total number of occurences of each class in the ground-truth
'''
window_title = "Ground-Truth Info"
plot_title = "Ground-Truth\n" + "(" + str(count_images) + " files and " + str(num_classes) + " classes)"
x_label = "Number of objects per class"
output_path = os.path.join('result','Ground-Truth_Info.png')
draw_plot_func(gt_counter_per_class, num_classes, window_title, plot_title, x_label, output_path, to_show=False, plot_color='forestgreen', true_p_bar='')
'''
Plot the total number of occurences of each class in the "predicted" folder
'''
window_title = "Predicted Objects Info"
# Plot title
plot_title = "Predicted Objects\n" + "(" + str(count_images) + " files and "
count_non_zero_values_in_dictionary = sum(int(x) > 0 for x in list(pred_counter_per_class.values()))
plot_title += str(count_non_zero_values_in_dictionary) + " detected classes)"
# end Plot title
x_label = "Number of objects per class"
output_path = os.path.join('result','Predicted_Objects_Info.png')
draw_plot_func(pred_counter_per_class, len(pred_counter_per_class), window_title, plot_title, x_label, output_path, to_show=False, plot_color='forestgreen', true_p_bar=count_true_positives)
'''
Draw mAP plot (Show AP's of all classes in decreasing order)
'''
window_title = "mAP"
plot_title = "mAP@IoU={0}: {1:.2f}%".format(iou_threshold, mAP)
x_label = "Average Precision"
output_path = os.path.join('result','mAP.png')
draw_plot_func(APs, num_classes, window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')
'''
Draw Precision plot (Show Precision of all classes in decreasing order)
'''
window_title = "Precision"
plot_title = "mPrec@IoU={0}: {1:.2f}%".format(iou_threshold, mPrec)
x_label = "Precision rate"