-
Notifications
You must be signed in to change notification settings - Fork 66
/
det_tools.py
executable file
·1771 lines (1469 loc) · 78.8 KB
/
det_tools.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
# -*- coding: utf-8 -*-
import math
import numpy as np
import os
import random
import sys
import glob
import cv2
import tensorflow as tf
from spatial_transformer import inplane_inverse_warp
def inverse_warp_view_2_to_1(heatmaps2, depths2, depths1, c2Tc1s, K1, K2, inv_thetas1, thetas2, depth_thresh=0.5, get_warped_depth=False):
# compute warping xy coordinate from view1 to view2
# Args
# depths1: [B,H,W,1] tf.float32
# c2Tc1s: [B,4,4] tf.float32
# K1,K2: [B,3,3] tf.float32
# inv_thetas1: [B,3,3] tf.float32
# thetas2: [B,3,3] tf.float32
# Return
# heatmaps1w : [B,H,W,1] tf.float32 warped heatmaps from camera2 to camera1
# visible_masks1 : [B,H,W,1] tf.float32 visible masks on camera1
# xy_u2 : [B,H,W,2] tf.float32 xy-coords-maps from camera1 to camera2
def norm_meshgrid(batch, height, width, is_homogeneous=True):
"""Construct a 2D meshgrid.
Args:
batch: batch size
height: height of the grid
width: width of the grid
is_homogeneous: whether to return in homogeneous coordinates
Returns:
x,y grid coordinates [batch, 2 (3 if homogeneous), height, width]
"""
x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])),
tf.transpose(tf.expand_dims(
tf.linspace(-1.0, 1.0, width), 1), [1, 0]))
y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1),
tf.ones(shape=tf.stack([1, width])))
if is_homogeneous:
ones = tf.ones_like(x_t)
coords = tf.stack([x_t, y_t, ones], axis=0)
else:
coords = tf.stack([x_t, y_t], axis=0)
coords = tf.tile(tf.expand_dims(coords, 0), [batch, 1, 1, 1])
return coords
def norm_xy_coords(xyz, height, width):
# xyz: [B,>=3,N], tf.float32 xyz[:,0] = x, xyz[:,1]=y
# suppose 0<=x<width, 0<=y<height
# outputs range will be [-1,1]
x_t = tf.slice(xyz, [0,0,0], [-1,1,-1])
y_t = tf.slice(xyz, [0,1,0], [-1,1,-1])
z_t = tf.slice(xyz, [0,2,0], [-1,-1,-1])
x_t = 2 * (x_t / tf.cast(width-1,tf.float32)) - 1.0
y_t = 2 * (y_t / tf.cast(height-1, tf.float32)) - 1.0
n_xyz = tf.concat([x_t, y_t, z_t], axis=1)
return n_xyz
def unnorm_xy_coords(xyz, height, width):
# xyz: [B,>=3,N], tf.float32 xyz[:,0] = x, xyz[:,1]=y
# suppose -1<=x<=1, -1<=y<=1
# outputs range will be [0,width) or [0,height)
x_t = tf.slice(xyz, [0,0,0], [-1,1,-1])
y_t = tf.slice(xyz, [0,1,0], [-1,1,-1])
z_t = tf.slice(xyz, [0,2,0], [-1,-1,-1])
x_t = (x_t+1.0) * 0.5 * tf.cast(width-1, tf.float32)
y_t = (y_t+1.0) * 0.5 * tf.cast(height-1, tf.float32)
u_xyz = tf.concat([x_t, y_t, z_t], axis=1)
return u_xyz
with tf.name_scope('WarpCoordinates'):
if K2 is None:
K2 = K1 # use same intrinsic matrix
eps = 1e-6
batch_size = tf.shape(depths1)[0]
height1 = tf.shape(depths1)[1]
width1 = tf.shape(depths1)[2]
inv_K1 = tf.matrix_inverse(K1)
right_col = tf.zeros([batch_size,3,1], dtype=tf.float32)
bottom_row = tf.tile(tf.constant([0,0,0,1], dtype=tf.float32, shape=[1,1,4]), [batch_size,1,1])
K2_4x4 = tf.concat([K2, right_col], axis=2)
K2_4x4 = tf.concat([K2_4x4, bottom_row], axis=1)
xy_n1 = norm_meshgrid(batch_size, height1, width1) # [B,3,H,W]
xy_n1 = tf.reshape(xy_n1, [batch_size, 3, -1]) # [B,3,N], N=H*W
# Inverse inplane transformation on camera1
if inv_thetas1 is not None:
xy_n1 = tf.matmul(inv_thetas1, xy_n1)
z_n1 = tf.slice(xy_n1, [0,2,0],[-1,1,-1])
xy_n1 = xy_n1 / (z_n1+eps)
# SE(3) transformation : pixel1 to camera1
Z1 = tf.reshape(depths1, [batch_size, 1, -1])
xy_u1 = unnorm_xy_coords(xy_n1, height=height1, width=width1)
XYZ1 = tf.matmul(inv_K1, xy_u1) * Z1
ones = tf.ones([batch_size, 1, height1*width1])
XYZ1 = tf.concat([XYZ1, ones], axis=1)
# SE(3) transformation : camera1 to camera2 to pixel2
proj_T = tf.matmul(K2_4x4, c2Tc1s)
xyz2 = tf.matmul(proj_T, XYZ1)
z2 = tf.slice(xyz2, [0,2,0], [-1,1,-1])
reproj_depths = tf.reshape(z2, [batch_size, 1, height1, width1])
reproj_depths = tf.transpose(reproj_depths, perm=[0,2,3,1]) # [B,H,W,1]
xy_u2 = tf.slice(xyz2, [0,0,0],[-1,3,-1]) / (z2+eps)
# Inplane transformation on camera2
if thetas2 is not None:
xy_n2 = norm_xy_coords(xy_u2, height1, width1)
xy_n2 = tf.matmul(thetas2, xy_n2)
z_n2 = tf.slice(xy_n2,[0,2,0], [-1,1,-1])
xy_n2 = xy_n2 / (z_n2+eps)
xy_u2 = unnorm_xy_coords(xy_n2, height1, width1)
xy_u2 = tf.slice(xy_u2, [0,0,0],[-1,2,-1]) # discard third dim
xy_u2 = tf.reshape(xy_u2, [batch_size, 2, height1, width1])
xy_u2 = tf.transpose(xy_u2, perm=[0, 2, 3, 1]) # [B,H,W,2]
heatmaps1w, depths1w = bilinear_sampling(heatmaps2, xy_u2, depths2) # it is not correct way to check depth consistency but it works well practically
visible_masks = get_visibility_mask(xy_u2)
camfront_masks = tf.cast(tf.greater(reproj_depths, tf.zeros((), reproj_depths.dtype)), tf.float32)
nonocc_masks = tf.cast(tf.less(tf.squared_difference(depths1w, depths1), depth_thresh**2), tf.float32)
visible_masks = visible_masks * camfront_masks * nonocc_masks # take logical_and
heatmaps1w = heatmaps1w * visible_masks
if get_warped_depth:
return heatmaps1w, visible_masks, xy_u2, depths1w
else:
return heatmaps1w, visible_masks, xy_u2
def get_angle_colorbar():
hue = np.arange(360)[:,None, None].astype(np.float32)
ones = np.ones_like(hue)
hsv = np.concatenate([hue, ones, ones], axis=-1)
colorbar = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
colorbar = np.squeeze(colorbar)
return colorbar
def get_degree_maps(ori_maps):
# ori_maps : [B,H,W,2], consist of cos, sin response
cos_maps = tf.slice(ori_maps, [0,0,0,0], [-1,-1,-1,1])
sin_maps = tf.slice(ori_maps, [0,0,0,1], [-1,-1,-1,1])
atan_maps = tf.atan2(sin_maps, cos_maps)
angle2rgb = tf.constant(get_angle_colorbar())
degree_maps = tf.cast(tf.clip_by_value(atan_maps*180/np.pi+180, 0, 360), tf.int32)
degree_maps = tf.gather(angle2rgb, degree_maps[...,0])
return degree_maps, atan_maps
# def inverse_warp_view_1_to_2(photos1, depths1, depths2, c1Tc2s, intrinsics_3x3, thetas1=None, thetas2=None, depth_thresh=0.5):
# if thetas1 is not None:
# # inverse in-plane transformation
# photo_depths1 = tf.concat([photos1, depths1], axis=-1)
# inwarp_photo_depths1, _ = inplane_inverse_warp(photo_depths1, thetas1)
# photos1 = tf.slice(inwarp_photo_depths1, [0,0,0,0],[-1,-1,-1,1])
# depths1 = tf.slice(inwarp_photo_depths1, [0,0,0,1],[-1,-1,-1,1])
# # projective inverse transformation
# photos2w, visible_masks2 = projective_inverse_warp(photos1, depths2, c1Tc2s,
# intrinsics_3x3, depths1, depth_thresh)
# projective_visible_masks2 = tf.identity(visible_masks2)
# if thetas2 is not None:
# # inverse in-plane transformation
# photo_masks2 = tf.concat([photos2w, visible_masks2], axis=-1)
# inwarp_photo_masks2, _ = inplane_inverse_warp(photo_masks2, thetas2)
# photos2w = tf.slice(inwarp_photo_masks2, [0,0,0,0], [-1,-1,-1,1])
# visible_masks2 = tf.slice(inwarp_photo_masks2, [0,0,0,1], [-1,-1,-1,1])
# visible_masks2 = tf.cast(tf.greater(visible_masks2, 0.5), tf.float32)
# return photos2w, visible_masks2, projective_visible_masks2
def end_of_frame_masks(height, width, radius, dtype=tf.float32):
eof_masks = tf.ones(tf.stack([1,height-2*radius,width-2*radius,1]), dtype=dtype)
eof_masks = tf.pad(eof_masks, [[0,0],[radius,radius],[radius,radius],[0,0]])
return eof_masks
def morphology_closing(inputs, dilate_ksize=3, erode_ksize=5):
curr_in = inputs
if dilate_ksize > 1:
curr_in = tf.nn.max_pool(curr_in, [1,dilate_ksize,dilate_ksize,1],
strides=[1,1,1,1], padding='SAME')
if erode_ksize > 1:
curr_in = -tf.nn.max_pool(-curr_in, [1,erode_ksize,erode_ksize,1],
strides=[1,1,1,1], padding='SAME')
return curr_in
def batch_gather_keypoints(inputs, batch_inds, kpts, xy_order=True):
# kpts: [N,2] x,y or y,x
# batch_inds: [N]
# outputs = inputs[b,y,x]
if xy_order:
kp_x, kp_y = tf.split(kpts, 2, axis=1)
else:
kp_y, kp_x = tf.split(kpts, 2, axis=1)
if len(batch_inds.get_shape().as_list()) == 1:
batch_inds = batch_inds[:,None]
byx = tf.concat([batch_inds, kp_y, kp_x], axis=1)
outputs = tf.gather_nd(inputs, byx)
return outputs
# def coordinate_se3_warp(kpts1, batch_inds, intrinsics_3x3, c2Tc1s, depths1, visible_masks2):
# # kpts1: [N,2] int32 (x,y)
# # batch_inds: [N,] int32 [0,batch_size)
# # intrinsics_3x3: [3,3] float32
# # c2Tc1s: [B,4,4] float32
# # depths1: [B,H,W,1] float32
# with tf.name_scope('XY_SE3_WARP'):
# N = tf.shape(kpts1)[0]
# # gather Z
# kp_x, kp_y = tf.split(kpts1, 2, axis=1)
# byx = tf.concat([batch_inds[:,None], kp_y, kp_x], axis=1) # [N,3]
# kp_z = tf.gather_nd(depths1, byx) # [N,1]
# # pix2cam
# pix_kpts = tf.transpose(tf.cast(kpts1, tf.float32)) # [2,N]
# ones = tf.ones([1,N], dtype=tf.float32)
# hpix_kpts = tf.concat([pix_kpts, ones], axis=0) # [3,N]
# inv_intrinsics = tf.matrix_inverse(intrinsics_3x3) # [3,3]
# cam_kpts = tf.matmul(inv_intrinsics, hpix_kpts) * tf.transpose(kp_z) # [3,3]*[3,N]*[1,N] = [3,N]
# hcam_kpts = tf.concat([cam_kpts, ones], axis=0) # [4,N]
# # projection matrix
# gathered_c2Tc1s = tf.gather(c2Tc1s, batch_inds) # [B,4,4],[N] --> [N,4,4]
# intrinsics_4x4 = tf.concat([intrinsics_3x3, tf.zeros([3,1])], axis=1)
# intrinsics_4x4 = tf.concat([intrinsics_4x4, tf.constant([0.,0.,0.,1.], shape=[1,4])], axis=0)
# intrinsics_4x4 = tf.tile(intrinsics_4x4[None], [N,1,1]) # [N,4,4]
# projT = tf.matmul(intrinsics_4x4, gathered_c2Tc1s) # [N,4,4]
# # cam2pix
# hcam_kpts = tf.transpose(hcam_kpts)[...,None] # [4,N]->[N,4,1]
# hcam_kpts_w = tf.matmul(projT, hcam_kpts)[:,:,0] # [N,4,4]*[N,4,1]-->[N,4]
# x_u = tf.slice(hcam_kpts_w, [0,0],[-1,1])
# y_u = tf.slice(hcam_kpts_w, [0,1],[-1,1])
# z_u = tf.slice(hcam_kpts_w, [0,2],[-1,1])
# kp_xw = x_u / (z_u+1e-6)
# kp_yw = y_u / (z_u+1e-6)
# # kpts_w = tf.concat([kp_xw, kp_yw], axis=1) # [N,2]
# # check visibility
# x0 = tf.cast(tf.floor(kp_xw), tf.int32)
# x1 = x0 + 1
# y0 = tf.cast(tf.floor(kp_yw), tf.int32)
# y1 = y0 + 1
# height = tf.shape(visible_masks2)[1]
# width = tf.shape(visible_masks2)[2]
# inside_x = tf.logical_and(tf.greater_equal(x0, 0), tf.less(x1, width))
# inside_y = tf.logical_and(tf.greater_equal(y0, 0), tf.less(y1, height))
# visibility = tf.cast(tf.logical_and(inside_x, inside_y), tf.float32)
# kp_xw_safe = tf.clip_by_value(tf.cast(tf.round(kp_xw), tf.int32), 0, width-1)
# kp_yw_safe = tf.clip_by_value(tf.cast(tf.round(kp_yw), tf.int32), 0, height-1)
# kpts_w_safe = tf.concat([kp_xw_safe, kp_yw_safe], axis=1) # [N,1] tf.int32
# byx = tf.concat([batch_inds[:,None], kp_yw_safe, kp_xw_safe], axis=1) # [N,3]
# gather_visbility = tf.gather_nd(visible_masks2, byx) # [N,1]
# # print('## ', visible_masks2.shape, byx.shape, gather_visbility.shape)
# visibility = visibility * gather_visbility # [N,1] tf.float32
# visibility = tf.squeeze(visibility, 1) # [N, ] tf.float32
# return kpts_w_safe, visibility
def coordinate_se3_warp(kpts1, batch_inds, intrinsics_3x3, c2Tc1s, depths1, visible_masks2):
# kpts1: [N,2] int32 (x,y)
# batch_inds: [N,] int32 [0,batch_size)
# intrinsics_3x3: [B,3,3] float32
# c2Tc1s: [B,4,4] float32
# depths1: [B,H,W,1] float32
with tf.name_scope('XY_SE3_WARP'):
N = tf.shape(kpts1)[0]
# gather Z
kp_x, kp_y = tf.split(kpts1, 2, axis=1)
byx = tf.concat([batch_inds[:,None], kp_y, kp_x], axis=1) # [N,3]
kp_z = tf.gather_nd(depths1, byx) # [N,1]
# pix2cam
pix_kpts = tf.transpose(tf.cast(kpts1, tf.float32)) # [2,N]
ones = tf.ones([1,N], dtype=tf.float32)
hpix_kpts = tf.concat([pix_kpts, ones], axis=0) # [3,N]
hpix_kpts = tf.expand_dims(tf.transpose(hpix_kpts), axis=-1) # [N,3,1]
inv_intrinsics = tf.matrix_inverse(intrinsics_3x3) # [B,3,3]
gatherd_inv_intrinsics = tf.gather(inv_intrinsics, batch_inds) # [B,3,3],[N]-->[N,3,3]
cam_kpts = tf.squeeze(tf.matmul(gatherd_inv_intrinsics, hpix_kpts), axis=-1) # [N,3,3]x[N,3,1] --> [N,3,1] --> [N,3]
cam_kpts = tf.transpose(cam_kpts*kp_z) # [3,N]
hcam_kpts = tf.concat([cam_kpts, ones], axis=0) # [4,N]
# projection matrix
gathered_c2Tc1s = tf.gather(c2Tc1s, batch_inds) # [B,4,4],[N] --> [N,4,4]
batch = tf.shape(intrinsics_3x3)[0]
right_col = tf.zeros([batch,3,1], dtype=tf.float32)
bottom_row = tf.tile(tf.constant([0,0,0,1], dtype=tf.float32, shape=[1,1,4]), [batch,1,1])
intrinsics_4x4 = tf.concat([intrinsics_3x3, right_col], axis=2)
intrinsics_4x4 = tf.concat([intrinsics_4x4, bottom_row], axis=1) # [B,4,4]
gathered_intrinsics_4x4 = tf.gather(intrinsics_4x4, batch_inds) # [B,4,4],[N] --> [N,4,4]
projT = tf.matmul(gathered_intrinsics_4x4, gathered_c2Tc1s) # [N,4,4]
# cam2pix
hcam_kpts = tf.transpose(hcam_kpts)[...,None] # [4,N]->[N,4,1]
hcam_kpts_w = tf.matmul(projT, hcam_kpts)[:,:,0] # [N,4,4]*[N,4,1]-->[N,4]
x_u = tf.slice(hcam_kpts_w, [0,0],[-1,1])
y_u = tf.slice(hcam_kpts_w, [0,1],[-1,1])
z_u = tf.slice(hcam_kpts_w, [0,2],[-1,1])
kp_xw = x_u / (z_u+1e-6)
kp_yw = y_u / (z_u+1e-6)
# kpts_w = tf.concat([kp_xw, kp_yw], axis=1) # [N,2]
# check visibility
x0 = tf.cast(tf.floor(kp_xw), tf.int32)
x1 = x0 + 1
y0 = tf.cast(tf.floor(kp_yw), tf.int32)
y1 = y0 + 1
height = tf.shape(visible_masks2)[1]
width = tf.shape(visible_masks2)[2]
inside_x = tf.logical_and(tf.greater_equal(x0, 0), tf.less(x1, width))
inside_y = tf.logical_and(tf.greater_equal(y0, 0), tf.less(y1, height))
visibility = tf.cast(tf.logical_and(inside_x, inside_y), tf.float32)
kp_xw_safe = tf.clip_by_value(tf.cast(tf.round(kp_xw), tf.int32), 0, width-1)
kp_yw_safe = tf.clip_by_value(tf.cast(tf.round(kp_yw), tf.int32), 0, height-1)
kpts_w_safe = tf.concat([kp_xw_safe, kp_yw_safe], axis=1) # [N,1] tf.int32
byx = tf.concat([batch_inds[:,None], kp_yw_safe, kp_xw_safe], axis=1) # [N,3]
gather_visbility = tf.gather_nd(visible_masks2, byx) # [N,1]
# print('## ', visible_masks2.shape, byx.shape, gather_visbility.shape)
visibility = visibility * gather_visbility # [N,1] tf.float32
visibility = tf.squeeze(visibility, 1) # [N, ] tf.float32
return kpts_w_safe, visibility
def find_hard_negative_from_myself(feats):
# feats.shape = [B,K,D]
K = tf.shape(feats)[1]
feats1_mat = tf.expand_dims(feats, axis=2) # [B,K,D] --> [B,K,1,D]
feats2_mat = tf.expand_dims(feats, axis=1) # [B,L,D] --> [B,1,L,D]
feats1_mat = tf.tile(feats1_mat, [1,1,K,1]) # [B,K,L,D]
feats2_mat = tf.tile(feats2_mat, [1,K,1,1]) # [B,K,L,D]
distances = tf.reduce_sum(tf.squared_difference(feats1_mat, feats2_mat), axis=-1) # [B,K,K]
myself = tf.eye(K)[None] * 1e5
distances = distances + myself
min_dist = tf.reduce_min(distances, axis=2) # min_dist1(i) = min_j |feats1(i)- feats2(j)|^2 [B,K]
arg_min = tf.argmin(distances, axis=2, output_type=tf.int32)
return min_dist, arg_min, distances
# def batch_nearest_neighbors_less_memory(feats1, batch_inds1, num_kpts1, feats2, batch_inds2, num_kpts2, batch_size, num_parallel=1, back_prop=False):
# # feats1 = [B*K1, D], feats2 = [B*K2,D]
# # batch_inds = [B*K,] takes [0,batch_size)
# # num_kpts: [B,] tf.int32
# # outputs = min_dist, arg_min [B*K]
# N1 = tf.shape(feats1)[0]
# batch_offsets1 = tf.concat([tf.zeros(1, dtype=tf.int32), tf.cumsum(num_kpts1)], axis=0)
# ta_dist1 = tf.TensorArray(dtype=tf.float32, size=N1)
# ta_inds1 = tf.TensorArray(dtype=tf.int32, size=N1)
# N2 = tf.shape(feats2)[0]
# batch_offsets2 = tf.concat([tf.zeros(1, dtype=tf.int32), tf.cumsum(num_kpts2)], axis=0)
# ta_dist2 = tf.TensorArray(dtype=tf.float32, size=N1)
# ta_inds2 = tf.TensorArray(dtype=tf.int32, size=N1)
# init_state = (0, ta_dist1, ta_inds1, ta_dist2, ta_inds2)
# condition = lambda i, _, _2: i < batch_size
# def body(i, ta_dist, ta_inds):
# pass
def find_hard_negative_from_myself_less_memory(feats, batch_inds, num_kpts, batch_size, num_parallel=1, back_prop=False):
# feats = [B*K, D]
# batch_inds = [B*K,] takes [0,batch_size)
# num_kpts: [B,] tf.int32
# outputs = min_dist, arg_min [B*K]
N = tf.shape(feats)[0]
batch_offsets = tf.concat([tf.zeros(1, dtype=tf.int32), tf.cumsum(num_kpts)], axis=0)
ta_dist = tf.TensorArray(dtype=tf.float32, size=N)
ta_inds = tf.TensorArray(dtype=tf.int32, size=N)
init_state = (0, ta_dist, ta_inds)
condition = lambda i, _, _2: i < batch_size
def body(i, ta_dist, ta_inds):
curr_inds = tf.cast(tf.reshape(tf.where(tf.equal(batch_inds, i)), [-1]), tf.int32)
is_empty = tf.equal(tf.size(curr_inds), 0)
curr_inds = tf.cond(is_empty, lambda: tf.constant([0,], dtype=tf.int32), lambda: curr_inds) # if empty use dammy index but all results are ignored
curr_feats = tf.gather(feats, curr_inds) # [K,D]
K = tf.shape(curr_feats)[0]
feats1_mat = tf.expand_dims(curr_feats, axis=1) # [K,1,D]
feats2_mat = tf.expand_dims(curr_feats, axis=0) # [1,K,D]
feats1_mat = tf.tile(feats1_mat, [1,K,1]) # [K,K,D]
feats2_mat = tf.tile(feats2_mat, [K,1,1])
distances = tf.reduce_sum(tf.squared_difference(feats1_mat, feats2_mat), axis=-1) # [K,K]
myself = tf.eye(K) * 1e5
distances = distances + myself # avoid to pickup myself
min_dist = tf.reduce_min(distances, axis=1) # min_dist1(i) = min_j |feats1(i)- feats2(j)|^2 [B,K]
arg_min = tf.argmin(distances, axis=1, output_type=tf.int32)
offset = batch_offsets[i]
arg_min = arg_min + offset
ta_dist = tf.cond(is_empty, lambda: ta_dist, lambda: ta_dist.scatter(curr_inds, min_dist))
ta_inds = tf.cond(is_empty, lambda: ta_inds, lambda: ta_inds.scatter(curr_inds, arg_min))
return i+1, ta_dist, ta_inds
# return i+1, ta_dist.scatter(curr_inds, min_dist), ta_inds.scatter(curr_inds, arg_min)
n, ta_dist_final, ta_inds_final = tf.while_loop(condition, body, init_state,
parallel_iterations=num_parallel,
back_prop=back_prop)
min_dist = ta_dist_final.stack()
min_inds = ta_inds_final.stack()
return min_dist, min_inds
def find_random_hard_negative_from_myself_with_geom_constrain_less_memory(num_pickup, feats, feats_warp, kpts_warp, batch_inds, num_kpts, batch_size, geom_sq_thresh, num_parallel=1, back_prop=False):
# find nearest ref-feats index
# feats = [B*K, D] feature on image1
# feats_warp = [B*K, D] feature on image2 (warped feature from image1)
# kpts = [B*K, 2] keypoints on image2 (warped coordinates from image1)
# geom_sqr_thresh = squre threshold of x,y coordinate distance
# batch_inds = [B*K,] takes [0,batch_size)
# num_kpts: [B,] tf.int32
# outputs = min_dist, arg_min [B*K]
N = tf.shape(feats)[0]
batch_offsets = tf.concat([tf.zeros(1, dtype=tf.int32), tf.cumsum(num_kpts)], axis=0)
ta_inds = tf.TensorArray(dtype=tf.int32, size=N)
init_state = (0, ta_inds)
condition = lambda i, _: i < batch_size
def body(i, ta_inds):
curr_inds = tf.cast(tf.reshape(tf.where(tf.equal(batch_inds, i)), [-1]), tf.int32)
is_empty = tf.equal(tf.size(curr_inds), 0)
curr_inds = tf.cond(is_empty, lambda: tf.constant([0,], dtype=tf.int32), lambda: curr_inds) # if empty use dammy index but all results are ignored
curr_feats1 = tf.gather(feats, curr_inds) # [K,D]
curr_feats2 = tf.gather(feats_warp, curr_inds) # [K,D]
curr_kpts = tf.gather(kpts_warp, curr_inds) # [K,2]
K = tf.shape(curr_feats1)[0]
feats1_mat = tf.expand_dims(curr_feats1, axis=1) # [K,1,D]
feats2_mat = tf.expand_dims(curr_feats2, axis=0) # [1,K,D]
feats1_mat = tf.tile(feats1_mat, [1,K,1]) # [K,K,D]
feats2_mat = tf.tile(feats2_mat, [K,1,1])
feat_dists = tf.reduce_sum(tf.squared_difference(feats1_mat, feats2_mat), axis=-1) # [K,K]
kp1_mat = tf.expand_dims(curr_kpts, axis=1) # [K,1,2]
kp2_mat = tf.expand_dims(curr_kpts, axis=0) # [1,K,2]
kp1_mat = tf.tile(kp1_mat, [1,K,1]) # [K,K,2]
kp2_mat = tf.tile(kp2_mat, [K,1,1])
geom_dists = tf.reduce_sum(tf.squared_difference(kp1_mat, kp2_mat), axis=-1) # [K,K]
neighbor_penalty = tf.cast(tf.less_equal(geom_dists, geom_sq_thresh), tf.float32) * 1e5
feat_dists = feat_dists + neighbor_penalty # avoid to pickup from neighborhood
# sort top_k and pickup from them
topk_dist, topk_inds = tf.nn.top_k(-feat_dists, k=num_pickup, sorted=False) # take the smallest value
# topk_dist = -topk_dist # convert comment out because dist are not necessary
pickup_inds = tf.concat([
tf.range(K,dtype=tf.int32)[:,None],
tf.random_uniform([K,1], minval=0, maxval=num_pickup, dtype=tf.int32)
], axis=1)
min_inds = tf.gather_nd(topk_inds, pickup_inds)
offset = batch_offsets[i]
min_inds = min_inds + offset
ta_inds = tf.cond(is_empty, lambda: ta_inds, lambda: ta_inds.scatter(curr_inds, min_inds))
return i+1, ta_inds
# return i+1, ta_dist.scatter(curr_inds, min_dist), ta_inds.scatter(curr_inds, arg_min)
n, ta_inds_final = tf.while_loop(condition, body, init_state,
parallel_iterations=num_parallel,
back_prop=back_prop)
min_inds = ta_inds_final.stack()
return min_inds
def find_hard_negative_from_myself_with_geom_constrain_less_memory(feats, feats_warp, kpts_warp, batch_inds, num_kpts, batch_size, geom_sq_thresh, num_parallel=1, back_prop=False):
# find nearest ref-feats index
# feats = [B*K, D] feature on image1
# feats_warp = [B*K, D] feature on image2 (warped feature from image1)
# kpts = [B*K, 2] keypoints on image2 (warped coordinates from image1)
# geom_sqr_thresh = squre threshold of x,y coordinate distance
# batch_inds = [B*K,] takes [0,batch_size)
# num_kpts: [B,] tf.int32
# outputs = min_dist, arg_min [B*K]
N = tf.shape(feats)[0]
batch_offsets = tf.concat([tf.zeros(1, dtype=tf.int32), tf.cumsum(num_kpts)], axis=0)
ta_dist = tf.TensorArray(dtype=tf.float32, size=N)
ta_inds = tf.TensorArray(dtype=tf.int32, size=N)
init_state = (0, ta_dist, ta_inds)
condition = lambda i, _, _2: i < batch_size
def body(i, ta_dist, ta_inds):
curr_inds = tf.cast(tf.reshape(tf.where(tf.equal(batch_inds, i)), [-1]), tf.int32)
is_empty = tf.equal(tf.size(curr_inds), 0)
curr_inds = tf.cond(is_empty, lambda: tf.constant([0,], dtype=tf.int32), lambda: curr_inds) # if empty use dammy index but all results are ignored
curr_feats1 = tf.gather(feats, curr_inds) # [K,D]
curr_feats2 = tf.gather(feats_warp, curr_inds) # [K,D]
curr_kpts = tf.gather(kpts_warp, curr_inds) # [K,2]
K = tf.shape(curr_feats1)[0]
feats1_mat = tf.expand_dims(curr_feats1, axis=1) # [K,1,D]
feats2_mat = tf.expand_dims(curr_feats2, axis=0) # [1,K,D]
feats1_mat = tf.tile(feats1_mat, [1,K,1]) # [K,K,D]
feats2_mat = tf.tile(feats2_mat, [K,1,1])
feat_dists = tf.reduce_sum(tf.squared_difference(feats1_mat, feats2_mat), axis=-1) # [K,K]
kp1_mat = tf.expand_dims(curr_kpts, axis=1) # [K,1,2]
kp2_mat = tf.expand_dims(curr_kpts, axis=0) # [1,K,2]
kp1_mat = tf.tile(kp1_mat, [1,K,1]) # [K,K,2]
kp2_mat = tf.tile(kp2_mat, [K,1,1])
geom_dists = tf.reduce_sum(tf.squared_difference(kp1_mat, kp2_mat), axis=-1) # [K,K]
neighbor_penalty = tf.cast(tf.less_equal(geom_dists, geom_sq_thresh), tf.float32) * 1e5
feat_dists = feat_dists + neighbor_penalty # avoid to pickup from neighborhood
min_dist = tf.reduce_min(feat_dists, axis=1) # min_dist1(i) = min_j |feats1(i)- feats2(j)|^2 [B,K]
arg_min = tf.argmin(feat_dists, axis=1, output_type=tf.int32) # find closest warped feats by using argmin(axis=1)
offset = batch_offsets[i]
arg_min = arg_min + offset
ta_dist = tf.cond(is_empty, lambda: ta_dist, lambda: ta_dist.scatter(curr_inds, min_dist))
ta_inds = tf.cond(is_empty, lambda: ta_inds, lambda: ta_inds.scatter(curr_inds, arg_min))
return i+1, ta_dist, ta_inds
# return i+1, ta_dist.scatter(curr_inds, min_dist), ta_inds.scatter(curr_inds, arg_min)
n, ta_dist_final, ta_inds_final = tf.while_loop(condition, body, init_state,
parallel_iterations=num_parallel,
back_prop=back_prop)
min_dist = ta_dist_final.stack()
min_inds = ta_inds_final.stack()
return min_dist, min_inds
def imperfect_find_hard_negative_from_myself_with_geom_constrain_less_memory(feats, kpts, batch_inds, num_kpts, batch_size, geom_sq_thresh, num_parallel=1, back_prop=False):
# feats = [B*K, D]
# kpts = [B*K, 2]
# geom_sqr_thresh = squre threshold of x,y coordinate distance
# batch_inds = [B*K,] takes [0,batch_size)
# num_kpts: [B,] tf.int32
# outputs = min_dist, arg_min [B*K]
N = tf.shape(feats)[0]
batch_offsets = tf.concat([tf.zeros(1, dtype=tf.int32), tf.cumsum(num_kpts)], axis=0)
ta_dist = tf.TensorArray(dtype=tf.float32, size=N)
ta_inds = tf.TensorArray(dtype=tf.int32, size=N)
init_state = (0, ta_dist, ta_inds)
condition = lambda i, _, _2: i < batch_size
def body(i, ta_dist, ta_inds):
curr_inds = tf.cast(tf.reshape(tf.where(tf.equal(batch_inds, i)), [-1]), tf.int32)
is_empty = tf.equal(tf.size(curr_inds), 0)
curr_inds = tf.cond(is_empty, lambda: tf.constant([0,], dtype=tf.int32), lambda: curr_inds) # if empty use dammy index but all results are ignored
curr_feats = tf.gather(feats, curr_inds) # [K,D]
curr_kpts = tf.gather(kpts, curr_inds) # [K,2]
K = tf.shape(curr_feats)[0]
feats1_mat = tf.expand_dims(curr_feats, axis=1) # [K,1,D]
feats2_mat = tf.expand_dims(curr_feats, axis=0) # [1,K,D]
feats1_mat = tf.tile(feats1_mat, [1,K,1]) # [K,K,D]
feats2_mat = tf.tile(feats2_mat, [K,1,1])
feat_dists = tf.reduce_sum(tf.squared_difference(feats1_mat, feats2_mat), axis=-1) # [K,K]
kp1_mat = tf.expand_dims(curr_kpts, axis=1) # [K,1,2]
kp2_mat = tf.expand_dims(curr_kpts, axis=0) # [1,K,2]
kp1_mat = tf.tile(kp1_mat, [1,K,1]) # [K,K,2]
kp2_mat = tf.tile(kp2_mat, [K,1,1])
geom_dists = tf.reduce_sum(tf.squared_difference(kp1_mat, kp2_mat), axis=-1) # [K,K]
neighbor_penalty = tf.cast(tf.less_equal(geom_dists, geom_sq_thresh), tf.float32) * 1e5
feat_dists = feat_dists + neighbor_penalty # avoid to pickup from neighborhood
min_dist = tf.reduce_min(feat_dists, axis=1) # min_dist1(i) = min_j |feats1(i)- feats2(j)|^2 [B,K]
arg_min = tf.argmin(feat_dists, axis=1, output_type=tf.int32)
offset = batch_offsets[i]
arg_min = arg_min + offset
ta_dist = tf.cond(is_empty, lambda: ta_dist, lambda: ta_dist.scatter(curr_inds, min_dist))
ta_inds = tf.cond(is_empty, lambda: ta_inds, lambda: ta_inds.scatter(curr_inds, arg_min))
return i+1, ta_dist, ta_inds
# return i+1, ta_dist.scatter(curr_inds, min_dist), ta_inds.scatter(curr_inds, arg_min)
n, ta_dist_final, ta_inds_final = tf.while_loop(condition, body, init_state,
parallel_iterations=num_parallel,
back_prop=back_prop)
min_dist = ta_dist_final.stack()
min_inds = ta_inds_final.stack()
return min_dist, min_inds
def find_random_negative_from_myself_less_memory(feats, batch_inds, num_kpts, batch_size, num_parallel=1, back_prop=False):
# feats = [B*K, D]
# batch_inds = [B*K,] takes [0,batch_size)
# num_kpts: [B,] tf.int32
# outputs = min_dist, arg_min [B*K]
N = tf.shape(feats)[0]
batch_offsets = tf.concat([tf.zeros(1, dtype=tf.int32), tf.cumsum(num_kpts)], axis=0)
ta_inds = tf.TensorArray(dtype=tf.int32, size=N)
init_state = (0, ta_inds)
condition = lambda i, _,: i < batch_size
def body(i, ta_inds):
curr_inds = tf.cast(tf.reshape(tf.where(tf.equal(batch_inds, i)), [-1]), tf.int32)
is_empty = tf.equal(tf.size(curr_inds), 0)
curr_inds = tf.cond(is_empty, lambda: tf.constant([0,], dtype=tf.int32), lambda: curr_inds) # if empty use dammy index but all results are ignored
curr_feats = tf.gather(feats, curr_inds) # [K,D]
K = tf.shape(curr_feats)[0]
# could be select itself in case K=1
rnd_inds = tf.random_uniform([K], minval=1, maxval=tf.maximum(K,2), dtype=tf.int32) # random_uniform doesn't allow the case minval==maxval
# rnd_inds = tf.ones([K], dtype=tf.int32) * 2
rnd_inds = tf.range(K) + rnd_inds
rnd_inds = tf.where(tf.less(rnd_inds, K), rnd_inds, rnd_inds-K)
rnd_inds = rnd_inds + batch_offsets[i]
ta_inds = tf.cond(is_empty, lambda: ta_inds, lambda: ta_inds.scatter(curr_inds, rnd_inds))
return i+1, ta_inds
n, ta_inds_final = tf.while_loop(condition, body, init_state,
parallel_iterations=num_parallel,
back_prop=back_prop)
rnd_inds = ta_inds_final.stack()
return rnd_inds
# def find_correspondences(points, indices):
# # points: tf.float32, [B,K,2]
# # indices: tf.int32, [B,L] indices[i,j] = [0,K)
# B = tf.shape(indices)[0]
# L = tf.shape(indices)[1]
# batch_indices = tf.tile(tf.range(B, dtype=indices.dtype)[:,None], [1,L])
# indices = tf.reshape(indices, [-1,1])
# batch_indices = tf.reshape(batch_indices, [-1,1])
# indices = tf.concat([batch_indices, indices], axis=1) # [B*L,2]
# gathered_points = tf.gather_nd(points, indices)
# gathered_points = tf.reshape(gathered_points, [B,L,-1])
# return gathered_points
# def batch_nearest_neighbors(feats1, feats2):
# # feats1.shape = [B,K,D]
# # feats2.shape = [B,L,D]
# K = tf.shape(feats1)[1]
# L = tf.shape(feats2)[1]
# feats1_mat = tf.expand_dims(feats1, axis=2) # [B,K,D] --> [B,K,1,D]
# feats2_mat = tf.expand_dims(feats2, axis=1) # [B,L,D] --> [B,1,L,D]
# feats1_mat = tf.tile(feats1_mat, [1,1,L,1]) # [B,K,L,D]
# feats2_mat = tf.tile(feats2_mat, [1,K,1,1]) # [B,K,L,D]
# distances = tf.reduce_sum(tf.squared_difference(feats1_mat, feats2_mat), axis=-1) # [B,K,L]
# min_dist1 = tf.reduce_min(distances, axis=2) # min_dist1(i) = min_j |feats1(i)- feats2(j)|^2 [B,K]
# arg_min1 = tf.argmin(distances, axis=2, output_type=tf.int32)
# min_dist2 = tf.reduce_min(distances, axis=1) # [B,L]
# arg_min2 = tf.argmin(distances, axis=1, output_type=tf.int32)
# return min_dist1, arg_min1, min_dist2, arg_min2
def nearest_neighbors(feats1, feats2):
# feats1.shape = [K,D]
# feats2.shape = [L,D]
K = tf.shape(feats1)[0]
L = tf.shape(feats2)[0]
feats1_mat = tf.expand_dims(feats1, axis=1) # [K,D] --> [K,1,D]
feats2_mat = tf.expand_dims(feats2, axis=0) # [K,D] --> [1,L,D]
feats1_mat = tf.tile(feats1_mat, [1,L,1]) # [K,L,D]
feats2_mat = tf.tile(feats2_mat, [K,1,1]) # [K,L,D]
distances = tf.reduce_sum(tf.squared_difference(feats1_mat, feats2_mat), axis=-1)
min_dist1 = tf.reduce_min(distances, axis=1) # min_dist1(i) = min_j |feats1(i)- feats2(j)|^2
arg_min1 = tf.argmin(distances, axis=1)
min_dist2 = tf.reduce_min(distances, axis=0)
arg_min2 = tf.argmin(distances, axis=0)
return min_dist1, arg_min1, min_dist2, arg_min2, distances
# def nearest_neighbors_less_memory(feats1, feats2, back_prop=False, num_parallel=10):
# # min_dist(i) = min_j |feats1(i)-feats(j|**2
# # arg_min(i) = arg min_j |feats1(i)-feats(j|**2
# # Less memory but too slow on notebook but why ?
# N = tf.shape(feats1)[0]
# ta_dist = tf.TensorArray(dtype=tf.float32, size=N)
# ta_inds = tf.TensorArray(dtype=tf.int32, size=N)
# init_state = (0, ta_dist, ta_inds)
# condition = lambda i, _, _2: i < N
# def body(i, ta_dist, ta_inds):
# dists = tf.reduce_sum( tf.squared_difference(feats1[i], feats2), axis=1)
# min_dist = tf.reduce_min(dists)
# min_inds = tf.cast(tf.argmin(dists), tf.int32)
# return i+1, ta_dist.write(i, min_dist), ta_inds.write(i, min_inds)
# n, ta_dist_final, ta_inds_final = tf.while_loop(condition, body, init_state,
# parallel_iterations=num_parallel, back_prop=back_prop)
# min_dist = ta_dist_final.stack()
# min_inds = ta_inds_final.stack()
# return min_dist, min_inds
def extract_keypoints(top_k):
coords = tf.where(tf.greater(top_k, 0.))
num_kpts = tf.reduce_sum(top_k, axis=[1,2,3])
coords = tf.cast(coords, tf.int32)
batch_inds, kp_y, kp_x, _ = tf.split(coords, 4, axis=-1)
batch_inds = tf.reshape(batch_inds, [-1])
kpts = tf.concat([kp_x, kp_y], axis=1)
num_kpts = tf.cast(num_kpts, tf.int32)
# kpts: [N,2] (N=B*K)
# batch_inds: N,
# num_kpts: B
return kpts, batch_inds, num_kpts
def extract_patches_from_keypoints(feat_maps, kpts, batch_inds, crop_radius, patch_size):
# feat_maps: [B,H,W,C]
# kpts: [N,2]
# batch_inds: [N,]
# crop_radius, patch_size: scalar
patch_size = (patch_size, patch_size)
with tf.name_scope('extract_patches_from_keypoints'):
kp_x, kp_y = tf.split(kpts, 2, axis=-1)
bboxes = tf.cast(tf.concat([kp_y-crop_radius, kp_x-crop_radius, kp_y+crop_radius, kp_x+crop_radius],
axis=1), tf.float32)# [num_boxes, 4]
# normalize bounding boxes
height = tf.cast(tf.shape(feat_maps)[1], tf.float32)
width = tf.cast(tf.shape(feat_maps)[2], tf.float32)
inv_imsizes = tf.stack([1./height, 1./width, 1./height, 1./width])[None] # [1,4]
bboxes = bboxes * inv_imsizes
crop_patches = tf.image.crop_and_resize(feat_maps, bboxes, batch_inds, patch_size)
return crop_patches
# def extract_patches_from_keypoints(feat_maps, top_k, crop_radius, patch_size):
# patch_size = (patch_size, patch_size)
# with tf.name_scope('extract_patches_from_keypoints'):
# coords = tf.where(tf.greater(top_k, 0.))
# coords = tf.cast(coords, tf.int32)
# box_ind, kp_y, kp_x, _ = tf.split(coords, 4, axis=-1)
# box_ind = tf.reshape(box_ind, [-1])
# kpts = tf.concat([kp_x, kp_y], axis=1)
# bboxes = tf.cast(tf.concat([kp_y-crop_radius, kp_x-crop_radius, kp_y+crop_radius, kp_x+crop_radius],
# axis=1), tf.float32)# [num_boxes, 4]
# # normalize bounding boxes
# height = tf.cast(tf.shape(feat_maps)[1], tf.float32)
# width = tf.cast(tf.shape(feat_maps)[2], tf.float32)
# inv_imsizes = tf.stack([1./height, 1./width, 1./height, 1./width])[None] # [1,4]
# bboxes = bboxes * inv_imsizes
# crop_patches = tf.image.crop_and_resize(feat_maps, bboxes, box_ind, patch_size)
# return crop_patches, kpts, box_ind
def make_intrinsics_3x3(fx, fy, cx, cy):
# non-batch inputs, outputs
# inputs are scalar, output is 3x3 tensor
r1 = tf.expand_dims(tf.stack([fx, 0., cx]), axis=0) # [1,3]
r2 = tf.expand_dims(tf.stack([0., fy, cy]), axis=0)
r3 = tf.constant([0.,0.,1.], shape=[1, 3])
intrinsics = tf.concat([r1, r2, r3], axis=0)
return intrinsics
def get_gauss_filter_weight(ksize, sig):
mu_x = mu_y = ksize//2
if sig == 0:
psf = np.zeros((ksize, ksize), dtype=np.float32)
psf[mu_y,mu_x] = 1.0
else:
xy = np.indices((ksize,ksize))
x = xy[1,:,:]
y = xy[0,:,:]
psf = np.exp(-((x-mu_x)**2/(2*sig**2) + (y-mu_y)**2/(2*sig**2)))
return psf
def spatial_softmax(logits, ksize, com_strength=1.0):
max_logits = tf.nn.max_pool(logits, [1,ksize,ksize, 1],
strides=[1,1,1,1], padding='SAME')
sum_filter = tf.constant(np.ones((ksize,ksize,1,1)), dtype=tf.float32)
ex = tf.exp(com_strength * (logits - max_logits))
sum_ex = tf.nn.conv2d(ex, sum_filter, [1,1,1,1], padding='SAME')
probs = ex / (sum_ex + 1e-6)
return probs
def soft_nms_3d(scale_logits, ksize, com_strength=1.0):
# apply softmax on scalespace logits
# scale_logits: [B,H,W,S]
num_scales = scale_logits.get_shape().as_list()[-1]
scale_logits_d = tf.transpose(scale_logits[...,None], [0,3,1,2,4]) # [B,S,H,W,1] in order to apply pool3d
max_maps = tf.nn.max_pool3d(scale_logits_d, [1,num_scales,ksize,ksize,1], [1,num_scales,1,1,1], padding='SAME')
max_maps = tf.transpose(max_maps[...,0], [0,2,3,1]) # [B,H,W,S]
exp_maps = tf.exp(com_strength * (scale_logits-max_maps))
exp_maps_d = tf.transpose(exp_maps[...,None], [0,3,1,2,4]) # [B,S,H,W,1]
sum_filter = tf.constant(np.ones((num_scales, ksize, ksize, 1, 1)), dtype=tf.float32)
sum_ex = tf.nn.conv3d(exp_maps_d, sum_filter, [1,num_scales,1,1,1], padding='SAME')
sum_ex = tf.transpose(sum_ex[...,0], [0,2,3,1]) # [B,H,W,S]
probs = exp_maps / (sum_ex + 1e-6)
return probs
def instance_normalization(inputs):
# normalize 0-means 1-variance in each sample (not take batch-axis)
inputs_dim = inputs.get_shape().ndims
# Epsilon to be used in the tf.nn.batch_normalization
var_eps = 1e-3
if inputs_dim == 4:
moments_dims = [1,2] # NHWC format
elif inputs_dim == 2:
moments_dims = [1]
else:
raise ValueError('instance_normalization suppose input dim is 4: inputs_dim={}\n'.format(inputs_dim))
mean, variance = tf.nn.moments(inputs, axes=moments_dims, keep_dims=True)
outputs = tf.nn.batch_normalization(inputs, mean, variance, None, None, var_eps) # non-parametric normalization
return outputs
def non_max_suppression(inputs, thresh=0.0, ksize=3, dtype=tf.float32, name='NMS'):
with tf.name_scope(name): # add namespace to keep graph clean
dtype = inputs.dtype
batch = tf.shape(inputs)[0]
height = tf.shape(inputs)[1]
width = tf.shape(inputs)[2]
channel = tf.shape(inputs)[3]
hk = ksize // 2
zeros = tf.zeros_like(inputs)
works = tf.where(tf.less(inputs, thresh), zeros, inputs)
works_pad = tf.pad(works, [[0,0], [2*hk,2*hk], [2*hk,2*hk], [0,0]], mode='CONSTANT')
map_augs = []
for i in range(ksize):
for j in range(ksize):
curr_in = tf.slice(works_pad, [0, i, j, 0], [-1, height+2*hk, width+2*hk, -1])
map_augs.append(curr_in)
num_map = len(map_augs) # ksize*ksize
center_map = map_augs[num_map//2]
peak_mask = tf.greater(center_map, map_augs[0])
for n in range(1, num_map):
if n == num_map // 2:
continue
peak_mask = tf.logical_and(peak_mask, tf.greater(center_map, map_augs[n]))
peak_mask = tf.slice(peak_mask, [0,hk,hk,0],[-1,height,width,-1])
if dtype != tf.bool:
peak_mask = tf.cast(peak_mask, dtype=dtype)
peak_mask.set_shape(inputs.shape) # keep shape information
return peak_mask
# def make_top_k_sparse_tensor(heatmaps, k=256):
# batch_size = tf.shape(heatmaps)[0]
# _, height, width, channel = heatmaps.get_shape().as_list()
# heatmaps_flt = tf.reshape(heatmaps, [batch_size, -1])
# values, indices = tf.nn.top_k(heatmaps_flt, k=k, sorted=False)
# boffset = tf.expand_dims(tf.range(batch_size) * width * height, axis=1)
# indices = indices + boffset
# indices = tf.reshape(indices, [-1])
# top_k_maps = tf.sparse_to_dense(indices, [batch_size*height*width*channel], 1, 0, validate_indices=False)
# top_k_maps = tf.reshape(top_k_maps, [batch_size, height, width, 1])
# return tf.cast(top_k_maps, tf.float32)
def make_top_k_sparse_tensor(heatmaps, k=256, get_kpts=False):
batch_size = tf.shape(heatmaps)[0]
height = tf.shape(heatmaps)[1]
width = tf.shape(heatmaps)[2]
heatmaps_flt = tf.reshape(heatmaps, [batch_size, -1])
imsize = tf.shape(heatmaps_flt)[1]
values, xy_indices = tf.nn.top_k(heatmaps_flt, k=k, sorted=False)
boffset = tf.expand_dims(tf.range(batch_size) * imsize, axis=1)
indices = xy_indices + boffset
indices = tf.reshape(indices, [-1])
top_k_maps = tf.sparse_to_dense(indices, [batch_size*imsize], 1, 0, validate_indices=False)
top_k_maps = tf.reshape(top_k_maps, [batch_size, height, width, 1])
top_k_maps = tf.cast(top_k_maps, tf.float32)
if get_kpts:
kpx = tf.mod(xy_indices, width)
kpy = xy_indices // width
batch_inds = tf.tile(tf.range(batch_size, dtype=tf.int32)[:,None], [1,k])
kpts = tf.concat([tf.reshape(kpx, [-1,1]), tf.reshape(kpy, [-1,1])], axis=1) # B*K,2
batch_inds = tf.reshape(batch_inds, [-1])
num_kpts = tf.ones([batch_size], dtype=tf.int32) * k
return top_k_maps, kpts, batch_inds, num_kpts
else:
return top_k_maps
def d_softargmax(d_heatmaps, block_size, com_strength=10):
# d_heatmaps = [batch, height/N, width/N, N**2]
# fgmask = [batch, height/N, width/N]
pos_array_x, pos_array_y = tf.meshgrid(tf.range(block_size), tf.range(block_size))
pos_array_x = tf.cast(tf.reshape(pos_array_x, [-1]), tf.float32)
pos_array_y = tf.cast(tf.reshape(pos_array_y, [-1]), tf.float32)
max_out = tf.reduce_max(
d_heatmaps, axis=-1, keep_dims=True)
o = tf.exp(com_strength * (d_heatmaps - max_out)) # + eps
sum_o = tf.reduce_sum(
o, axis=-1, keep_dims=True)
x = tf.reduce_sum(
o * tf.reshape(pos_array_x, [1, 1, 1, -1]),
axis=-1, keep_dims=True
) / sum_o
y = tf.reduce_sum(
o * tf.reshape(pos_array_y, [1, 1, 1, -1]),
axis=-1, keep_dims=True
) / sum_o
# x,y shape = [B,H,W,1]
coords = tf.concat([x, y], axis=-1)
# x = tf.squeeze(x, axis=-1)
# y = tf.squeeze(y, axis=-1)
return coords
def softargmax(score_map, com_strength=10):
# out.shape = [batch, height, width, 1]
height = tf.shape(score_map)[1]
width = tf.shape(score_map)[2]
md = len(score_map.shape)
# CoM to get the coordinates
pos_array_x = tf.cast(tf.range(height), dtype=tf.float32)
pos_array_y = tf.cast(tf.range(height), dtype=tf.float32)
max_out = tf.reduce_max(
score_map, axis=list(range(1, md)), keep_dims=True)
o = tf.exp(com_strength * (score_map - max_out)) # + eps
sum_o = tf.reduce_sum(
o, axis=list(range(1, md)), keep_dims=True)
x = tf.reduce_sum(
o * tf.reshape(pos_array_x, [1, 1, -1, 1]),
axis=list(range(1, md)), keep_dims=True
) / sum_o
y = tf.reduce_sum(
o * tf.reshape(pos_array_y, [1, -1, 1, 1]),
axis=list(range(1, md)), keep_dims=True
) / sum_o
# Remove the unecessary dimensions (i.e. flatten them)
x = tf.reshape(x, (-1,))
y = tf.reshape(y, (-1,))
return x, y
##--------------------------
## Bilinear Inverse Warping
##--------------------------
def meshgrid(batch, height, width, is_homogeneous=True):
"""Construct a 2D meshgrid.
Args:
batch: batch size
height: height of the grid
width: width of the grid
is_homogeneous: whether to return in homogeneous coordinates
Returns:
x,y grid coordinates [batch, 2 (3 if homogeneous), height, width]
"""
x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])),
tf.transpose(tf.expand_dims(
tf.linspace(-1.0, 1.0, width), 1), [1, 0]))
y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1),
tf.ones(shape=tf.stack([1, width])))
x_t = (x_t + 1.0) * 0.5 * tf.cast(width - 1, tf.float32)
y_t = (y_t + 1.0) * 0.5 * tf.cast(height - 1, tf.float32)
if is_homogeneous:
ones = tf.ones_like(x_t)
coords = tf.stack([x_t, y_t, ones], axis=0)
else:
coords = tf.stack([x_t, y_t], axis=0)
coords = tf.tile(tf.expand_dims(coords, 0), [batch, 1, 1, 1])
return coords
# def pixel2cam(depths, pixel_coords, inv_intrinsics_3x3, is_homogeneous=True):
# """Transforms coordinates in the pixel frame to the camera frame.
# Args:
# depths: [batch, height, width]
# pixel_coords: homogeneous pixel coordinates [batch, 3, height, width]
# intrinsics: camera intrinsics [batch, 3, 3]
# is_homogeneous: return in homogeneous coordinates
# Returns:
# Coords in the camera frame [batch, 3 (4 if homogeneous), height, width]
# """
# batch = tf.shape(depths)[0]
# height = tf.shape(depths)[1]
# width = tf.shape(depths)[2]
# depths = tf.reshape(depths, [batch, 1, -1])
# pixel_coords = tf.reshape(pixel_coords, [batch, 3, -1])
# inv_intrinsics = tf.tile(tf.expand_dims(inv_intrinsics_3x3, axis=0), [batch, 1, 1])
# cam_coords = tf.matmul(inv_intrinsics, pixel_coords) * depths
# if is_homogeneous:
# ones = tf.ones([batch, 1, height*width])