-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
2151 lines (1604 loc) · 71 KB
/
utils.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
# Implement Faster-RCNN Project
# Editor: Lee, Jongmo
# Filename: /custom/utils.py
# Reference URL
# https://www.tensorflow.org/guide/checkpoint
# https://www.tensorflow.org/guide/autodiff
import os
import math
import pickle
import random
from glob import glob
from time import time
from ast import literal_eval
from configparser import ConfigParser
from xml.etree.ElementTree import parse
import cv2
from tqdm import tqdm
import tensorflow as tf
number_of_cls, number_of_reg = 2, 4
lightness_max = 255
draw_scale_parameter = 4e-4
text_thickness_unit = 1
line_thickness_unit = 3
black = (0, 0, 0)
def CRLF():
"""
Line break
"""
print()
def square(anchor_side):
"""
Get anchor size from anchor side
Arguments)
1. anchor_side => 'int'
- Length of anchor side line
Returns)
1. anchor_size => 'int'
- Area of anchor
"""
anchor_size = anchor_side * anchor_side
return anchor_size
def load_network_manager(model_class,
ckpt_path,
max_to_keep,
**kwargs):
"""
Load objects to manage model
Arguments)
1. model_class => 'type'
- Class of model defined in models.py
2. ckpt_path => 'str'
- Checkpoint path of model
3. max_to_keep => 'int'
- Max number of checkpoints to keep
4. **kwargs
- Arguments for init model_class
Returns)
1. model => 'custom.models.*'
- Custom model for Faster-RCNN-object-detection
2. ckpt => 'tensorflow.python.training.tracking.util.Checkpoint'
- Model checkpoint
3. ckpt_manager => 'tensorflow.python.training.checkpoint_management.
CheckpointManager'
- Model checkpoint manager
"""
model = model_class(**kwargs)
if os.path.exists(ckpt_path):
latest = tf.train.latest_checkpoint(ckpt_path)
model.load_weights(latest)
print("%s Restored from %s" % (model_class.__name__, latest))
else:
print("%s Initialized" % model_class.__name__)
ckpt = tf.train.Checkpoint(model)
ckpt_manager = tf.train.CheckpointManager(ckpt, ckpt_path, max_to_keep)
return model, ckpt, ckpt_manager
def apply_weight_decay(model,
l2):
"""
Apply weight decay option to model
Arguments)
1. model => 'custom.models.*'
- Custom model to apply weight decay
2. l2 => 'float'
- Weight decay factor
Returns)
1. model => 'custom.models.*'
- Custom model with weight decay applied
"""
for layer in model.layers:
if hasattr(layer, 'kernel_regularizer'):
layer.kernel_regularizer = tf.keras.regularizers.L2(l2)
return model
def get_input_image_and_original_shape(image_path,
image_input_size):
"""
Get tensor array from image file
Arguments)
1. image_path => 'str'
- Image file path
2. image_input_size => 'tuple'
- Fixed shape when input image to model
Returns)
1. image_tensor => 'tensorflow.python.framework.ops.EagerTensor'
- Image tensor from which to extract feature maps
2. image_shape => 'tuple'
- Original shape(height, width, depth) of image
"""
image_array = cv2.imread(image_path)
image_shape = image_array.shape
image_array = cv2.resize(image_array, image_input_size[:2]) / lightness_max
image_tensor = tf.convert_to_tensor(image_array, dtype=tf.float32)
return (image_tensor,
image_shape)
def generate_anchors(image_shape,
image_input_size,
feature_map_size,
anchor_size_per_feature,
anchor_aspect_ratio_per_feature,
number_of_anchors_per_feature,
shorter_side_scale,
number_of_features):
"""
Generate anchors projected on image_input_size from original image_shape
Arguments)
1. image_shape => 'tuple'
- Original shape(height, width, depth) of image
2. image_input_size => 'tuple'
- Fixed shape when input image to model
3. feature_map_size => 'tuple'
- Extracted feature map shape from image by backbone
4. anchor_size_per_feature => 'list'
- Anchor area defined
5. anchor_aspect_ratio_per_feature => 'list'
- Anchor width-height ratio defined
6. number_of_anchors_per_feature => 'int'
- Number of anchors corresponding to a feature
7. shorter_side_scale => 'int'
- Fix shorter side scale when generate anchors
8. number_of_features => 'int'
- Number of features in a feature map
Returns)
1. anchors => 'tensorflow.python.framework.ops.EagerTensor'
- Generated anchors in input image
"""
if (image_shape[0] < image_shape[1]):
height = float(shorter_side_scale)
width = image_shape[1] / image_shape[0] * shorter_side_scale
else:
height = image_shape[0] / image_shape[1] * shorter_side_scale
width = float(shorter_side_scale)
stride_x = image_input_size[1] / feature_map_size[1]
stride_y = image_input_size[0] / feature_map_size[0]
centered_x = ((tf.cast(tf.range(feature_map_size[1]), dtype=tf.float32)
+ 0.5) * stride_x)
centered_y = ((tf.cast(tf.range(feature_map_size[0]), dtype=tf.float32)
+ 0.5) * stride_y)
mesh_x, mesh_y = tf.meshgrid(centered_x, centered_y)
mesh_x = tf.reshape(mesh_x, (-1,))
mesh_y = tf.reshape(mesh_y, (-1,))
tile_coords = tf.stack([mesh_x, mesh_y], -1)
coords = tf.reshape(tf.tile(tile_coords,
[1, number_of_anchors_per_feature]),
(number_of_features * number_of_anchors_per_feature, 2))
tile_anchors_shape = []
for area in anchor_size_per_feature:
for ratio in anchor_aspect_ratio_per_feature:
anchor_width = math.sqrt(area / ratio)
anchor_height = anchor_width * ratio
anchor_width *= image_input_size[1] / width
anchor_height *= image_input_size[0] / height
tile_anchors_shape.append([anchor_width, anchor_height])
tile_anchors_shape = tf.convert_to_tensor(tile_anchors_shape,
dtype=tf.float32)
anchors_shape = tf.tile(tile_anchors_shape, [number_of_features, 1])
anchors = tf.concat([coords, anchors_shape], -1)
return anchors
def load_pascal_voc_faster_rcnn_dataset(images_path,
metadata_path,
anchor_size_per_feature,
anchor_aspect_ratio_per_feature,
number_of_anchors_per_feature,
shorter_side_scale,
image_input_size,
feature_map_size,
products_config):
"""
Load PascalVOC2007 dataset for training Faster-RCNN object detection Model
Arguments)
1. images_path => 'str'
- image file path in dataset
2. metadata_path => 'str'
- *.xml file path containing metadata
3. anchor_size_per_feature => 'list'
- Anchor area defined
4. anchor_aspect_ratio_per_feature => 'list'
- Anchor width-height ratio defined
5. number_of_anchors_per_feature => 'int'
- Number of anchors corresponding to a feature
6. shorter_side_scale => 'int'
- Fix shorter side scale when generate anchors
7. image_input_size => 'tuple'
- Fixed shape when input image to model
8. feature_map_size => 'tuple'
- Extracted feature map shape from image by backbone
9. products_config => 'configparser.ConfigParser'
- Parser that save products generated during processing
Returns)
1. images_list => 'list'
- Images list parsed from dataset
2. object_dict => 'dict'
- Object labels information, {'background': 0, ...}
3. anchors_list => 'list'
- Anchors list generated from images list
4. ground_truth_bboxes_list => 'list'
- Ground truth bounding box list for all images list
5. ground_truth_labels_list => 'list'
- Ground truth object labels list for all images list
6. number_of_objects => 'int'
- Number of objects to predict
7. products_config => 'configparser.ConfigParser'
- Parser that save products generated during processing
"""
def ground_truth_parser(root_tag,
object_dict,
object_label,
image_input_size,
image_shape):
"""
Parse ground truth data from *.xml file
Arguments)
1. root_tag => 'xml.etree.ElementTree.Element'
- Data(*.xml) include ground truth information
2. object_dict => 'dict'
- Object labels information, {'background': 0, ...}
3. object_label => 'int'
- Object label max number in current
4. image_input_size => 'tuple'
- Fixed shape when input image to model
5. image_shape => 'tuple'
- Original shape(height, width, depth) of image
Returns)
1. ground_truth_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Ground truth bounding boxes in an image
2. ground_truth_labels => 'tensorflow.python.framework.ops.EagerTensor'
- Ground truth labels in an image
3. object_dict => 'dict'
- Object labels information, {'background': 0, ...}
"""
ground_truth_bboxes = []
ground_truth_labels = []
for object_tag in root_tag.findall('object'):
object_name = object_tag.find('name').text
if (object_dict.get(object_name) == None):
object_dict[object_name] = object_label
object_label += 1
width_multiplier = image_input_size[1] / image_shape[1]
height_multiplier = image_input_size[0] / image_shape[0]
xmin_g = int(object_tag.find("bndbox/xmin").text) * width_multiplier
ymin_g = int(object_tag.find("bndbox/ymin").text) * height_multiplier
xmax_g = int(object_tag.find("bndbox/xmax").text) * width_multiplier
ymax_g = int(object_tag.find("bndbox/ymax").text) * height_multiplier
x_g = (xmin_g + xmax_g) / 2
y_g = (ymin_g + ymax_g) / 2
w_g = xmax_g - xmin_g
h_g = ymax_g - ymin_g
ground_truth_bboxes.append([x_g, y_g, w_g, h_g])
ground_truth_labels.append(object_dict[object_name])
ground_truth_bboxes = tf.convert_to_tensor(ground_truth_bboxes,
dtype=tf.float32)
ground_truth_labels = tf.convert_to_tensor(ground_truth_labels,
dtype=tf.int32)
return (ground_truth_bboxes,
ground_truth_labels,
object_dict)
tqdm_bar_format = '{percentage:3.0f}%|{bar:30}{r_bar}'
object_dict = {'background': 0}; object_label = 1
images_list = []
anchors_list = []
ground_truth_bboxes_list = []
ground_truth_labels_list = []
print('Load Data...')
metadataset = glob(metadata_path + '*.xml')
number_of_features = feature_map_size[0] * feature_map_size[1]
products_config['variables']['number_of_data'] = str(len(metadataset))
products_config['variables']['number_of_features'] = str(number_of_features)
for metadata_file in tqdm(metadataset, bar_format=tqdm_bar_format):
tree = parse(metadata_file)
root_tag = tree.getroot()
image_path = images_path + root_tag.find('filename').text
(image_tensor, image_shape) = get_input_image_and_original_shape(
image_path, image_input_size)
images_list.append(image_tensor)
anchors = generate_anchors(image_shape, image_input_size,
feature_map_size, anchor_size_per_feature,
anchor_aspect_ratio_per_feature, number_of_anchors_per_feature,
shorter_side_scale, number_of_features)
anchors_list.append(anchors)
(ground_truth_bboxes, ground_truth_labels, object_dict) = \
ground_truth_parser(root_tag, object_dict, object_label,
image_input_size, image_shape)
ground_truth_bboxes_list.append(ground_truth_bboxes)
ground_truth_labels_list.append(ground_truth_labels)
CRLF()
number_of_objects = len(object_dict) - 1 # Omit backgound
object_list = []
object_color_list = []
for object_name in object_dict:
object_list.append(object_name)
object_color_list.append((random.randint(0, lightness_max),
random.randint(0, lightness_max), random.randint(0, lightness_max)))
products_config['variables']['object_list'] = str(object_list)
products_config['variables']['object_color_list'] = str(object_color_list)
products_config['variables']['number_of_objects'] = str(number_of_objects)
return (images_list,
object_dict,
anchors_list,
ground_truth_bboxes_list,
ground_truth_labels_list,
number_of_objects,
products_config)
def load_train_dataset(products_file,
train_dataset_file):
"""
Load data from file saved
Arguments)
1. products_file => 'str'
- Product filename('products.ini')
2. train_dataset_file => 'str'
- Dataset filename('train_dataset.pickle')
Returns)
1. train_dataset => 'dict'
- Dataset for models training
2. number_of_objects => 'int'
- Number of objects to predict
3. products_config => 'configparser.ConfigParser'
- Parser that save products generated during processing
"""
products_config = ConfigParser()
products_config.read(products_file)
number_of_objects = products_config.getint('variables',
'number_of_objects')
with open(train_dataset_file, 'rb') as f:
train_dataset = pickle.load(f)
return (train_dataset,
number_of_objects,
products_config)
def make_cache(products_file,
train_dataset_file,
pool_size,
images_path,
metadata_path,
anchor_size_per_feature,
anchor_aspect_ratio_per_feature,
number_of_anchors_per_feature,
shorter_side_scale,
image_input_size,
feature_map_size):
"""
Make cache file for loading time save
Arguments)
1. products_file => 'str'
- Product filename('products.ini')
2. train_dataset_file => 'str'
- Dataset filename('train_dataset.pickle')
3. pool_size => 'tuple'
- Return size of pooled feature map after operate ROIPooling
4. images_path => 'str'
- image file path in dataset
5. metadata_path => 'str'
- *.xml file path containing metadata
6. anchor_size_per_feature => 'list'
- Anchor area defined
7. anchor_aspect_ratio_per_feature => 'list'
- Anchor width-height ratio defined
8. number_of_anchors_per_feature => 'int'
- Number of anchors corresponding to a feature
9. shorter_side_scale => 'int'
- Fix shorter side scale when generate anchors
10. image_input_size => 'tuple'
- Fixed shape when input image to model
11. feature_map_size => 'tuple'
- Extracted feature map shape from image by backbone
Returns)
1. train_dataset => 'dict'
- Dataset for models training
2. number_of_objects => 'int'
- Number of objects to predict
3. products_config => 'configparser.ConfigParser'
- Parser that save products generated during processing
"""
def save_products(products_config,
products_file):
"""
Save variables producted
Arguments)
1. products_config => 'configparser.ConfigParser'
- Parser that save products generated during processing
2. products_file => 'str'
- Product filename('products.ini')
"""
with open(products_file, 'a') as f:
products_config.write(f)
def save_train_dataset(train_dataset,
train_dataset_file):
"""
Save train dataset loaded
Arguments)
1. train_dataset => 'dict'
- Dataset for models training
2. train_dataset_file => 'str'
- Dataset filename('train_dataset.pickle')
"""
with open(train_dataset_file, 'wb') as f:
pickle.dump(train_dataset, f, pickle.HIGHEST_PROTOCOL)
if (os.path.isfile(products_file)):
os.remove(products_file)
if (os.path.isfile(train_dataset_file)):
os.remove(train_dataset_file)
products_config = ConfigParser()
products_config['variables'] = {}
products_config['variables']['number_of_anchors_per_feature'] = \
str(number_of_anchors_per_feature)
products_config['variables']['feature_map_size'] = str(feature_map_size)
products_config['variables']['pool_size'] = str(pool_size)
(images_list, object_dict, anchors_list, ground_truth_bboxes_list,
ground_truth_labels_list, number_of_objects, products_config) = \
load_pascal_voc_faster_rcnn_dataset(images_path, metadata_path,
anchor_size_per_feature, anchor_aspect_ratio_per_feature,
number_of_anchors_per_feature, shorter_side_scale,
image_input_size, feature_map_size, products_config)
train_dataset = {'images_list': images_list,
'anchors_list': anchors_list,
'ground_truth_bboxes_list': ground_truth_bboxes_list,
'ground_truth_labels_list': ground_truth_labels_list}
save_products(products_config, products_file)
save_train_dataset(train_dataset, train_dataset_file)
return (train_dataset,
number_of_objects,
products_config)
def shuffle_list(*args):
"""
Apply the same shuffle to all list arguments
Arguments)
1. *args
- Lists with same length
Returns)
2. zip(*l)
- Shuffled lists
"""
l = list(zip(*args))
random.shuffle(l)
return zip(*l)
def convert_centered_to_square_and_split(centered_bboxes):
"""
Convert and split centered coordinates to square coordinates
Arguments)
1. centered_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Coordinates defined (x, y, w, h) , where x, y represent the centered
Returns)
1. bboxes_coordinates => 'tuple'
- Returns the coordinates defined as a tensor in tuple.
"""
x, y, w, h = tf.split(centered_bboxes, 4, -1)
xmin = x - 0.5 * w
ymin = y - 0.5 * h
xmax = x + 0.5 * w
ymax = y + 0.5 * h
bboxes_coordinates = (xmin, ymin, xmax, ymax)
return bboxes_coordinates
def convert_centered_to_square(centered_bboxes):
"""
Convert centered coordinates to square coordinates
Arguments)
1. centered_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Coordinates defined (x, y, w, h)
Returns)
1. square_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Coordinates defined (xmin, ymin, xmax, ymax)
"""
square_coordinates = convert_centered_to_square_and_split(centered_bboxes)
square_bboxes = tf.concat(square_coordinates, -1)
return square_bboxes
def convert_square_to_centered(square_bboxes):
"""
Convert square coordinates to centered coordinates
Arguments)
1. square_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Coordinates defined (xmin, ymin, xmax, ymax)
Returns)
1. centered_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Coordinates defined (x, y, w, h)
"""
xy_min, xy_max = tf.split(square_bboxes, 2, -1)
xy = (xy_min + xy_max) / 2
wh = xy_max - xy_min
centered_bboxes = tf.concat([xy, wh], -1)
return centered_bboxes
def get_iou_map(centered_bboxes_1,
centered_bboxes_2):
"""
Operate iou map from two centered bounding boxes (example: anchors and
ground truth bboxes)
!!Caution!! => Batch process operation not applied yet...
Arguments)
1. centered_bboxes_1 => 'tensorflow.python.framework.ops.EagerTensor'
- Centered bounding boxes (Use current bounding boxes you have)
2. centered_bboxes_2 => 'tensorflow.python.framework.ops.EagerTensor'
- Centered bounding boxes (Use ground truth bounding boxes)
Returns)
1. iou_map => 'tensorflow.python.framework.ops.EagerTensor'
- IoU map (matrix) between two bounding boxes
"""
def intersection_area_map(square_bboxes_1,
square_bboxes_2):
"""
Operate intersection area map from two square bounding boxes (example:
anchors and ground truth bboxes)
Arguments)
1. square_bboxes_1 => 'tensorflow.python.framework.ops.EagerTensor'
- Square bounding boxes (Use current bounding boxes you have)
2. square_bboxes_2 => 'tensorflow.python.framework.ops.EagerTensor'
- Square bounding boxes (Use ground truth bounding boxes)
Returns)
1. area_i => 'tensorflow.python.framework.ops.EagerTensor'
- Intersection area map (matrix) between two bounding boxes
"""
xmin_1, ymin_1, xmax_1, ymax_1 = square_bboxes_1
xmin_2, ymin_2, xmax_2, ymax_2 = square_bboxes_2
xmin_i = tf.maximum(xmin_1, tf.transpose(xmin_2, [0, 2, 1]))
ymin_i = tf.maximum(ymin_1, tf.transpose(ymin_2, [0, 2, 1]))
xmax_i = tf.minimum(xmax_1, tf.transpose(xmax_2, [0, 2, 1]))
ymax_i = tf.minimum(ymax_1, tf.transpose(ymax_2, [0, 2, 1]))
area_i = tf.maximum(xmax_i - xmin_i, 0) * tf.maximum(ymax_i - ymin_i, 0)
return area_i
def union_area_map(area_1,
area_2,
area_i):
"""
Operate union area map from two square bounding boxes (example: anchors
and ground truth bboxes)
Arguments)
1. area_1 => 'tensorflow.python.framework.ops.EagerTensor'
- Bounding boxes (Current bounding boxes) area map
2. area_2 => 'tensorflow.python.framework.ops.EagerTensor'
- Bounding boxes (Ground truth bounding boxes) area map
3. area_i => 'tensorflow.python.framework.ops.EagerTensor'
- Intersection area map between two bounding boxes
Returns)
1. area_u => 'tensorflow.python.framework.ops.EagerTensor'
- Union area map (matrix) between two bounding boxes
"""
area_u = (tf.expand_dims(area_1, -1) + tf.expand_dims(area_2, 1)
- area_i)
return area_u
square_bboxes_1 = convert_centered_to_square_and_split(centered_bboxes_1)
x_1, y_1, w_1, h_1 = tf.split(centered_bboxes_1, number_of_reg, -1)
square_bboxes_2 = convert_centered_to_square_and_split(centered_bboxes_2)
x_2, y_2, w_2, h_2 = tf.split(centered_bboxes_2, number_of_reg, -1)
area_1 = tf.squeeze(w_1 * h_1, axis=-1)
area_2 = tf.squeeze(w_2 * h_2, axis=-1)
area_i = intersection_area_map(square_bboxes_1, square_bboxes_2)
area_u = union_area_map(area_1, area_2, area_i)
iou_map = area_i / area_u
return iou_map
def centered_to_regression_labels(max_iou_ground_truth_bboxes,
current_bboxes):
"""
Encoding bounding boxes for operating regression loss
Arguments)
1. max_iou_ground_truth_bboxes => 'tensorflow.python.framework.ops.
EagerTensor'
- Label IoU max ground truth bounding boxes
2. current_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Bounding boxes you have (example: anchors, decoded regression predict from
region proposal network)
Returns)
1. reg_label => 'tensorflow.python.framework.ops.EagerTensor'
- Regression values of bounding boxes
"""
xy_g, wh_g = tf.split(max_iou_ground_truth_bboxes, 2, -1)
xy_c, wh_c = tf.split(current_bboxes, 2, -1)
xy_reg = (xy_g - xy_c) / wh_c
wh_reg = tf.math.log(wh_g / wh_c)
reg_label = tf.concat([xy_reg, wh_reg], 2)
return reg_label
def regression_to_centered_predict(regression_predict,
current_bboxes):
"""
Decoding bounding boxes
Arguments)
1. regression_predict => 'tensorflow.python.framework.ops.EagerTensor'
- Regression bounding boxes from model (example: region proposal network)
2. current_bboxes => 'tensorflow.python.framework.ops.EagerTensor'
- Bounding boxes you have (example: anchors, decoded regression predict from
region proposal network)
Returns)
1. centered_bboxes_predict => 'tensorflow.python.framework.ops.EagerTensor'
- Centered coordinates bounding boxes
"""
xy_offset, wh_offset = tf.split(regression_predict, 2, -1)
xy_c, wh_c = tf.split(current_bboxes, 2, -1)
xy_p = xy_offset * wh_c + xy_c
wh_p = tf.math.exp(wh_offset) * wh_c
centered_bboxes_predict = tf.concat([xy_p, wh_p], -1)
return centered_bboxes_predict
def print_step_message(step,
steps,
step_start,
loss,
progress_bar_length):
"""
Print message during a step
Arguments)
1. step => 'int'
- Current step in epoch
2. steps => 'int'
- Total step in epoch
3. step_start => 'float'
- Step start time
4. loss => 'tensorflow.python.framework.ops.EagerTensor'
- Loss value calculated
5. progress_bar_length => 'int'
- Length when Visualize progress bar
"""
terminal_width, _ = os.get_terminal_size()
progress = int(progress_bar_length * (step + 1) / steps)
progress_bar = (progress * "●").ljust(progress_bar_length, "○")
step_runtime = time() - step_start
step_message = \
"\rtrain: %4d/%4d[%s] - multi_task_loss: %.4e - time: %.4fsec" \
% (step + 1, steps, progress_bar, loss, step_runtime)
print(step_message.ljust(terminal_width, " "), end="")
def print_epoch_message(epoch_start,
train_loss_list,
valid_loss_list):
"""
Print message during an epoch
Arguments)
1. epoch_start => 'float'
- Epoch start time
2. train_loss_list => 'list'
- List of train loss values
3. valid_loss_list => 'list'
- List of validation loss values
"""
terminal_width, _ = os.get_terminal_size()
epoch_runtime = time() - epoch_start
epoch_message = \
"\rtrain_loss_mean: %.4e - valid_loss_mean: %.4e - time: %.4fsec" \
% (tf.reduce_mean(train_loss_list), tf.reduce_mean(valid_loss_list),
epoch_runtime)
print(epoch_message.ljust(terminal_width, " "))
def save_weights(epoch,
save_cycle,
*ckpt_managers):
"""
Save model's weights per cycle epoch
Arguments)
1. epoch => 'int'
- Current epoch
2. save_cycle => 'int'
- Cycle that save model
3. *ckpt_managers
- Checkpoint managers of models
"""
if ((epoch % save_cycle) == (save_cycle - 1)):
print("Weights Saved!!")
for ckpt_manager in ckpt_managers:
ckpt_manager.save()
def train_rpn(train_dataset,
products_config,
epochs,
train_valid_split_rate,
valid_steps_max,
backbone_model,
proposal_model,
backbone_trainable,
sparse_categorical_cross_entropy,
huber,
rpn_loss_lambda,
stochastic_gradient_descent,
number_of_sampled_region,
progress_bar_length,
save_cycle,
*ckpt_managers):
"""
Train region proposal network
Arguments)
1. train_dataset => 'dict'
- Dataset for models training
2. products_config => 'configparser.ConfigParser'
- Parser that save products generated during processing
3. epochs => 'int'
- Total epochs when training
4. train_valid_split_rate => 'float'
- Split rate between train and validation of dataset when training
5. valid_steps_max => 'int'
- Max of validation dataset when validate during training
6. backbone_model => 'custom.models.BackBone'
- Feature extract model for image
7. proposal_model => 'custom.models.Proposal'
- Region proposal using feature map
8. backbone_trainable => 'bool'
- Whether to train the backbone network
9. sparse_categorical_cross_entropy => 'keras.losses.
SparseCategoricalCrossentropy'
- Classification loss function
10. huber => 'keras.losses.Huber'
- Regression loss function
11. rpn_loss_lambda => 'int'
- Balancing parameter when calculate multi task loss between classification
loss and regression loss
12. stochastic_gradient_descent => 'keras.optimizer_v2.gradient_descent.SGD'
- Optimize function
13. number_of_sampled_region => 'int'
- Total sampling number of region for classification training
14. progress_bar_length => 'int'
- Length when Visualize progress bar
15. save_cycle => 'int'
- Cycle that save model
16. *ckpt_managers
- Checkpoint managers of models
"""
def rpn_data_generator(images_list,
anchors_list,
ground_truth_bboxes_list,
number_of_anchors_per_feature,
number_of_features,
number_of_sampled_region):
"""