-
Notifications
You must be signed in to change notification settings - Fork 72
/
utils.py
3223 lines (2538 loc) · 128 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
"""
Mask R-CNN
Common utility functions and classes.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import sys
import os
import cv2
import math
import random
import numpy as np
import tensorflow as tf
import scipy.misc
import skimage.color
import _pickle as cPickle
from ctypes import *
import copy
import ICP
import glob
import time
from aligning import estimateSimilarityTransform
sys.path.append('./cocoapi/PythonAPI')
from pycocotools.cocoeval import COCOeval
from pycocotools import mask as maskUtils
import matplotlib.pyplot as plt
############################################################
# Bounding Boxes
############################################################
def extract_bboxes(mask):
"""Compute bounding boxes from masks.
mask: [height, width, num_instances]. Mask pixels are either 1 or 0.
Returns: bbox array [num_instances, (y1, x1, y2, x2)].
"""
boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32)
for i in range(mask.shape[-1]):
m = mask[:, :, i]
# Bounding box.
horizontal_indicies = np.where(np.any(m, axis=0))[0]
vertical_indicies = np.where(np.any(m, axis=1))[0]
if horizontal_indicies.shape[0]:
x1, x2 = horizontal_indicies[[0, -1]]
y1, y2 = vertical_indicies[[0, -1]]
# x2 and y2 should not be part of the box. Increment by 1.
x2 += 1
y2 += 1
else:
# No mask for this instance. Might happen due to
# resizing or cropping. Set bbox to zeros
x1, x2, y1, y2 = 0, 0, 0, 0
boxes[i] = np.array([y1, x1, y2, x2])
return boxes.astype(np.int32)
def compute_iou(box, boxes, box_area, boxes_area):
"""Calculates IoU of the given box with the array of the given boxes.
box: 1D vector [y1, x1, y2, x2]
boxes: [boxes_count, (y1, x1, y2, x2)]
box_area: float. the area of 'box'
boxes_area: array of length boxes_count.
Note: the areas are passed in rather than calculated here for
efficiency. Calculate once in the caller to avoid duplicate work.
"""
# Calculate intersection areas
y1 = np.maximum(box[0], boxes[:, 0])
y2 = np.minimum(box[2], boxes[:, 2])
x1 = np.maximum(box[1], boxes[:, 1])
x2 = np.minimum(box[3], boxes[:, 3])
intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)
union = box_area + boxes_area[:] - intersection[:]
iou = intersection / union
return iou
def compute_overlaps(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
For better performance, pass the largest set first and the smaller second.
"""
# Areas of anchors and GT boxes
area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
# Compute overlaps to generate matrix [boxes1 count, boxes2 count]
# Each cell contains the IoU value.
overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0]))
for i in range(overlaps.shape[1]):
box2 = boxes2[i]
overlaps[:, i] = compute_iou(box2, boxes1, area2[i], area1)
return overlaps
def compute_overlaps_masks(masks1, masks2):
'''Computes IoU overlaps between two sets of masks.
masks1, masks2: [Height, Width, instances]
'''
# flatten masks
masks1 = np.reshape(masks1 > .5, (-1, masks1.shape[-1])).astype(np.float32)
masks2 = np.reshape(masks2 > .5, (-1, masks2.shape[-1])).astype(np.float32)
area1 = np.sum(masks1, axis=0)
area2 = np.sum(masks2, axis=0)
# intersections and union
intersections = np.dot(masks1.T, masks2)
union = area1[:, None] + area2[None, :] - intersections
overlaps = intersections / union
return overlaps
def compute_mean_l1_coord_diff(mask1, mask2, coord1, coord2, synset, cls_id):
'''Computes IoU overlaps between two sets of masks.
mask1, mask2: [Height, Width]
coord1, coord2: [Height, Width, 3]
'''
# flatten masks
num_pixels = mask1.shape[0] * mask1.shape[1]
mask1 = np.reshape(mask1 > .5, (-1)).astype(np.float32)
mask2 = np.reshape(mask2 > .5, (-1)).astype(np.float32)
coord1 = np.reshape(coord1, (-1, 3)).astype(np.float32)
coord2 = np.reshape(coord2, (-1, 3)).astype(np.float32)
# intersections and union
intersections = np.logical_and(mask1, mask2)
num_pixel_intersection = len(np.where(intersections)[0])
pts1 = coord1[intersections, :].transpose() - 0.5
pts2 = coord2[intersections, :].transpose() - 0.5
def rotation_y_matrix(theta):
rotation_matrix = \
np.array([ np.cos(theta), 0, np.sin(theta),
0, 1, 0,
-np.sin(theta), 0, np.cos(theta)])
rotation_matrix = np.reshape(rotation_matrix, (3, 3))
return rotation_matrix
if synset[cls_id] in ['bottle', 'bowl', 'can']:
M = 20
pts1_symmetry = np.zeros(pts1.shape+(M,)) ## shape: (3, N, 6)
for i in range(M):
rotated_pts1 = rotation_y_matrix(float(i)*np.float32(2*math.pi/M)) @ pts1
pts1_symmetry[:, :, i] = rotated_pts1
pts2_reshape = pts2.reshape([3, -1, 1])
mean_dists = np.mean(np.linalg.norm(pts1_symmetry - pts2_reshape, axis=0), axis=0)
mean_dist = np.amin(mean_dists)
elif synset[cls_id] in ['phone']:
pts1_symmetry = np.zeros(pts1.shape+(2,))
for i in range(2):
rotated_pts1 = rotation_y_matrix(float(i)*np.float32(2*math.pi/2)) @ pts1
#print(rotated_pts1)
pts1_symmetry[:, :, i] = rotated_pts1
pts2_reshape = pts2.reshape([3, -1, 1])
mean_dists = np.mean(np.linalg.norm(pts1_symmetry - pts2_reshape, axis=0), axis=0)
mean_dist = np.amin(mean_dists)
else:
#print(synset[cls_id])
diff = pts1 - pts2
dist = np.linalg.norm(diff, axis=0)
assert dist.shape[0] == num_pixel_intersection
mean_dist = np.mean(dist)
mean_l1_coord_diff = mean_dist
#print(mean_l1_coord_diff, pts1.shape[0])
return mean_l1_coord_diff
def compute_3d_iou(bbox_3d_1, bbox_3d_2, handle_visibility, class_name_1, class_name_2):
'''Computes IoU overlaps between two 3d bboxes.
bbox_3d_1, bbox_3d_1: [3, 8]
'''
# flatten masks
def asymmetric_3d_iou(bbox_3d_1, bbox_3d_2):
bbox_1_max = np.amax(bbox_3d_1, axis=0)
bbox_1_min = np.amin(bbox_3d_1, axis=0)
bbox_2_max = np.amax(bbox_3d_2, axis=0)
bbox_2_min = np.amin(bbox_3d_2, axis=0)
overlap_min = np.maximum(bbox_1_min, bbox_2_min)
overlap_max = np.minimum(bbox_1_max, bbox_2_max)
# intersections and union
if np.amin(overlap_max - overlap_min) <0:
intersections = 0
else:
intersections = np.prod(overlap_max - overlap_min)
union = np.prod(bbox_1_max - bbox_1_min) + np.prod(bbox_2_max - bbox_2_min) - intersections
overlaps = intersections / union
return overlaps
if bbox_3d_1 is None or bbox_3d_2 is None:
return -1
symmetry_flag = False
if class_name_1 in ['bottle', 'bowl', 'can'] and class_name_1 == class_name_2:
symmetry_flag = True
if class_name_1 == 'mug' and class_name_1 == class_name_2 and handle_visibility==0:
symmetry_flag = True
if symmetry_flag:
print('*'*10)
n = 20
theta = 2*math.pi/n
y_rotation_matrix = np.array([[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]])
max_iou = 0
for i in range(n):
bbox_center = np.mean(bbox_3d_1, -1, keepdims=True)
bbox_3d_1 = y_rotation_matrix @ (bbox_3d_1 - bbox_center) + bbox_center
max_iou = max(max_iou, asymmetric_3d_iou(bbox_3d_1, bbox_3d_2))
return max_iou
else:
return asymmetric_3d_iou(bbox_3d_1, bbox_3d_2)
def compute_3d_iou_new(RT_1, RT_2, scales_1, scales_2, handle_visibility, class_name_1, class_name_2):
'''Computes IoU overlaps between two 3d bboxes.
bbox_3d_1, bbox_3d_1: [3, 8]
'''
# flatten masks
def asymmetric_3d_iou(RT_1, RT_2, scales_1, scales_2):
noc_cube_1 = get_3d_bbox(scales_1, 0)
bbox_3d_1 = transform_coordinates_3d(noc_cube_1, RT_1)
noc_cube_2 = get_3d_bbox(scales_2, 0)
bbox_3d_2 = transform_coordinates_3d(noc_cube_2, RT_2)
bbox_1_max = np.amax(bbox_3d_1, axis=0)
bbox_1_min = np.amin(bbox_3d_1, axis=0)
bbox_2_max = np.amax(bbox_3d_2, axis=0)
bbox_2_min = np.amin(bbox_3d_2, axis=0)
overlap_min = np.maximum(bbox_1_min, bbox_2_min)
overlap_max = np.minimum(bbox_1_max, bbox_2_max)
# intersections and union
if np.amin(overlap_max - overlap_min) <0:
intersections = 0
else:
intersections = np.prod(overlap_max - overlap_min)
union = np.prod(bbox_1_max - bbox_1_min) + np.prod(bbox_2_max - bbox_2_min) - intersections
overlaps = intersections / union
return overlaps
if RT_1 is None or RT_2 is None:
return -1
symmetry_flag = False
if (class_name_1 in ['bottle', 'bowl', 'can'] and class_name_1 == class_name_2) or (class_name_1 == 'mug' and class_name_1 == class_name_2 and handle_visibility==0):
print('*'*10)
noc_cube_1 = get_3d_bbox(scales_1, 0)
noc_cube_2 = get_3d_bbox(scales_2, 0)
bbox_3d_2 = transform_coordinates_3d(noc_cube_2, RT_2)
def y_rotation_matrix(theta):
return np.array([[np.cos(theta), 0, np.sin(theta), 0],
[0, 1, 0 , 0],
[-np.sin(theta), 0, np.cos(theta), 0],
[0, 0, 0 , 1]])
n = 20
max_iou = 0
for i in range(n):
rotated_RT_1 = RT_1@y_rotation_matrix(2*math.pi*i/float(n))
max_iou = max(max_iou,
asymmetric_3d_iou(rotated_RT_1, RT_2, scales_1, scales_2))
else:
max_iou = asymmetric_3d_iou(RT_1, RT_2, scales_1, scales_2)
return max_iou
def compute_RT_distances(RT_1, RT_2):
'''
:param RT_1: [4, 4]. homogeneous affine transformation
:param RT_2: [4, 4]. homogeneous affine transformation
:return: theta: angle difference of R in degree, shift: l2 difference of T in centimeter
'''
#print(RT_1[3, :], RT_2[3, :])
## make sure the last row is [0, 0, 0, 1]
if RT_1 is None or RT_2 is None:
return -1
try:
assert np.array_equal(RT_1[3, :], RT_2[3, :])
assert np.array_equal(RT_1[3, :], np.array([0, 0, 0, 1]))
except AssertionError:
print(RT_1[3, :], RT_2[3, :])
R1 = RT_1[:3, :3]/np.cbrt(np.linalg.det(RT_1[:3, :3]))
T1 = RT_1[:3, 3]
R2 = RT_2[:3, :3]/np.cbrt(np.linalg.det(RT_2[:3, :3]))
T2 = RT_2[:3, 3]
R = R1 @ R2.transpose()
theta = np.arccos((np.trace(R) - 1)/2) * 180/np.pi
shift = np.linalg.norm(T1-T2) * 100
# print(theta, shift)
if theta < 5 and shift < 5:
return 10 - theta - shift
else:
return -1
def compute_RT_degree_cm_symmetry(RT_1, RT_2, class_id, handle_visibility, synset_names):
'''
:param RT_1: [4, 4]. homogeneous affine transformation
:param RT_2: [4, 4]. homogeneous affine transformation
:return: theta: angle difference of R in degree, shift: l2 difference of T in centimeter
synset_names = ['BG', # 0
'bottle', # 1
'bowl', # 2
'camera', # 3
'can', # 4
'cap', # 5
'phone', # 6
'monitor', # 7
'laptop', # 8
'mug' # 9
]
synset_names = ['BG', # 0
'bottle', # 1
'bowl', # 2
'camera', # 3
'can', # 4
'laptop', # 5
'mug' # 6
]
'''
## make sure the last row is [0, 0, 0, 1]
if RT_1 is None or RT_2 is None:
return -1
try:
assert np.array_equal(RT_1[3, :], RT_2[3, :])
assert np.array_equal(RT_1[3, :], np.array([0, 0, 0, 1]))
except AssertionError:
print(RT_1[3, :], RT_2[3, :])
exit()
R1 = RT_1[:3, :3] / np.cbrt(np.linalg.det(RT_1[:3, :3]))
T1 = RT_1[:3, 3]
R2 = RT_2[:3, :3] / np.cbrt(np.linalg.det(RT_2[:3, :3]))
T2 = RT_2[:3, 3]
# try:
# assert np.abs(np.linalg.det(R1) - 1) < 0.01
# assert np.abs(np.linalg.det(R2) - 1) < 0.01
# except AssertionError:
# print(np.linalg.det(R1), np.linalg.det(R2))
if synset_names[class_id] in ['bottle', 'can', 'bowl']: ## symmetric when rotating around y-axis
y = np.array([0, 1, 0])
y1 = R1 @ y
y2 = R2 @ y
theta = np.arccos(y1.dot(y2) / (np.linalg.norm(y1) * np.linalg.norm(y2)))
elif synset_names[class_id] == 'mug' and handle_visibility==0: ## symmetric when rotating around y-axis
y = np.array([0, 1, 0])
y1 = R1 @ y
y2 = R2 @ y
theta = np.arccos(y1.dot(y2) / (np.linalg.norm(y1) * np.linalg.norm(y2)))
elif synset_names[class_id] in ['phone', 'eggbox', 'glue']:
y_180_RT = np.diag([-1.0, 1.0, -1.0])
R = R1 @ R2.transpose()
R_rot = R1 @ y_180_RT @ R2.transpose()
theta = min(np.arccos((np.trace(R) - 1) / 2),
np.arccos((np.trace(R_rot) - 1) / 2))
else:
R = R1 @ R2.transpose()
theta = np.arccos((np.trace(R) - 1) / 2)
theta *= 180 / np.pi
shift = np.linalg.norm(T1 - T2) * 100
result = np.array([theta, shift])
return result
def compute_RT_projection_2d_symmetry(RT_1, RT_2, class_id, handle_visibility, mesh_vertices, intrinsics, synset_names, num_rotation=20):
'''
:param RT_1: [4, 4]. homogeneous affine transformation
:param RT_2: [4, 4]. homogeneous affine transformation
:param vertices: [3, N].
:param intrinsics: [4, 4]
:return: mean 2d projection distance in pixel
synset_names = ['BG', # 0
'bottle', # 1
'bowl', # 2
'camera', # 3
'can', # 4
'laptop', # 5
'mug' # 6
]
'''
## make sure the last row is [0, 0, 0, 1]
if RT_1 is None or RT_2 is None:
return -1
try:
assert np.array_equal(RT_1[3, :], RT_2[3, :])
assert np.array_equal(RT_1[3, :], np.array([0, 0, 0, 1]))
except AssertionError:
print(RT_1[3, :], RT_2[3, :])
exit()
RT_1[:3, :3] = RT_1[:3, :3]/np.cbrt(np.linalg.det(RT_1[:3, :3]))
R1 = RT_1[:3, :3]
#T1 = RT_1[:3, 3]
RT_2[:3, :3] = RT_2[:3, :3]/np.cbrt(np.linalg.det(RT_2[:3, :3]))
R2 = RT_2[:3, :3]
#T2 = RT_2[:3, 3]
try:
assert np.abs(np.linalg.det(R1) - 1) < 0.01
assert np.abs(np.linalg.det(R2) - 1) < 0.01
except AssertionError:
print(np.linalg.det(R1), np.linalg.det(R2))
# check the vertices are in meter unit
vertices = np.copy(mesh_vertices)/1000
assert np.amax(vertices) < 0.5, np.amax(vertices)
assert np.amax(vertices) > 0, np.amax(vertices)
assert np.amin(vertices) < 0, np.amin(vertices)
assert np.amin(vertices) > -0.5, np.amin(vertices)
assert vertices.shape[0] == 3
num_vertices = vertices.shape[1]
coords_3d_1 = transform_coordinates_3d(vertices, RT_1)
projected_1 = calculate_2d_projections(coords_3d_1, intrinsics)
coords_3d_2 = transform_coordinates_3d(vertices, RT_2)
projected_2 = calculate_2d_projections(coords_3d_2, intrinsics)
# calculate reprojection 2d error
dists = np.linalg.norm(projected_1 - projected_2, axis=1)
assert len(dists) == num_vertices
min_mean_dist = np.mean(dists)
## take care of symmetry categories
# freely rotate around y axis
if (synset_names[class_id] in ['bottle', 'can', 'bowl']) or (synset_names[class_id] == 'mug' and handle_visibility==0):
def y_rotation_matrix(theta):
return np.array([[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]])
for i in range(1, num_rotation):
theta = 2*math.pi*i/float(num_rotation)
coords_3d_2 = transform_coordinates_3d(y_rotation_matrix(theta)@vertices, RT_2)
projected_2 = calculate_2d_projections(coords_3d_2, intrinsics)
dists = np.linalg.norm(projected_1 - projected_2, axis=1)
assert len(dists) == num_vertices
min_mean_dist = min(min_mean_dist, np.mean(dists))
# rotate 180 around y axis
elif synset_names[class_id] in ['phone']:
y_180_RT = np.diag([-1.0, 1.0, -1.0])
coords_3d_2 = transform_coordinates_3d(y_180_RT@vertices, RT_2)
projected_2 = calculate_2d_projections(coords_3d_2, intrinsics)
dists = np.linalg.norm(projected_1 - projected_2, axis=1)
assert len(dists) == num_vertices
min_mean_dist = min(min_mean_dist, np.mean(dists))
# rotate 180 around z axis
elif synset_names[class_id] in ['eggbox', 'glue']:
z_180_RT = np.diag([-1.0, -1.0, 1.0])
coords_3d_2 = transform_coordinates_3d(z_180_RT@vertices, RT_2)
projected_2 = calculate_2d_projections(coords_3d_2, intrinsics)
dists = np.linalg.norm(projected_1 - projected_2, axis=1)
assert len(dists) == num_vertices
min_mean_dist = min(min_mean_dist, np.mean(dists))
else: ## normal asymmetric objects
min_mean_dist = min_mean_dist
return min_mean_dist
def non_max_suppression(boxes, scores, threshold):
"""Performs non-maximum suppression and returns indices of kept boxes.
boxes: [N, (y1, x1, y2, x2)]. Notice that (y2, x2) lays outside the box.
scores: 1-D array of box scores.
threshold: Float. IoU threshold to use for filtering.
"""
assert boxes.shape[0] > 0
if boxes.dtype.kind != "f":
boxes = boxes.astype(np.float32)
# Compute box areas
y1 = boxes[:, 0]
x1 = boxes[:, 1]
y2 = boxes[:, 2]
x2 = boxes[:, 3]
area = (y2 - y1) * (x2 - x1)
# Get indicies of boxes sorted by scores (highest first)
ixs = scores.argsort()[::-1]
pick = []
while len(ixs) > 0:
# Pick top box and add its index to the list
i = ixs[0]
pick.append(i)
# Compute IoU of the picked box with the rest
iou = compute_iou(boxes[i], boxes[ixs[1:]], area[i], area[ixs[1:]])
# Identify boxes with IoU over the threshold. This
# returns indicies into ixs[1:], so add 1 to get
# indicies into ixs.
remove_ixs = np.where(iou > threshold)[0] + 1
# Remove indicies of the picked and overlapped boxes.
ixs = np.delete(ixs, remove_ixs)
ixs = np.delete(ixs, 0)
return np.array(pick, dtype=np.int32)
def apply_box_deltas(boxes, deltas):
"""Applies the given deltas to the given boxes.
boxes: [N, (y1, x1, y2, x2)]. Note that (y2, x2) is outside the box.
deltas: [N, (dy, dx, log(dh), log(dw))]
"""
boxes = boxes.astype(np.float32)
# Convert to y, x, h, w
height = boxes[:, 2] - boxes[:, 0]
width = boxes[:, 3] - boxes[:, 1]
center_y = boxes[:, 0] + 0.5 * height
center_x = boxes[:, 1] + 0.5 * width
# Apply deltas
center_y += deltas[:, 0] * height
center_x += deltas[:, 1] * width
height *= np.exp(deltas[:, 2])
width *= np.exp(deltas[:, 3])
# Convert back to y1, x1, y2, x2
y1 = center_y - 0.5 * height
x1 = center_x - 0.5 * width
y2 = y1 + height
x2 = x1 + width
return np.stack([y1, x1, y2, x2], axis=1)
def box_refinement_graph(box, gt_box):
"""Compute refinement needed to transform box to gt_box.
box and gt_box are [N, (y1, x1, y2, x2)]
"""
box = tf.cast(box, tf.float32)
gt_box = tf.cast(gt_box, tf.float32)
height = box[:, 2] - box[:, 0]
width = box[:, 3] - box[:, 1]
center_y = box[:, 0] + 0.5 * height
center_x = box[:, 1] + 0.5 * width
gt_height = gt_box[:, 2] - gt_box[:, 0]
gt_width = gt_box[:, 3] - gt_box[:, 1]
gt_center_y = gt_box[:, 0] + 0.5 * gt_height
gt_center_x = gt_box[:, 1] + 0.5 * gt_width
dy = (gt_center_y - center_y) / height
dx = (gt_center_x - center_x) / width
dh = tf.log(gt_height / height)
dw = tf.log(gt_width / width)
result = tf.stack([dy, dx, dh, dw], axis=1)
return result
def box_refinement(box, gt_box):
"""Compute refinement needed to transform box to gt_box.
box and gt_box are [N, (y1, x1, y2, x2)]. (y2, x2) is
assumed to be outside the box.
"""
box = box.astype(np.float32)
gt_box = gt_box.astype(np.float32)
height = box[:, 2] - box[:, 0]
width = box[:, 3] - box[:, 1]
center_y = box[:, 0] + 0.5 * height
center_x = box[:, 1] + 0.5 * width
gt_height = gt_box[:, 2] - gt_box[:, 0]
gt_width = gt_box[:, 3] - gt_box[:, 1]
gt_center_y = gt_box[:, 0] + 0.5 * gt_height
gt_center_x = gt_box[:, 1] + 0.5 * gt_width
dy = (gt_center_y - center_y) / height
dx = (gt_center_x - center_x) / width
dh = np.log(gt_height / height)
dw = np.log(gt_width / width)
return np.stack([dy, dx, dh, dw], axis=1)
def get_3d_bbox(scale, shift = 0):
"""
Input:
scale: [3] or scalar
shift: [3] or scalar
Return
bbox_3d: [3, N]
"""
if hasattr(scale, "__iter__"):
bbox_3d = np.array([[scale[0] / 2, +scale[1] / 2, scale[2] / 2],
[scale[0] / 2, +scale[1] / 2, -scale[2] / 2],
[-scale[0] / 2, +scale[1] / 2, scale[2] / 2],
[-scale[0] / 2, +scale[1] / 2, -scale[2] / 2],
[+scale[0] / 2, -scale[1] / 2, scale[2] / 2],
[+scale[0] / 2, -scale[1] / 2, -scale[2] / 2],
[-scale[0] / 2, -scale[1] / 2, scale[2] / 2],
[-scale[0] / 2, -scale[1] / 2, -scale[2] / 2]]) + shift
else:
bbox_3d = np.array([[scale / 2, +scale / 2, scale / 2],
[scale / 2, +scale / 2, -scale / 2],
[-scale / 2, +scale / 2, scale / 2],
[-scale / 2, +scale / 2, -scale / 2],
[+scale / 2, -scale / 2, scale / 2],
[+scale / 2, -scale / 2, -scale / 2],
[-scale / 2, -scale / 2, scale / 2],
[-scale / 2, -scale / 2, -scale / 2]]) +shift
bbox_3d = bbox_3d.transpose()
return bbox_3d
def transform_coordinates_3d(coordinates, RT):
"""
Input:
coordinates: [3, N]
RT: [4, 4]
Return
new_coordinates: [3, N]
"""
assert coordinates.shape[0] == 3
coordinates = np.vstack([coordinates, np.ones((1, coordinates.shape[1]), dtype=np.float32)])
new_coordinates = RT @ coordinates
new_coordinates = new_coordinates[:3, :]/new_coordinates[3, :]
return new_coordinates
def calculate_2d_projections(coordinates_3d, intrinsics):
"""
Input:
coordinates: [3, N]
intrinsics: [3, 3]
Return
projected_coordinates: [N, 2]
"""
projected_coordinates = intrinsics @ coordinates_3d
projected_coordinates = projected_coordinates[:2, :] / projected_coordinates[2, :]
projected_coordinates = projected_coordinates.transpose()
projected_coordinates = np.array(projected_coordinates, dtype=np.int32)
return projected_coordinates
############################################################
# IMAGE AUGMENTATION
############################################################
def calculate_rotation(image_size, angle):
image_center = tuple(np.array(image_size) / 2)
# Convert the OpenCV 3x2 rotation matrix to 3x3
rot_mat = np.vstack(
[cv2.getRotationMatrix2D(image_center, angle, 1.0), [0, 0, 1]]
)
rot_mat_notranslate = np.matrix(rot_mat[0:2, 0:2])
# Shorthand for below calcs
image_w2 = image_size[0] * 0.5
image_h2 = image_size[1] * 0.5
# Obtain the rotated coordinates of the image corners
rotated_coords = [
(np.array([-image_w2, image_h2]) * rot_mat_notranslate).A[0],
(np.array([image_w2, image_h2]) * rot_mat_notranslate).A[0],
(np.array([-image_w2, -image_h2]) * rot_mat_notranslate).A[0],
(np.array([image_w2, -image_h2]) * rot_mat_notranslate).A[0]
]
# Find the size of the new image
x_coords = [pt[0] for pt in rotated_coords]
x_pos = [x for x in x_coords if x > 0]
x_neg = [x for x in x_coords if x < 0]
y_coords = [pt[1] for pt in rotated_coords]
y_pos = [y for y in y_coords if y > 0]
y_neg = [y for y in y_coords if y < 0]
right_bound = max(x_pos)
left_bound = min(x_neg)
top_bound = max(y_pos)
bot_bound = min(y_neg)
new_w = int(abs(right_bound - left_bound))
new_h = int(abs(top_bound - bot_bound))
# We require a translation matrix to keep the image centred
trans_mat = np.matrix([
[1, 0, int(new_w * 0.5 - image_w2)],
[0, 1, int(new_h * 0.5 - image_h2)],
[0, 0, 1]
])
# Compute the tranform for the combined rotation and translation
affine_mat = (np.matrix(trans_mat) * np.matrix(rot_mat))[0:2, :]
return new_w, new_h, affine_mat
def rotate_image(image, new_w, new_h, affine_mat, interpolation=cv2.INTER_LINEAR):
"""
Rotates an OpenCV 2 / NumPy image about it's centre by the given angle
(in degrees). The returned image will be large enough to hold the entire
new image, with a black background
"""
# Get the image size
# No that's not an error - NumPy stores image matricies backwards
# Apply the transform
result = cv2.warpAffine(
image,
affine_mat,
(new_w, new_h),
flags=interpolation
)
return result
def largest_rotated_rect(w, h, angle):
"""
Given a rectangle of size wxh that has been rotated by 'angle' (in
radians), computes the width and height of the largest possible
axis-aligned rectangle within the rotated rectangle.
Original JS code by 'Andri' and Magnus Hoff from Stack Overflow
Converted to Python by Aaron Snoswell
"""
quadrant = int(math.floor(angle / (math.pi / 2))) & 3
sign_alpha = angle if ((quadrant & 1) == 0) else math.pi - angle
alpha = (sign_alpha % math.pi + math.pi) % math.pi
bb_w = w * math.cos(alpha) + h * math.sin(alpha)
bb_h = w * math.sin(alpha) + h * math.cos(alpha)
gamma = math.atan2(bb_w, bb_w) if (w < h) else math.atan2(bb_w, bb_w)
delta = math.pi - alpha - gamma
length = h if (w < h) else w
d = length * math.cos(alpha)
a = d * math.sin(alpha) / math.sin(delta)
y = a * math.cos(gamma)
x = y * math.tan(gamma)
return (
bb_w - 2 * x,
bb_h - 2 * y
)
def crop_around_center(image, width, height):
"""
Given a NumPy / OpenCV 2 image, crops it to the given width and height,
around it's centre point
"""
image_size = (image.shape[1], image.shape[0])
image_center = (int(image_size[0] * 0.5), int(image_size[1] * 0.5))
if(width > image_size[0]):
width = image_size[0]
if(height > image_size[1]):
height = image_size[1]
x1 = int(image_center[0] - width * 0.5)
x2 = int(image_center[0] + width * 0.5)
y1 = int(image_center[1] - height * 0.5)
y2 = int(image_center[1] + height * 0.5)
return image[y1:y2, x1:x2]
def rotate_and_crop(image, rotate_degree, interpolation):
image_height, image_width = image.shape[0:2]
new_w, new_h, affine_mat = calculate_rotation(image.shape[0:2][::-1], rotate_degree)
image_rotated = rotate_image(image, new_w, new_h, affine_mat, interpolation)
image_rotated_cropped = crop_around_center(
image_rotated,
*largest_rotated_rect(
image_width,
image_height,
math.radians(rotate_degree)
)
)
return image_rotated_cropped
def rotate_and_crop_images(image, masks, coords, rotate_degree):
image_height, image_width = image.shape[0:2]
new_w, new_h, affine_mat = calculate_rotation(image.shape[0:2][::-1], rotate_degree)
image_rotated = rotate_image(image, new_w, new_h, affine_mat, cv2.INTER_LINEAR)
mask_rotated = rotate_image(masks, new_w, new_h, affine_mat, cv2.INTER_NEAREST)
rect = largest_rotated_rect(
image_width,
image_height,
math.radians(rotate_degree)
)
image_rotated_cropped = crop_around_center(image_rotated, *rect)
mask_rotated_cropped = crop_around_center(mask_rotated, *rect)
image_rotated_cropped = cv2.resize(image_rotated_cropped, (image_width, image_height),interpolation=cv2.INTER_LINEAR)
mask_rotated_cropped = cv2.resize(mask_rotated_cropped, (image_width, image_height), interpolation=cv2.INTER_NEAREST)
if coords is not None:
coord_rotated = rotate_image(coords, new_w, new_h, affine_mat, cv2.INTER_NEAREST)
coord_rotated_cropped = crop_around_center(coord_rotated, *rect)
coord_rotated_cropped = cv2.resize(coord_rotated_cropped, (image_width, image_height), interpolation=cv2.INTER_NEAREST)
return image_rotated_cropped, mask_rotated_cropped, coord_rotated_cropped
else:
return image_rotated_cropped, mask_rotated_cropped
############################################################
# Dataset
############################################################
class Dataset(object):
"""The base class for dataset classes.
To use it, create a new class that adds functions specific to the dataset
you want to use. For example:
class CatsAndDogsDataset(Dataset):
def load_cats_and_dogs(self):
...
def load_mask(self, image_id):
...
def image_reference(self, image_id):
...
See COCODataset and ShapesDataset as examples.
"""
def __init__(self, class_map=None):
self._image_ids = []
self.image_info = []
# Background is always the first class
self.class_info = [{"source": "", "id": 0, "name": "BG"}]
self.source_class_ids = {}
def add_class(self, source, class_id, class_name):
assert "." not in source, "Source name cannot contain a dot"
# Does the class exist already?
for info in self.class_info:
if info['source'] == source and info["id"] == class_id:
# source.class_id combination already available, skip
return
# Add the class
self.class_info.append({
"source": source,
"id": class_id,
"name": class_name,
})
def add_image(self, source, image_id, path, **kwargs):
image_info = {
"id": image_id,
"source": source,
"path": path,
}
image_info.update(kwargs)
self.image_info.append(image_info)
def image_reference(self, image_id):
"""Return a link to the image in its source Website or details about
the image that help looking it up or debugging it.
Override for your dataset, but pass to this function
if you encounter images not in your dataset.
"""
return ""
def prepare(self, class_map=None):
"""Prepares the Dataset class for use.d
"""
def clean_name(name):
"""Returns a shorter version of object names for cleaner display."""
return ",".join(name.split(",")[:1])
# Build (or rebuild) everything else from the info dicts.
#self.num_classes = len(self.class_info)
self.num_classes = 0
#self.class_ids = np.arange(self.num_classes)
self.class_ids = []
#self.class_names = [clean_name(c["name"]) for c in self.class_info]
self.class_names = []
#self.class_from_source_map = {"{}.{}".format(info['source'], info['id']): id
# for info, id in zip(self.class_info, self.class_ids)}
self.class_from_source_map = {}
for cls_info in self.class_info:
source = cls_info["source"]
if source == 'coco':
map_key = "{}.{}".format(cls_info['source'], cls_info['id'])
self.class_from_source_map[map_key] = self.class_names.index(class_map[cls_info["name"]])
else:
self.class_ids.append(self.num_classes)
self.num_classes += 1
self.class_names.append(cls_info["name"])
map_key = "{}.{}".format(cls_info['source'], cls_info['id'])
self.class_from_source_map[map_key] = self.class_ids[-1]
self.num_images = len(self.image_info)
self._image_ids = np.arange(self.num_images)
# Mapping from source class and image IDs to internal IDs
self.image_from_source_map = {"{}.{}".format(info['source'], info['id']): id
for info, id in zip(self.image_info, self.image_ids)}
# Map sources to class_ids they support
self.sources = list(set([i['source'] for i in self.class_info]))
'''
self.source_class_ids = {}
# Loop over datasets
for source in self.sources:
self.source_class_ids[source] = []
# Find classes that belong to this dataset
for i, info in enumerate(self.class_info):
# Include BG class in all datasets
if i == 0 or source == info['source']:
self.source_class_ids[source].append(i)
'''
print(self.class_names)