-
Notifications
You must be signed in to change notification settings - Fork 28
/
map_example.py
1480 lines (1293 loc) · 57.3 KB
/
map_example.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
import io
import os
import cv2
import sys
import math
import time
import json
import glob
import base64
import shutil
import argparse
import operator
import requests
import numpy as np
from PIL import Image
import tensorflow as tf
import matplotlib as plt
from loguru import logger
from PIL import ImageDraw
from PIL import ImageFont
import xml.etree.ElementTree as ET
from works.simples.settings import PHI
from works.simples.settings import MODE
from works.simples.settings import PRUNING
from works.simples.settings import USE_GPU
from works.simples.settings import GT_PATH
from works.simples.settings import DR_PATH
from works.simples.settings import IMG_PATH
from works.simples.settings import MODEL_PATH
from works.simples.settings import MODEL_NAME
from works.simples.settings import PRUNING_MODEL_NAME
from works.simples.utils import Image_Processing
from works.simples.settings import THRESHOLD
from works.simples.settings import TEST_PATH
from works.simples.settings import LABEL_PATH
from works.simples.settings import IMAGE_WIDTH
from works.simples.settings import OUTPUT_PATH
from works.simples.settings import IMAGE_SIZES
from works.simples.settings import IMAGE_HEIGHT
from works.simples.settings import NUMBER_CLASSES_FILE
from works.simples.utils import Predict_Image
table = []
mean_time = []
for i in range(256):
if i < THRESHOLD:
table.append(0)
else:
table.append(255)
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 这两行需要手动设置
if MODE == 'EFFICIENTDET' or MODE == 'SSD' or MODE == 'YOLO_TINY' or MODE == 'YOLO':
pass
else:
raise ValueError('不是目标检测任务无法测试Map')
if USE_GPU:
gpus = tf.config.experimental.list_physical_devices(device_type="GPU")
if gpus:
logger.info("use gpu device")
logger.info(f'可用GPU数量: {len(gpus)}')
try:
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
except RuntimeError as e:
logger.error(e)
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(device=gpu, enable=True)
tf.print(gpu)
except RuntimeError as e:
logger.error(e)
else:
tf.config.experimental.list_physical_devices(device_type="CPU")
os.environ["CUDA_VISIBLE_DEVICE"] = "-1"
logger.info("not found gpu device,convert to use cpu")
else:
logger.info("use cpu device")
# 禁用gpu
tf.config.experimental.list_physical_devices(device_type="CPU")
os.environ["CUDA_VISIBLE_DEVICE"] = "-1"
class Predict_Images(Predict_Image):
def predict_image(self, image_path):
global mean_time
global right_value
global predicted_value
start_time = time.time()
recognition_rate_list = []
if MODE == 'EFFICIENTDET':
if self.app:
image = Image.fromarray(image_path)
else:
image = Image.open(image_path)
if image.mode != 'RGB':
image = image.convert('RGB')
image_shape = np.array(np.shape(image)[0:2])
crop_img = self.letterbox_image(image, [IMAGE_SIZES[PHI], IMAGE_SIZES[PHI]])
photo = np.array(crop_img, dtype=np.float32)
# 图片预处理,归一化
photo = np.reshape(self.preprocess_input(photo),
[1, IMAGE_SIZES[PHI], IMAGE_SIZES[PHI], 3])
if PRUNING:
model = self.model
input_details = model.get_input_details()
output_details = model.get_output_details()
model.set_tensor(input_details[0]['index'], photo)
model.invoke()
pred1 = model.get_tensor(output_details[0]['index'])
pred2 = model.get_tensor(output_details[1]['index'])
preds = (pred2, pred1)
else:
preds = self.model.predict(photo)
# 将预测结果进行解码
results = self.bbox_util.detection_out(preds, self.prior, confidence_threshold=self.confidence)
if len(results[0]) <= 0:
# if self.detection_results:
_, file_name = os.path.split(image_path)
file_name, _ = os.path.splitext(file_name)
with open(os.path.join(DR_PATH, file_name + '.txt'), mode='a', encoding='utf-8') as f:
f.write(f'Fail {0} {0} {0} {0} {0}\n')
return image
results = np.array(results)
# 筛选出其中得分高于confidence的框
det_label = results[0][:, 5]
det_conf = results[0][:, 4]
det_xmin, det_ymin, det_xmax, det_ymax = results[0][:, 0], results[0][:, 1], results[0][:, 2], results[0][:,
3]
top_indices = [i for i, conf in enumerate(det_conf) if conf >= self.confidence]
top_conf = det_conf[top_indices]
top_label_indices = det_label[top_indices].tolist()
top_xmin, top_ymin, top_xmax, top_ymax = np.expand_dims(det_xmin[top_indices], -1), np.expand_dims(
det_ymin[top_indices], -1), np.expand_dims(det_xmax[top_indices], -1), np.expand_dims(
det_ymax[top_indices],
-1)
# 去掉灰条
boxes = self.efficientdet_correct_boxes(top_ymin, top_xmin, top_ymax, top_xmax,
np.array([IMAGE_SIZES[PHI], IMAGE_SIZES[PHI]]),
image_shape)
font = ImageFont.truetype(font='simhei.ttf',
size=np.floor(3e-2 * np.shape(image)[1] + 0.5).astype('int32'))
thickness = (np.shape(image)[0] + np.shape(image)[1]) // IMAGE_SIZES[PHI]
for i, c in enumerate(top_label_indices):
predicted_class = self.num_classes_list[int(c)]
score = top_conf[i]
recognition_rate_list.append(score)
top, left, bottom, right = boxes[i]
top = top - 5
left = left - 5
bottom = bottom + 5
right = right + 5
top = max(0, np.floor(top + 0.5).astype('int32'))
left = max(0, np.floor(left + 0.5).astype('int32'))
bottom = min(np.shape(image)[0], np.floor(bottom + 0.5).astype('int32'))
right = min(np.shape(image)[1], np.floor(right + 0.5).astype('int32'))
if self.classification:
image_crop = image.crop((left, top, right, bottom))
image_bytearr = io.BytesIO()
image_crop.save(image_bytearr, format='JPEG')
image_bytes = image_bytearr.getvalue()
data = {'data': [f'data:image;base64,{base64.b64encode(image_bytes).decode()}']}
response = requests.post('http://127.0.0.1:7860/api/predict/', json=data).json()
result = json.loads(response.get('data')[0].get('label'))
predicted_class = result.get('result')
recognition_rate = result.get('recognition_rate')
recognition_rate = float(recognition_rate.replace('%', '')) / 100
recognition_rate_list.append(recognition_rate)
# 画框框
label = '{} {:.2f}'.format(predicted_class, score)
draw = ImageDraw.Draw(image)
label_size = draw.textsize(label, font)
# if self.detection_results:
_, file_name = os.path.split(image_path)
file_name, _ = os.path.splitext(file_name)
with open(os.path.join(DR_PATH, file_name + '.txt'), mode='a', encoding='utf-8') as f:
f.write(f'{predicted_class} {score} {left} {top} {right} {bottom}\n')
logger.info(label)
label = label.encode('utf-8')
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
for i in range(thickness):
draw.rectangle(
[left + i, top + i, right - i, bottom - i],
outline=self.colors[int(c)])
draw.rectangle(
[tuple(text_origin), tuple(text_origin + label_size)],
fill=self.colors[int(c)])
draw.text(text_origin, str(label, 'UTF-8'), fill=(0, 0, 0), font=font)
del draw
end_time = time.time()
logger.info(f'识别时间为{end_time - start_time}s')
logger.info(f'总体置信度为{round(self.recognition_probability(recognition_rate_list), 2) * 100}%')
return image
elif MODE == 'YOLO' or MODE == 'YOLO_TINY':
if self.app:
image = Image.fromarray(image_path)
else:
image = Image.open(image_path)
if image.mode != 'RGB':
image = image.convert('RGB')
new_image_size = (IMAGE_HEIGHT, IMAGE_WIDTH)
boxed_image = self.letterbox_image(image, new_image_size)
image_data = np.array(boxed_image, dtype='float32')
image_data /= 255.
image_data = np.expand_dims(image_data, 0) # Add batch dimension.
# 预测结果
out_boxes, out_scores, out_classes = self.sess.run(
[self.boxes, self.scores, self.classes],
feed_dict={
self.model.input: image_data,
self.input_image_shape: [image.size[1], image.size[0]],
# KT.learning_phase(): 0
})
if len(out_boxes) <= 0:
_, file_name = os.path.split(image_path)
file_name, _ = os.path.splitext(file_name)
with open(os.path.join(DR_PATH, file_name + '.txt'), mode='a', encoding='utf-8') as f:
f.write(f'Fail {0} {0} {0} {0} {0}\n')
return image
# logger.debug('Found {} boxes for {}'.format(len(out_boxes), 'img'))
# 设置字体
font = ImageFont.truetype(font='simhei.ttf',
size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
thickness = (image.size[0] + image.size[1]) // 300
for i, c in list(enumerate(out_classes)):
predicted_class = self.num_classes_list[c]
box = out_boxes[i]
score = out_scores[i]
recognition_rate_list.append(score)
top, left, bottom, right = box
top = top - 5
left = left - 5
bottom = bottom + 5
right = right + 5
top = max(0, np.floor(top + 0.5).astype('int32'))
left = max(0, np.floor(left + 0.5).astype('int32'))
bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
# 画框框
label = '{} {:.2f}'.format(predicted_class, score)
draw = ImageDraw.Draw(image)
label_size = draw.textsize(label, font)
_, file_name = os.path.split(image_path)
file_name, _ = os.path.splitext(file_name)
with open(os.path.join(DR_PATH, file_name + '.txt'), mode='a', encoding='utf-8') as f:
f.write(f'{predicted_class} {score} {left} {top} {right} {bottom}\n')
logger.info(label)
label = label.encode('utf-8')
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
for i in range(thickness):
draw.rectangle(
[left + i, top + i, right - i, bottom - i],
outline=self.colors[c])
draw.rectangle(
[tuple(text_origin), tuple(text_origin + label_size)],
fill=self.colors[c])
draw.text(text_origin, str(label, 'UTF-8'), fill=(0, 0, 0), font=font)
del draw
end_time = time.time()
mean_time.append(end_time - start_time)
logger.info(f'识别时间为{end_time - start_time}s')
logger.info(f'平均识别时间为{np.mean(mean_time)}s')
logger.info(f'总体置信度为{round(self.recognition_probability(recognition_rate_list), 2) * 100}%')
return image
elif MODE == 'SSD':
if self.app:
image = Image.fromarray(image_path)
else:
image = Image.open(image_path)
if image.mode != 'RGB':
image = image.convert('RGB')
image_shape = np.array(np.shape(image)[0:2])
crop_img, x_offset, y_offset = self.letterbox_image(image, (IMAGE_HEIGHT, IMAGE_WIDTH))
photo = np.array(crop_img, dtype=np.float64)
photo = tf.keras.applications.imagenet_utils.preprocess_input(
np.reshape(photo, [1, IMAGE_HEIGHT, IMAGE_WIDTH, 3]))
preds = self.model(photo).numpy()
results = self.bbox_util.detection_out(preds, confidence_threshold=self.ssdconfidence)
if len(results[0]) <= 0:
# if self.detection_results:
_, file_name = os.path.split(image_path)
file_name, _ = os.path.splitext(file_name)
with open(os.path.join(DR_PATH, file_name + '.txt'), mode='a', encoding='utf-8') as f:
f.write(f'Fail {0} {0} {0} {0} {0}\n')
return image
det_label = results[0][:, 0]
det_conf = results[0][:, 1]
det_xmin, det_ymin, det_xmax, det_ymax = results[0][:, 2], results[0][:, 3], results[0][:, 4], results[0][:,
5]
top_indices = [i for i, conf in enumerate(det_conf) if conf >= self.ssdconfidence]
top_conf = det_conf[top_indices]
top_label_indices = det_label[top_indices].tolist()
top_xmin, top_ymin, top_xmax, top_ymax = np.expand_dims(det_xmin[top_indices], -1), np.expand_dims(
det_ymin[top_indices], -1), np.expand_dims(det_xmax[top_indices], -1), np.expand_dims(
det_ymax[top_indices],
-1)
boxes = self.ssd_correct_boxes(top_ymin, top_xmin, top_ymax, top_xmax,
np.array([IMAGE_HEIGHT, IMAGE_WIDTH]), image_shape)
font = ImageFont.truetype(font='simhei.ttf',
size=np.floor(3e-2 * np.shape(image)[1] + 0.5).astype('int32'))
thickness = (np.shape(image)[0] + np.shape(image)[1]) // IMAGE_HEIGHT
for i, c in enumerate(top_label_indices):
predicted_class = self.num_classes_list[int(c)]
score = top_conf[i]
recognition_rate_list.append(score)
top, left, bottom, right = boxes[i]
top = top - 5
left = left - 5
bottom = bottom + 5
right = right + 5
top = max(0, np.floor(top + 0.5).astype('int32'))
left = max(0, np.floor(left + 0.5).astype('int32'))
bottom = min(np.shape(image)[0], np.floor(bottom + 0.5).astype('int32'))
right = min(np.shape(image)[1], np.floor(right + 0.5).astype('int32'))
if self.classification:
image_crop = image.crop((left, top, right, bottom))
image_bytearr = io.BytesIO()
image_crop.save(image_bytearr, format='JPEG')
image_bytes = image_bytearr.getvalue()
data = {'data': [f'data:image;base64,{base64.b64encode(image_bytes).decode()}']}
response = requests.post('http://127.0.0.1:7860/api/predict/', json=data).json()
result = json.loads(response.get('data')[0].get('label'))
predicted_class = result.get('result')
recognition_rate = result.get('recognition_rate')
recognition_rate = float(recognition_rate.replace('%', '')) / 100
recognition_rate_list.append(recognition_rate)
# 画框框
label = '{} {:.2f}'.format(predicted_class, score)
draw = ImageDraw.Draw(image)
label_size = draw.textsize(label, font)
# if self.detection_results:
_, file_name = os.path.split(image_path)
file_name, _ = os.path.splitext(file_name)
with open(os.path.join(DR_PATH, file_name + '.txt'), mode='a', encoding='utf-8') as f:
f.write(f'{predicted_class} {score} {left} {top} {right} {bottom}\n')
logger.info(label)
label = label.encode('utf-8')
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
for i in range(thickness):
draw.rectangle(
[left + i, top + i, right - i, bottom - i],
outline=self.colors[int(c)])
draw.rectangle(
[tuple(text_origin), tuple(text_origin + label_size)],
fill=self.colors[int(c)])
draw.text(text_origin, str(label, 'UTF-8'), fill=(0, 0, 0), font=font)
del draw
end_time = time.time()
logger.info(f'识别时间为{end_time - start_time}s')
logger.info(f'总体置信度为{round(self.recognition_probability(recognition_rate_list), 2) * 100}%')
return image
else:
if PRUNING:
model = self.model
input_details = model.get_input_details()
output_details = model.get_output_details()
image_object = self.decode_image(image_path)
model.set_tensor(input_details[0]['index'], image_object)
model.invoke()
vertor = model.get_tensor(output_details[0]['index'])
else:
model = self.model
image_object = self.decode_image(image_path)
vertor = model.predict(image_object)
text, recognition_rate = self.decode_vector(vector=vertor, num_classes=self.num_classes_dict)
right_text = self.decode_label(image_path)
logger.info(f'预测为{text},真实为{right_text}') if text == right_text else logger.error(
f'预测为{text},真实为{right_text}')
logger.info(f'识别率为:{recognition_rate * 100}%') if recognition_rate > 0.7 else logger.error(
f'识别率为:{recognition_rate * 100}%')
if str(text) != str(right_text):
logger.error(f'预测失败的图片路径为:{image_path}')
right_value = right_value + 1
logger.info(f'正确率:{(predicted_value / right_value) * 100}%')
if predicted_value > 0:
logger.info(f'预测正确{predicted_value}张图片')
else:
predicted_value = predicted_value + 1
right_value = right_value + 1
logger.info(f'正确率:{(predicted_value / right_value) * 100}%')
if predicted_value > 0:
logger.info(f'预测正确{predicted_value}张图片')
end_time = time.time()
logger.info(f'已识别{right_value}张图片')
logger.info(f'识别时间为{end_time - start_time}s')
# return Image.fromarray(image_object[0] * 255)
def get_ground_truth(image):
paths = os.path.splitext(os.path.split(image)[-1])[0]
try:
label = (paths, glob.glob(f'{LABEL_PATH}/*/{paths}.xml')[0])
except:
label = (paths, glob.glob(f'{LABEL_PATH}/{paths}.xml')[0])
index, label_xml = label
file = open(label_xml, encoding='utf-8')
for i in ET.parse(file).getroot().iter('object'):
with open(NUMBER_CLASSES_FILE, 'r', encoding='utf-8') as f:
result = f.read()
num_classes_dict = json.loads(result)
if len(num_classes_dict) == 1:
classes = 'block'
else:
classes = i.find('name').text
xmlbox = i.find('bndbox')
box = (int(float(xmlbox.find('xmin').text)), int(float(xmlbox.find('ymin').text)),
int(float(xmlbox.find('xmax').text)),
int(float(xmlbox.find('ymax').text)))
with open(os.path.join(GT_PATH, index + '.txt'), mode='a', encoding='utf-8') as f:
f.write(f'{classes} {box[0]} {box[1]} {box[2]} {box[3]}\n')
file.close()
def get_images_optional(image):
_, file = os.path.split(image)
new_file = os.path.join(IMG_PATH, file)
logger.debug(f'正在复制{image}到{new_file}')
shutil.copy(image, new_file)
logger.success('复制完成')
if not os.path.exists(GT_PATH):
os.mkdir(GT_PATH)
if not os.path.exists(DR_PATH):
os.mkdir(DR_PATH)
if not os.path.exists(IMG_PATH):
os.mkdir(IMG_PATH)
test_image_list = Image_Processing.extraction_image(TEST_PATH)
if len(os.listdir(IMG_PATH)) == 0:
for image in test_image_list:
get_images_optional(image)
if len(os.listdir(GT_PATH)) == 0:
for image in test_image_list:
get_ground_truth(image)
if len(os.listdir(DR_PATH)) == 0:
if PRUNING:
model_path = os.path.join(MODEL_PATH, PRUNING_MODEL_NAME)
else:
model_path = os.path.join(MODEL_PATH, MODEL_NAME)
logger.debug(f'加载模型{model_path}')
if not os.path.exists(model_path):
raise OSError(f'{model_path}没有模型')
Predict = Predict_Images(model_path=model_path)
for image in test_image_list:
Predict.predict_image(image)
MINOVERLAP = 0.5 # default value (defined in the PASCAL VOC2012 challenge)
parser = argparse.ArgumentParser()
parser.add_argument('-na', '--no-animation', help="no animation is shown.", action="store_true")
parser.add_argument('-np', '--no-plot', help="no plot is shown.", action="store_true")
parser.add_argument('-q', '--quiet', help="minimalistic console output.", action="store_true")
# argparse receiving list of classes to be ignored (e.g., python main.py --ignore person book)
parser.add_argument('-i', '--ignore', nargs='+', type=str, help="ignore a list of classes.")
# argparse receiving list of classes with specific IoU (e.g., python main.py --set-class-iou person 0.7)
parser.add_argument('--set-class-iou', nargs='+', type=str, help="set IoU for a specific class.")
args = parser.parse_args()
'''
0,0 ------> x (width)
|
| (Left,Top)
| *_________
| | |
| |
y |_________|
(height) *
(Right,Bottom)
'''
# if there are no classes to ignore then replace None by empty list
if args.ignore is None:
args.ignore = []
specific_iou_flagged = False
if args.set_class_iou is not None:
specific_iou_flagged = True
# make sure that the cwd() is the location of the python script (so that every path makes sense)
if os.path.exists(IMG_PATH):
for dirpath, dirnames, files in os.walk(IMG_PATH):
if not files:
args.no_animation = True
else:
args.no_animation = True
# try to import OpenCV if the user didn't choose the option --no-animation
show_animation = False
if not args.no_animation:
try:
import cv2
show_animation = True
except ImportError:
print("\"opencv-python\" not found, please install to visualize the results.")
args.no_animation = True
# try to import Matplotlib if the user didn't choose the option --no-plot
draw_plot = False
if not args.no_plot:
try:
import matplotlib.pyplot as plt
draw_plot = True
except ImportError:
print("\"matplotlib\" not found, please install it to get the resulting plots.")
args.no_plot = True
def log_average_miss_rate(prec, rec, num_images):
"""
log-average miss rate:
Calculated by averaging miss rates at 9 evenly spaced FPPI points
between 10e-2 and 10e0, in log-space.
output:
lamr | log-average miss rate
mr | miss rate
fppi | false positives per image
references:
[1] Dollar, Piotr, et al. "Pedestrian Detection: An Evaluation of the
State of the Art." Pattern Analysis and Machine Intelligence, IEEE
Transactions on 34.4 (2012): 743 - 761.
"""
# if there were no detections of that class
if prec.size == 0:
lamr = 0
mr = 1
fppi = 0
return lamr, mr, fppi
fppi = (1 - prec)
mr = (1 - rec)
fppi_tmp = np.insert(fppi, 0, -1.0)
mr_tmp = np.insert(mr, 0, 1.0)
# Use 9 evenly spaced reference points in log-space
ref = np.logspace(-2.0, 0.0, num=9)
for i, ref_i in enumerate(ref):
# np.where() will always find at least 1 index, since min(ref) = 0.01 and min(fppi_tmp) = -1.0
j = np.where(fppi_tmp <= ref_i)[-1][-1]
ref[i] = mr_tmp[j]
# log(0) is undefined, so we use the np.maximum(1e-10, ref)
lamr = math.exp(np.mean(np.log(np.maximum(1e-10, ref))))
return lamr, mr, fppi
"""
throw error and exit
"""
def error(msg):
print(msg)
sys.exit(0)
"""
check if the number is a float between 0.0 and 1.0
"""
def is_float_between_0_and_1(value):
try:
val = float(value)
if val > 0.0 and val < 1.0:
return True
else:
return False
except ValueError:
return False
"""
Calculate the AP given the recall and precision array
1st) We compute a version of the measured precision/recall curve with
precision monotonically decreasing
2nd) We compute the AP as the area under this curve by numerical integration.
"""
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: for i=numel(mpre)-1:-1:1
mpre(i)=max(mpre(i),mpre(i+1));
"""
# 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
"""
Convert the lines of a file to a list
"""
def file_lines_to_list(path):
# open txt file lines to a list
with open(path, encoding='utf-8') as f:
content = f.readlines()
# remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
return content
"""
Draws text in image
"""
def draw_text_in_image(img, text, pos, color, line_width):
font = cv2.FONT_HERSHEY_PLAIN
fontScale = 1
lineType = 1
bottomLeftCornerOfText = pos
cv2.putText(img, text,
bottomLeftCornerOfText,
font,
fontScale,
color,
lineType)
text_width, _ = cv2.getTextSize(text, font, fontScale, lineType)[0]
return img, (line_width + text_width)
"""
Plot - adjust axes
"""
def adjust_axes(r, t, fig, 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])
"""
Draw plot using Matplotlib
"""
def draw_plot_func(dictionary, n_classes, window_title, plot_title, x_label, output_path, to_show, plot_color,
true_p_bar):
# 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 -> TP: True Positives (object detected and matches ground-truth)
- red -> FP: False Positives (object detected but does not match ground-truth)
- pink -> FN: False Negatives (object not detected but present in the ground-truth)
"""
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 Positive')
plt.barh(range(n_classes), tp_sorted, align='center', color='forestgreen', label='True Positive',
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
fig.canvas.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()
"""
Create a ".temp_files/" and "output/" directory
"""
TEMP_FILES_PATH = ".temp_files"
if not os.path.exists(TEMP_FILES_PATH): # if it doesn't exist already
os.makedirs(TEMP_FILES_PATH)
output_files_path = OUTPUT_PATH
if os.path.exists(output_files_path): # if it exist already
# reset the output directory
shutil.rmtree(output_files_path)
os.makedirs(output_files_path)
if draw_plot:
os.makedirs(os.path.join(output_files_path, "classes"))
if show_animation:
os.makedirs(os.path.join(output_files_path, "images", "detections_one_by_one"))
"""
ground-truth
Load each of the ground-truth files into a temporary ".json" file.
Create a list of all the class names present in the ground-truth (gt_classes).
"""
# get a list with the ground-truth files
ground_truth_files_list = glob.glob(GT_PATH + '/*.txt')
if len(ground_truth_files_list) == 0:
error("Error: No ground-truth files found!")
ground_truth_files_list.sort()
# dictionary with counter per class
gt_counter_per_class = {}
counter_images_per_class = {}
gt_files = []
for txt_file in ground_truth_files_list:
# print(txt_file)
file_id = txt_file.split(".txt", 1)[0]
file_id = os.path.basename(os.path.normpath(file_id))
# check if there is a correspondent detection-results file
temp_path = os.path.join(DR_PATH, (file_id + ".txt"))
if not os.path.exists(temp_path):
error_msg = "Error. File not found: {}\n".format(temp_path)
error_msg += "(You can avoid this error message by running extra/intersect-gt-and-dr.py)"
error(error_msg)
lines_list = file_lines_to_list(txt_file)
# create ground-truth dictionary
bounding_boxes = []
is_difficult = False
already_seen_classes = []
for line in lines_list:
try:
if "difficult" in line:
class_name, left, top, right, bottom, _difficult = line.split()
is_difficult = True
else:
class_name, left, top, right, bottom = line.split()
except ValueError:
error_msg = "Error: File " + txt_file + " in the wrong format.\n"
error_msg += " Expected: <class_name> <left> <top> <right> <bottom> ['difficult']\n"
error_msg += " Received: " + line
error_msg += "\n\nIf you have a <class_name> with spaces between words you should remove them\n"
error_msg += "by running the script \"remove_space.py\" or \"rename_class.py\" in the \"extra/\" folder."
error(error_msg)
# check if class is in the ignore list, if yes skip
if class_name in args.ignore:
continue
bbox = left + " " + top + " " + right + " " + bottom
if is_difficult:
bounding_boxes.append({"class_name": class_name, "bbox": bbox, "used": False, "difficult": True})
is_difficult = False
else:
bounding_boxes.append({"class_name": class_name, "bbox": bbox, "used": False})
# count that object
if class_name in gt_counter_per_class:
gt_counter_per_class[class_name] += 1
else:
# if class didn't exist yet
gt_counter_per_class[class_name] = 1
if class_name not in already_seen_classes:
if class_name in counter_images_per_class:
counter_images_per_class[class_name] += 1
else:
# if class didn't exist yet
counter_images_per_class[class_name] = 1
already_seen_classes.append(class_name)
# dump bounding_boxes into a ".json" file
new_temp_file = TEMP_FILES_PATH + "/" + file_id + "_ground_truth.json"
gt_files.append(new_temp_file)
with open(new_temp_file, 'w', encoding='utf-8') as outfile:
json.dump(bounding_boxes, outfile)
gt_classes = list(gt_counter_per_class.keys())
# let's sort the classes alphabetically
gt_classes = sorted(gt_classes)
n_classes = len(gt_classes)
# print(gt_classes)
# print(gt_counter_per_class)
"""
Check format of the flag --set-class-iou (if used)
e.g. check if class exists
"""
if specific_iou_flagged:
n_args = len(args.set_class_iou)
error_msg = \
'\n --set-class-iou [class_1] [IoU_1] [class_2] [IoU_2] [...]'
if n_args % 2 != 0:
error('Error, missing arguments. Flag usage:' + error_msg)
# [class_1] [IoU_1] [class_2] [IoU_2]
# specific_iou_classes = ['class_1', 'class_2']
specific_iou_classes = args.set_class_iou[::2] # even
# iou_list = ['IoU_1', 'IoU_2']
iou_list = args.set_class_iou[1::2] # odd
if len(specific_iou_classes) != len(iou_list):
error('Error, missing arguments. Flag usage:' + error_msg)
for tmp_class in specific_iou_classes:
if tmp_class not in gt_classes:
error('Error, unknown class \"' + tmp_class + '\". Flag usage:' + error_msg)