-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
FRCNN.py
3333 lines (2783 loc) · 139 KB
/
FRCNN.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
###############################################################################
#
# Faster-RCNN is composed of 3 neural networks
# Feature Network
# - usually a well-known pre-trained image classifier such as VGG or ResNet50
# minus a few layers
# - to generate good features from the images
# Region Proposal Network (RPN)
# - usually a simple network with 3 convolutional layers
# - to generate a number of bounding boxes called Region of interests (ROIs)
# that has high probability of containing any object
# Detection Network (RCNN network)
# - takes input from both the feature network and RPN, and generates the
# final class and bounding box
#
#
# based on the work by yhenon (https://github.com/yhenon/keras-frcnn/) and
# RockyXu66 (https://github.com/RockyXu66/Faster_RCNN_for_Open_Images_Dataset_Keras),
# - converted to use tensorflow.keras
# - refactored to be used as a library, following tensorflow.keras Model API
###############################################################################
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Add, Input, InputSpec, Dense, Activation, Dropout
from tensorflow.keras.layers import Flatten, Conv2D
from tensorflow.keras.layers import AveragePooling2D, TimeDistributed
from tensorflow.keras import optimizers
from tensorflow.keras import initializers, regularizers
from tensorflow.keras.backend import categorical_crossentropy
import tensorflow.keras.utils as utils
import tensorflow.keras.backend as K
import numpy as np
import pandas as pd
import cv2
import time
import random
import math
import copy
import os
import sys
import imgaug.augmenters as iaa
from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage
import imgaug as ia
from matplotlib import pyplot as plt
from collections import Counter
from numba import jit
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
# tf.config.optimizer.set_jit(True)
DEBUG = False
class FRCNN(): # class FRCNN(tf.keras.Model):
def __init__(
self,
base_net_type='resnet50', base_trainable=False,
num_classes=10, input_shape=(None, None, 3),
num_rois=256, num_anchors=9
):
# super(FRCNN, self).__init__(name='frcnn')
self.num_classes = num_classes
self.num_anchors = num_anchors
self.num_rois = num_rois
self.base_net_type = base_net_type
# Checking of inputs for Feature Network (Base Net),
# allow some flexibility in name of base_net
base_net_type = base_net_type.lower()
if ('resnet' in base_net_type):
base_net_type = 'resnet50'
elif ('vgg' in base_net_type):
base_net_type = 'vgg'
if (base_net_type != 'resnet50' and base_net_type != 'vgg'):
print("Only resnet50 and vgg are currently supported as base models")
raise ValueError
elif (base_net_type == 'resnet50'):
from tensorflow.keras.applications import ResNet50 as fn
elif (base_net_type == 'vgg'):
from tensorflow.keras.applications import VGG16 as fn
img_input = Input(shape=input_shape)
roi_input = Input(shape=(None, 4))
# Define Feature Network
# Assume we will always use pretrained weights for Feature Network for now
base_net = fn(weights='imagenet', include_top=False, input_tensor=img_input)
for layer in base_net.layers:
layer.trainable = base_trainable
layer._name = layer.name + "a" # prevent duplicate layer name
# For VGG, the last max pooling layer in VGGNet is also removed
if (base_net_type == 'vgg'):
# base_net.layers.pop() # does not work - https://github.com/tensorflow/tensorflow/issues/22479
feature_network = base_net.layers[-2].output
num_features = 512
# For Resnet50, the last stage (stage 5) is also removed
else:
# feature_network = base_net.outputs[0]
# lastStage = max([i if 'res5a_branch2a' in x.name else 0 for i,x in enumerate(base_net.layers)]) - 1
lastStage = 142
feature_network = base_net.layers[lastStage].output
num_features = 1024
self.feature_network = feature_network
# Define RPN, built upon the base layers
rpn = _rpn(feature_network, num_anchors)
classifier = _classifier(
feature_network, roi_input, num_rois, nb_classes=num_classes,
trainable=True, base_net_type=base_net_type)
self.model_rpn = Model(img_input, rpn[:2])
self.model_classifier = Model([img_input, roi_input], classifier)
# this will be the model that holds both the RPN and the classifier, used to load/save weights for the models
self.model_all = Model([img_input, roi_input], rpn[:2] + classifier)
# Create models that will be used for predictions
roi_input = Input(shape=(num_rois, 4))
feature_map_input = Input(shape=(None, None, num_features))
p_classifier = _classifier(
feature_map_input, roi_input, num_rois, nb_classes=num_classes,
trainable=True, base_net_type=base_net_type)
self.predict_rpn = Model(img_input, rpn)
self.predict_classifier = Model([feature_map_input, roi_input], p_classifier)
# return model_all
def summary(self, line_length=None, positions=None, print_fn=None):
"""Prints a string summary of the overall FRCNN network
Arguments:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided,
defaults to `[.33, .55, .67, 1.]`.
print_fn: Print function to use. Defaults to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
return self.model_all.summary(line_length=line_length, positions=positions, print_fn=print_fn)
def compile(
self,
optimizer=None,
loss=None,
**kwargs):
"""Configures the model for training.
Arguments:
optimizer: Array of String (name of optimizer), array of optimizer instance,
String (name of optimizer) or optimizer instance
See `tf.keras.optimizers`. If it is not an array, the same optimizer will
be used for all submodels. Otherwise index 0-rpn, 1-classifier, 2-all.
Set to None to use defaults
Example: [optimizers.Adam(lr=1e-5), optimizers.Adam(lr=1e-5), 'sgd']
loss: Array of String (name of objective function), array of objective function,
String (name of objective function), objective function or
`tf.losses.Loss` instance. See `tf.losses`. If it is not an array,
the same loss will be used for all submodels. Otherwise, index
0-rpn, 1-classifier, 2-all.
If the model has multiple outputs, you can use a different loss on each output by
passing a dictionary or a list of losses. The loss value that will
be minimized by the model will then be the sum of all individual
losses.
Set to None to use defaults
**kwargs: Any additional arguments.
Raises:
ValueError: In case of invalid arguments for
`optimizer`, `loss`, `metrics` or `sample_weight_mode`.
"""
# Allow user to override defaults
if optimizer is not None:
# Ideally optimizer settings should be specified individually
if (isinstance(optimizer, list)):
if (len(optimizer) != 3):
print("Length of list for optimizer should be 3")
raise ValueError
else:
optimizer_rpn = optimizer[0]
optimizer_classifier = optimizer[1]
optimizer_all = optimizer[2]
# Use same optimizer for all
else:
optimizer_rpn = optimizer
optimizer_classifier = optimizer
optimizer_all = optimizer
# Use defaults for optimizers if not specified
else:
optimizer_rpn = optimizers.Adam(lr=1e-5)
optimizer_classifier = optimizers.Adam(lr=1e-5)
optimizer_all = 'sgd'
if loss is not None:
if (isinstance(loss, list)):
if (len(loss) != 3):
print("Length of list for loss should be 3")
raise ValueError
else:
loss_rpn = loss[0]
loss_classifier = loss[1]
loss_all = loss[2]
# Use same loss function for all
else:
loss_rpn = loss
loss_classifier = loss
# Use defaults for loss if not specified
else:
loss_rpn = [rpn_loss_cls(self.num_anchors), rpn_loss_regr(self.num_anchors)]
loss_classifier = [class_loss_cls, class_loss_regr(self.num_classes - 1)]
loss_all = 'mae'
self.model_rpn.compile(optimizer=optimizer_rpn, loss=loss_rpn)
self.model_classifier.compile(
optimizer=optimizer_classifier,
loss=loss_classifier, metrics={'dense_class_{}'.format(self.num_classes): 'accuracy'})
self.model_all.compile(optimizer=optimizer_all, loss=loss_all)
self.predict_rpn.compile(optimizer='sgd', loss='mse')
self.predict_classifier.compile(optimizer='sgd', loss='mse')
def fit_generator(
self,
generator,
steps_per_epoch=1000,
epochs=1,
verbose=1,
initial_epoch=-1,
class_mapping=None,
target_size=-1, # length of shorter size
anchor_box_scales=[128, 256, 512],
anchor_box_ratios=[[1, 1], [1./math.sqrt(2), 2./math.sqrt(2)], [2./math.sqrt(2), 1./math.sqrt(2)]],
std_scaling=4.0, # for scaling of standard deviation
classifier_regr_std=[8.0, 8.0, 4.0, 4.0], #
classifier_min_overlap=0.1, # repo values
classifier_max_overlap=0.5, # repo values
rpn_stride=16, # stride at the RPN (this depends on the network configuration)
model_path='./frcnn.hdf5',
csv_path="./frcnn.csv"
):
"""Fits the model on data yielded batch-by-batch by FRCNNGenerator.
Will automatically save model and csv to the specified paths
model_path and csv_path respectively.
If file at model_path exists, will automatically resume training
if initial_epoch is set to -1. Otherwise, will prompt user to resume
training
Arguments:
generator: Generator that was created via FRCNNGenerator
The generator is expected to loop over its data
indefinitely. An epoch finishes when `steps_per_epoch`
batches have been seen by the model.
steps_per_epoch: Total number of steps (batches of samples)
to yield from `generator` before declaring one epoch
finished and starting the next epoch.
epochs: Integer, total number of iterations on the data.
verbose: Verbosity mode. 0 = Silent, 1 = progress bar
initial_epoch: Integer. Epoch at which to start training
(useful for resuming a previous training run)
model_path: Path for saving model hdf5. Also used to resume training
csv_path: Path for saving training csv. Also used to resume training
class_mapping: Class mapping based on training set. This is the third output from parseAnnotationFile()
target_size: Integer. Shorter-side length. Used for image resizing based on the shorter length
Returns:
None
Raises:
ValueError: In case the generator yields data in an invalid format.
"""
epoch_length = steps_per_epoch
iter_num = 0
losses = np.zeros((epoch_length, 5))
rpn_accuracy_rpn_monitor = []
rpn_accuracy_for_epoch = []
best_loss = np.Inf
# input validation
if (class_mapping is None):
print("class_mapping should not be None")
raise ValueError
elif (target_size < 0):
print("target_size (shorter-side size) must be a positive integer")
raise ValueError
print()
# let's check if model file exists
if not os.path.isfile(model_path):
print('Starting training')
initial_epoch = 0
# Create the record.csv file to record losses, acc and mAP
record_df = pd.DataFrame(
columns=[
'mean_overlapping_bboxes', 'class_acc', 'loss_rpn_cls',
'loss_rpn_regr', 'loss_class_cls', 'loss_class_regr', 'curr_loss', 'elapsed_time', 'mAP'])
else:
# if setting is not to continue training and file exists, confirm with user again,
# before overwriting file, just in case
if (initial_epoch != -1):
ask = input('File %s exists. Continue training? [Y/N]' % (model_path))
if (ask.lower() in ['y', 'yes', 'ya']):
initial_epoch = -1
else:
print('Restarting training and overwriting %s and %s' % (model_path, csv_path))
if (initial_epoch == -1):
# If this is a continued training, load the trained model from before
print('Continuing training based on previous trained model')
print('Loading weights from {}'.format(model_path))
self.model_rpn.load_weights(model_path, by_name=True)
self.model_classifier.load_weights(model_path, by_name=True)
record_df = pd.read_csv(csv_path)
initial_epoch = len(record_df)
# for debugging
# r_mean_overlapping_bboxes = record_df['mean_overlapping_bboxes']
# r_class_acc = record_df['class_acc']
# r_loss_rpn_cls = record_df['loss_rpn_cls']
# r_loss_rpn_regr = record_df['loss_rpn_regr']
# r_loss_class_cls = record_df['loss_class_cls']
# r_loss_class_regr = record_df['loss_class_regr']
# r_elapsed_time = record_df['elapsed_time']
# r_mAP = record_df['mAP']
r_curr_loss = record_df['curr_loss']
best_loss = np.min(r_curr_loss)
if verbose:
print('Already trained %dK batches' % (len(record_df)))
####
start_time = time.time()
total_epoch = initial_epoch + epochs # We might be resuming training, so we will start with initial_epoch
for epoch_num in range(epochs):
progbar = utils.Progbar(epoch_length)
print('Epoch {}/{}'.format(initial_epoch + 1 + epoch_num, total_epoch))
while True:
try:
if len(rpn_accuracy_rpn_monitor) == epoch_length and verbose:
mean_overlapping_bboxes = float(sum(rpn_accuracy_rpn_monitor))/len(rpn_accuracy_rpn_monitor)
rpn_accuracy_rpn_monitor = []
if mean_overlapping_bboxes == 0:
print('RPN is not producing bounding boxes that overlap the ground truth boxes. Check RPN settings or keep training.')
# Generate X (x_img) and label Y ([y_rpn_cls, y_rpn_regr])
X, Y, img_data, debug_img, debug_num_pos = next(generator)
if DEBUG:
print("DEBUG", img_data['filepath'])
# Train rpn model and get loss value [_, loss_rpn_cls, loss_rpn_regr]
loss_rpn = self.model_rpn.train_on_batch(X, Y)
# Get predicted rpn from rpn model [rpn_cls, rpn_regr]
P_rpn = self.model_rpn.predict_on_batch(X)
# R: bboxes (shape=(300,4))
# Convert rpn layer to roi bboxes
R = rpn_to_roi(
P_rpn[0], P_rpn[1],
std_scaling, anchor_box_ratios, anchor_box_scales, rpn_stride,
use_regr=True, overlap_thresh=0.7, max_boxes=300)
# note: calc_iou converts from (x1,y1,x2,y2) to (x,y,w,h) format
# X2: bboxes that iou > C.classifier_min_overlap for all gt bboxes in 300 non_max_suppression bboxes
# Y1: one hot code for bboxes from above => x_roi (X)
# Y2: corresponding labels and corresponding gt bboxes
X2, Y1, Y2, IouS = calc_iou(
R, img_data, [classifier_min_overlap, classifier_max_overlap],
target_size, rpn_stride, class_mapping, classifier_regr_std)
if DEBUG:
print("DEBUG calc_iou (inputs)", classifier_min_overlap, classifier_max_overlap, target_size, rpn_stride, class_mapping, classifier_regr_std)
print("DEBUG calc_iou", X2, Y1, Y2, IouS)
# If X2 is None means there are no matching bboxes
if X2 is None:
rpn_accuracy_rpn_monitor.append(0)
rpn_accuracy_for_epoch.append(0)
continue
# Find out the positive anchors and negative anchors
neg_samples = np.where(Y1[0, :, -1] == 1)
pos_samples = np.where(Y1[0, :, -1] == 0)
if len(neg_samples) > 0:
neg_samples = neg_samples[0]
else:
neg_samples = []
if len(pos_samples) > 0:
pos_samples = pos_samples[0]
else:
pos_samples = []
rpn_accuracy_rpn_monitor.append(len(pos_samples))
rpn_accuracy_for_epoch.append((len(pos_samples)))
if self.num_rois > 1:
# If number of positive anchors is larger than 4//2 = 2, randomly choose 2 pos samples
if len(pos_samples) < self.num_rois//2:
selected_pos_samples = pos_samples.tolist()
else:
selected_pos_samples = np.random.choice(pos_samples, self.num_rois//2, replace=False).tolist()
# Randomly choose (num_rois - num_pos) neg samples
try:
selected_neg_samples = np.random.choice(neg_samples, self.num_rois - len(selected_pos_samples), replace=False).tolist()
except ValueError:
try:
selected_neg_samples = np.random.choice(neg_samples, self.num_rois - len(selected_pos_samples), replace=True).tolist()
except Exception as e:
if DEBUG: print(e)
# The neg_samples is [[1 0 ]] only, therefore there's no negative sample
continue
# Save all the pos and neg samples in sel_samples
sel_samples = selected_pos_samples + selected_neg_samples
else:
# in the extreme case where num_rois = 1, we pick a random pos or neg sample
selected_pos_samples = pos_samples.tolist()
selected_neg_samples = neg_samples.tolist()
if np.random.randint(0, 2):
sel_samples = random.choice(neg_samples)
else:
sel_samples = random.choice(pos_samples)
# training_data: [X, X2[:, sel_samples, :]]
# labels: [Y1[:, sel_samples, :], Y2[:, sel_samples, :]]
# X => img_data resized image
# X2[:, sel_samples, :] => num_rois (4 in here) bboxes which contains selected neg and pos
# Y1[:, sel_samples, :] => one hot encode for num_rois bboxes which contains selected neg and pos
# Y2[:, sel_samples, :] => labels and gt bboxes for num_rois bboxes which contains selected neg and pos
loss_class = self.model_classifier.train_on_batch([X, X2[:, sel_samples, :]], [Y1[:, sel_samples, :], Y2[:, sel_samples, :]])
losses[iter_num, 0] = loss_rpn[1]
losses[iter_num, 1] = loss_rpn[2]
losses[iter_num, 2] = loss_class[1]
losses[iter_num, 3] = loss_class[2]
losses[iter_num, 4] = loss_class[3]
iter_num += 1
progbar.update(
iter_num, [
('rpn_cls', np.mean(losses[:iter_num, 0])), ('rpn_regr', np.mean(losses[:iter_num, 1])),
('final_cls', np.mean(losses[:iter_num, 2])), ('final_regr', np.mean(losses[:iter_num, 3]))
])
if iter_num == epoch_length:
loss_rpn_cls = np.mean(losses[:, 0])
loss_rpn_regr = np.mean(losses[:, 1])
loss_class_cls = np.mean(losses[:, 2])
loss_class_regr = np.mean(losses[:, 3])
class_acc = np.mean(losses[:, 4])
mean_overlapping_bboxes = float(sum(rpn_accuracy_for_epoch)) / len(rpn_accuracy_for_epoch)
rpn_accuracy_for_epoch = []
if verbose:
print('Mean number of bounding boxes from RPN overlapping ground truth boxes: {}'.format(mean_overlapping_bboxes))
print('Classifier accuracy for bounding boxes from RPN: {}'.format(class_acc))
print('Loss RPN classifier: {}'.format(loss_rpn_cls))
print('Loss RPN regression: {}'.format(loss_rpn_regr))
print('Loss Detector classifier: {}'.format(loss_class_cls))
print('Loss Detector regression: {}'.format(loss_class_regr))
print('Total loss: {}'.format(loss_rpn_cls + loss_rpn_regr + loss_class_cls + loss_class_regr))
print('Elapsed time: {}'.format(time.time() - start_time))
elapsed_time = (time.time()-start_time)/60
curr_loss = loss_rpn_cls + loss_rpn_regr + loss_class_cls + loss_class_regr
iter_num = 0
start_time = time.time()
if curr_loss < best_loss:
if verbose:
print('Total loss decreased from {} to {}, saving weights'.format(best_loss, curr_loss))
best_loss = curr_loss
self.model_all.save_weights(model_path)
new_row = {
'mean_overlapping_bboxes': round(mean_overlapping_bboxes, 3),
'class_acc': round(class_acc, 3),
'loss_rpn_cls': round(loss_rpn_cls, 3),
'loss_rpn_regr': round(loss_rpn_regr, 3),
'loss_class_cls': round(loss_class_cls, 3),
'loss_class_regr': round(loss_class_regr, 3),
'curr_loss': round(curr_loss, 3),
'elapsed_time': round(elapsed_time, 3),
'mAP': 0}
record_df = record_df.append(new_row, ignore_index=True)
record_df.to_csv(csv_path, index=0)
break
except Exception as e:
print('Exception: {}'.format(e))
continue
print('-- Training complete, exiting.')
return None
def load_config(
self,
anchor_box_scales=[128, 256, 512],
anchor_box_ratios=[[1, 1], [1./math.sqrt(2), 2./math.sqrt(2)], [2./math.sqrt(2), 1./math.sqrt(2)]],
std_scaling=4.0,
rpn_stride=16, # stride at the RPN (this depends on the network configuration)
num_rois=32,
target_size=600,
img_channel_mean=[103.939, 116.779, 123.68],
img_scaling_factor=1,
classifier_regr_std=[8.0, 8.0, 4.0, 4.0],
):
"""Loads configuration settings for FRCNN model.
These will be used for predictions
Arguments:
anchor_box_scales: Anchor box scales array
anchor_box_ratios: Anchor box ratios array
std_scaling: For scaling of standard deviation
rpn_stride: RPN stride. This should be the same as what was passed into the generator
num_rois: number of regions of interest to be used
target_size: Integer. Shorter-side length. Used for image resizing based on the shorter length
img_channel_mean: image channel-wise (RGB) mean to subtract for standardisation
img_scaling_factor: scaling factor to divide by, for standardisation
classifier_regr_std: For scaling of standard deviation for classifier regression for x,y,w,h
Returns:
None
"""
self.anchor_box_scales = anchor_box_scales
self.anchor_box_ratios = anchor_box_ratios
self.std_scaling = std_scaling
self.rpn_stride = rpn_stride
self.im_size = target_size
self.img_channel_mean = img_channel_mean
self.img_scaling_factor = 1
return None
def load_weights(self, filepath):
"""Loads all layer weights, from an HDF5 file.
Weights are loaded with 'by_name' true, meaning that weights are loaded into
layers only if they share the same name. This assumes a single HDF5 file and
consistent layer names
If it is desired to load weights with 'by_name' is False, and load
weights based on the network's topology, please access the individual embedded
sub-models in this class. eg frcnn.model_rpn.load_weights(filepath, by_name=False)
Arguments:
filepath: String, path to the weights file to load. For weight files in
TensorFlow format, this is the file prefix (the same as was passed
to 'save_weights').
Returns:
None
"""
if (not os.path.isfile(filepath)):
raise FileNotFoundError('File does not exist: %s ' % filepath)
self.model_rpn.load_weights(filepath, by_name=True)
self.model_classifier.load_weights(filepath, by_name=True)
self.predict_rpn.load_weights(filepath, by_name=True)
self.predict_classifier.load_weights(filepath, by_name=True)
return None
def predict(
self,
x, #
verbose=2, #
class_mapping=None,
bbox_threshold=0.7,
overlap_thres=0.2
): #
"""Generates output predictions for the input samples.
Computation is done in batches.
Arguments:
x: Input samples. This should be a list of img data
or a list of dict containing groundtruth bounding
boxes (key=bboxes) and path of the image (key=filepath)
verbose: Verbosity mode.
0 = silent. 1 = print results. 2 = print results and show images
class_mapping: Class mapping based on training set
bbox_threshold: If box classification value is less than this, we will ignore that box
overlap_thres: Non-maximum suppression setting. If overlap > overlap_thres, we will remove the box
Returns:
Numpy array(s) of predictions.
"""
return self._loopSamplesAndPredictOrEvaluate(
x, class_mapping,
bbox_threshold, overlap_thresh=overlap_thres, verbose=verbose)
def evaluate(
self,
x=None,
verbose=2,
class_mapping=None,
overlap_thresh=0.3
):
"""Returns the mean average precision (mAP) for the model in test mode,
using metrics used by the VOC Pascal 2012 challenge.
Computation is done in batches.
Arguments:
x: Input samples. This should be a list of dict containing
groundtruth bounding boxes (key=bboxes) and path of the image (key=filepath)
verbose: Verbosity mode.
0 = silent. 1 = print results. 2 = print results and show images
class_mapping: Class mapping based on training set
overlap_thres: Non-maximum suppression setting. If overlap > overlap_thres, we will remove the box
Returns:
List of mAPs
Raises:
ValueError: in case of invalid arguments.
"""
return self._loopSamplesAndPredictOrEvaluate(
x, class_mapping, overlap_thresh=overlap_thresh, verbose=verbose, mode='evaluate')
# from profilehooks import profile
# @profile
def _loopSamplesAndPredictOrEvaluate(
self, samples, class_mapping, bbox_threshold=None,
overlap_thresh=0.5, verbose=1, mode='predict'
):
visualise = (verbose > 1)
my_bboxes = RPBoundingBoxes() # using rafaelpadilla/Object-Detection-Metrics
# from sklearn.metrics import average_precision_score
output = []
i = 1
isImgData = True
if isinstance(samples[0], dict):
isImgData = False
# For evaluation of mAP, we will need the ground-truth bboxes
if (mode == 'evaluate' and isImgData):
print('For evaluate, please provide input as array of dict containing bboxes and filepath')
raise ValueError
elif (mode == 'evaluate' and visualise):
print('Green: Ground truth bounding boxes. Red: Detected Objects')
if (class_mapping is None):
print("class_mapping should not be None")
raise ValueError
# Switch key and value for class_mapping 'Person': 0 --> 0: 'Person'
class_mapping = {v: k for k, v in class_mapping.items()}
# Assign color to each
class_to_color = {class_mapping[v]: np.random.randint(0, 255, 3) for v in class_mapping}
def get_mAP_RP(pred, gt, f, i, imgSize, my_bboxes1):
imgName = '{:03d}'.format(i)
# add groundtruth bboxes
for bbox in gt:
my_bboxes1.addBoundingBox(RPBoundingBox(
imageName=imgName, classId=bbox['class'],
x=bbox['x1'], y=bbox['y1'],
w=bbox['x2'], h=bbox['y2'],
typeCoordinates=CoordinatesType.Absolute,
bbType=BBType.GroundTruth, format=BBFormat.XYX2Y2, imgSize=imgSize)
)
# add prediction bboxes
for bbox in pred:
my_bboxes1.addBoundingBox(RPBoundingBox(
imageName=imgName, classId=bbox['class'],
x=bbox['x1'], y=bbox['y1'],
w=bbox['x2'], h=bbox['y2'],
typeCoordinates=CoordinatesType.Absolute, classConfidence= bbox['prob'],
bbType=BBType.Detected, format=BBFormat.XYX2Y2, imgSize=imgSize)
)
if visualise:
my_bboxes1.drawAllBoundingBoxes(img_original, imgName)
return my_bboxes1
def plotBBox(real_x1, real_y1, real_x2, real_y2):
cv2.rectangle(
img_original, (real_x1, real_y1), (real_x2, real_y2),
(int(class_to_color[key][0]), int(class_to_color[key][1]), int(class_to_color[key][2])), 4)
textLabel = '{}: {}'.format(key, int(100*new_probs[jk]))
# (retval,baseLine) = cv2.getTextSize(textLabel,cv2.FONT_HERSHEY_COMPLEX,1,1)
textOrg = (real_x1, real_y1-0)
y = real_y1+10 if real_y1 < 10 else real_y1
textOrg = (real_x1, y)
cv2.putText(
img_original, textLabel, textOrg, cv2.FONT_HERSHEY_DUPLEX,
0.5, (255, 255, 255), 2, lineType=cv2.LINE_AA)
cv2.putText(
img_original, textLabel, textOrg, cv2.FONT_HERSHEY_DUPLEX,
0.5, (0, 0, 0), 1, lineType=cv2.LINE_AA)
def calcPredictOutput():
# Calculate real coordinates on original image and save coordinates, and (key and prob) separately
(real_x1, real_y1, real_x2, real_y2) = _get_real_coordinates(ratio, x1, y1, x2, y2)
all_pos.append((real_x1, real_y1, real_x2, real_y2))
all_dets.append((key, 100*new_probs[jk]))
if (visualise):
plotBBox(real_x1, real_y1, real_x2, real_y2)
def calcEvalOutput():
# Save coordinates, class and probability
det = {'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2, 'class': key, 'prob': new_probs[jk]}
all_dets.append(det)
calcOutput = calcPredictOutput if mode == 'predict' else calcEvalOutput # check once, instead of every loop
overall_st = time.time()
for data in samples:
if verbose and not isImgData:
print('{}/{} - {}'.format(i, len(samples), data['filepath']))
i = i + 1
st = time.time()
# convert image
img_original = data if isImgData else cv2.imread(data['filepath'])
img, ratio, fx, fy = _format_img(img_original, self.img_channel_mean, self.img_scaling_factor, self.im_size)
img = np.transpose(img, (0, 2, 3, 1))
# get output layer Y1, Y2 from the RPN and the feature maps F
# Y1: y_rpn_cls, Y2: y_rpn_regr
[Y1, Y2, F] = self.predict_rpn.predict(img) #
# Get bboxes by applying NMS
# R.shape = (300, 4)
R = rpn_to_roi(
Y1, Y2, self.std_scaling, self.anchor_box_ratios, self.anchor_box_scales, self.rpn_stride,
use_regr=True, overlap_thresh=0.7)
# convert from (x1,y1,x2,y2) to (x,y,w,h)
R[:, 2] -= R[:, 0]
R[:, 3] -= R[:, 1]
# apply the spatial pyramid pooling to the proposed regions
bboxes = {}
probs = {}
for jk in range(R.shape[0]//self.num_rois + 1):
ROIs = np.expand_dims(R[self.num_rois*jk:self.num_rois*(jk+1), :], axis=0)
if ROIs.shape[1] == 0:
break
if jk == R.shape[0]//self.num_rois:
# pad R
curr_shape = ROIs.shape
target_shape = (curr_shape[0], self.num_rois, curr_shape[2])
ROIs_padded = np.zeros(target_shape).astype(ROIs.dtype)
ROIs_padded[:, :curr_shape[1], :] = ROIs
ROIs_padded[0, curr_shape[1]:, :] = ROIs[0, 0, :]
ROIs = ROIs_padded
[P_cls, P_regr] = self.predict_classifier.predict([F, ROIs])
# Calculate bboxes coordinates on resized image
for ii in range(P_cls.shape[1]):
# Ignore 'bg' class
if ((bbox_threshold is not None and np.max(P_cls[0, ii, :]) < bbox_threshold) or np.argmax(P_cls[0, ii, :]) == (P_cls.shape[2] - 1)):
continue
# Get class name
cls_name = class_mapping[np.argmax(P_cls[0, ii, :])]
if cls_name not in bboxes:
bboxes[cls_name] = []
probs[cls_name] = []
(x, y, w, h) = ROIs[0, ii, :]
cls_num = np.argmax(P_cls[0, ii, :])
try:
(tx, ty, tw, th) = P_regr[0, ii, 4*cls_num:4*(cls_num+1)]
tx /= self.classifier_regr_std[0]
ty /= self.classifier_regr_std[1]
tw /= self.classifier_regr_std[2]
th /= self.classifier_regr_std[3]
x, y, w, h = apply_regr(x, y, w, h, tx, ty, tw, th)
except Exception as e:
if DEBUG: print(e)
pass
bboxes[cls_name].append([self.rpn_stride*x, self.rpn_stride*y, self.rpn_stride*(x+w), self.rpn_stride*(y+h)])
probs[cls_name].append(np.max(P_cls[0, ii, :]))
all_dets = []
all_pos = []
for key in bboxes:
bbox = np.array(bboxes[key])
# Apply non-max-suppression on final bboxes to get the output bounding boxes
new_boxes, new_probs = non_max_suppression_fast(bbox, np.array(probs[key]), overlap_thresh=overlap_thresh)
for jk in range(new_boxes.shape[0]):
(x1, y1, x2, y2) = new_boxes[jk, :]
# Upate all_dets and all_poos
calcOutput()
if verbose > 0:
print('Elapsed time = {}'.format(time.time() - st))
if mode == 'predict':
if verbose == -1 and len(all_dets)>0 and not isImgData:
print(data['filepath'])
print(all_dets)
if verbose > 0 :
print(all_dets)
output.append((all_dets, all_pos)) # store all predictions and their positions for each image
else:
my_bboxes = get_mAP_RP(all_dets, data['bboxes'], (fx, fy), i, img_original.shape, my_bboxes)
evaluator = Evaluator()
metricsPerClass = evaluator.GetPascalVOCMetrics(my_bboxes, IOUThreshold=0.2)
if verbose:
# Loop through classes to obtain their metrics
for mc in metricsPerClass:
# Get metric values per each class
c = mc['class']
precision = mc['precision']
recall = mc['recall']
average_precision = mc['AP']
ipre = mc['interpolated precision']
irec = mc['interpolated recall']
# Print AP per class
print('%s AP: %f' % (c, average_precision))
output.append(metricsPerClass)
# t, p = get_map(all_dets, data['bboxes'], (fx, fy))
# for key in t.keys():
# if key not in T:
# T[key] = []
# P[key] = []
# T[key].extend(t[key])
# P[key].extend(p[key])
# all_aps = []
# for key in T.keys():
# ap = average_precision_score(T[key], P[key])
# all_aps.append(ap)
# if verbose:
# print('{} AP: {}'.format(key, ap))
# if verbose:
# print('mAP = {}'.format(np.nanmean(np.array(all_aps))))
# print()
# output.append(np.nanmean(np.array(all_aps)))
if visualise:
# plt.figure(figsize=(10,10))
plt.figure()
plt.grid()
plt.imshow(cv2.cvtColor(img_original, cv2.COLOR_BGR2RGB))
plt.show()
if verbose:
print('Total elapsed time = {}'.format(time.time() - overall_st))
output = np.asarray(output)
return output
###############################################################################
def _get_real_coordinates(ratio, x1, y1, x2, y2):
real_x1 = int(round(x1 // ratio))
real_y1 = int(round(y1 // ratio))
real_x2 = int(round(x2 // ratio))
real_y2 = int(round(y2 // ratio))
return (real_x1, real_y1, real_x2, real_y2)
def _format_img(img, img_channel_mean, img_scaling_factor, target_size):
""" format image for prediction or mAP calculation. Resize original image to target_size
Arguments:
img: cv2 image
img_channel_mean: image channel-wise (RGB) mean to subtract for standardisation
img_scaling_factor: scaling factor to divide by, for standardisation
target_size: shorter-side length. Used for image resizing based on the shorter length
Returns:
img: Scaled and normalized image with expanding dimension
ratio: img_min_side / original min side eg img_min_side / width if width <= height
fx: ratio for width scaling (original width / new width)
fy: ratio for height scaling (original height/ new height)
"""
""" resize image based on config """
img_min_side = float(target_size)
(height, width, _) = img.shape
if width <= height:
ratio = img_min_side/width
new_height = int(ratio * height)
new_width = int(img_min_side)
else:
ratio = img_min_side/height
new_width = int(ratio * width)
new_height = int(img_min_side)
fx = width/float(new_width)
fy = height/float(new_height)
img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC)
""" format image channels based on config """
img = img[:, :, (2, 1, 0)]
img = img.astype(np.float32)
img[:, :, 0] -= img_channel_mean[0]
img[:, :, 1] -= img_channel_mean[1]
img[:, :, 2] -= img_channel_mean[2]
img /= img_scaling_factor
img = np.transpose(img, (2, 0, 1))
img = np.expand_dims(img, axis=0)
return img, ratio, fx, fy
def _get_img_output_length(width, height, base_net_type='resnet50'):
b = base_net_type
def get_output_length(input_length, b):
if ('resnet'in b):
# zero_pad
input_length += 6
# apply 4 strided convolutions
filter_sizes = [7, 3, 1, 1]
stride = 2
for filter_size in filter_sizes:
input_length = (input_length - filter_size + stride) // stride
return input_length
else:
return input_length//16
return get_output_length(width, b), get_output_length(height, b)
def _rpn(base_layers, num_anchors):
# common layer fed to 2 layers
# - x_class for classification (is object in bounding box?)
# - x_regr for bounding box regression (ROIs)
x = Conv2D(512, (3, 3), padding='same', activation='relu', kernel_initializer='normal', name='rpn_conv1')(base_layers)
x_class = Conv2D(num_anchors, (1, 1), activation='sigmoid', kernel_initializer='uniform', name='rpn_out_class')(x)
x_regr = Conv2D(num_anchors * 4, (1, 1), activation='linear', kernel_initializer='zero', name='rpn_out_regress')(x)
return [x_class, x_regr, base_layers]
def _classifier(base_layers, input_rois, num_rois, nb_classes=4, trainable=True, base_net_type='resnet50'):
if ('resnet' in base_net_type):
pooling_regions = 14
input_shape = (num_rois, pooling_regions, pooling_regions, 1024)
out_roi_pool = RoiPoolingConv(pooling_regions, num_rois, name='roi_pooling_conv')([base_layers, input_rois])
# out = _classifier_layers(out_roi_pool, input_shape=input_shape, trainable=True)
trainable = True
out = _conv_block_td(out_roi_pool, 3, [512, 512, 2048], stage=5, block='a', input_shape=input_shape, strides=(2, 2), trainable=trainable)
out = _identity_block_td(out, 3, [512, 512, 2048], stage=5, block='b', trainable=trainable)
out = _identity_block_td(out, 3, [512, 512, 2048], stage=5, block='c', trainable=trainable)