forked from WangYixuan12/d3fields
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfusion.py
1780 lines (1564 loc) · 89.3 KB
/
fusion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
sys.path.append('/home/yixuan/general_dp/diffusion_policy/d3fields_dev')
import time
import torch
import torch.nn.functional as F
import torchvision.transforms as T
import numpy as np
from tqdm import tqdm
from PIL import Image
import plotly.graph_objects as go
import pickle
from matplotlib import cm
import matplotlib.pyplot as plt
import cv2
import mcubes
import trimesh
from PIL import Image
import open3d as o3d
import groundingdino
from groundingdino.util.inference import Model as GroundingDINOModel
from segment_anything import build_sam, SamPredictor
from XMem.model.network import XMem
from XMem.inference.data.mask_mapper import MaskMapper
from XMem.inference.inference_core import InferenceCore
from XMem.dataset.range_transform import im_normalization
from utils.grounded_sam import grounded_instance_sam_new_ver
from utils.draw_utils import draw_keypoints, aggr_point_cloud_from_data
from utils.my_utils import depth2fgpcd, fps_np
def project_points_coords(pts, Rt, K):
"""
:param pts: [pn,3]
:param Rt: [rfn,3,4]
:param K: [rfn,3,3]
:return:
coords: [rfn,pn,2]
invalid_mask: [rfn,pn]
depth: [rfn,pn,1]
"""
pn = pts.shape[0]
hpts = torch.cat([pts,torch.ones([pn,1],device=pts.device,dtype=pts.dtype)],1)
srn = Rt.shape[0]
KRt = K @ Rt # rfn,3,4
last_row = torch.zeros([srn,1,4],device=pts.device,dtype=pts.dtype)
last_row[:,:,3] = 1.0
H = torch.cat([KRt,last_row],1) # rfn,4,4
pts_cam = H[:,None,:,:] @ hpts[None,:,:,None]
pts_cam = pts_cam[:,:,:3,0]
depth = pts_cam[:,:,2:]
invalid_mask = torch.abs(depth)<1e-4
depth[invalid_mask] = 1e-3
pts_2d = pts_cam[:,:,:2]/depth
return pts_2d, ~(invalid_mask[...,0]), depth
def interpolate_feats(feats, points, h=None, w=None, padding_mode='zeros', align_corners=False, inter_mode='bilinear'):
"""
:param feats: b,f,h,w
:param points: b,n,2
:param h: float
:param w: float
:param padding_mode:
:param align_corners:
:param inter_mode:
:return: feats_inter: b,n,f
"""
b, _, ch, cw = feats.shape
if h is None and w is None:
h, w = ch, cw
x_norm = points[:, :, 0] / (w - 1) * 2 - 1
y_norm = points[:, :, 1] / (h - 1) * 2 - 1
points_norm = torch.stack([x_norm, y_norm], -1).unsqueeze(1) # [srn,1,n,2]
feats_inter = F.grid_sample(feats, points_norm, mode=inter_mode, padding_mode=padding_mode, align_corners=align_corners).squeeze(2) # srn,f,n
feats_inter = feats_inter.permute(0,2,1)
return feats_inter
def create_init_grid(boundaries, step_size):
x_lower, x_upper = boundaries['x_lower'], boundaries['x_upper']
y_lower, y_upper = boundaries['y_lower'], boundaries['y_upper']
z_lower, z_upper = boundaries['z_lower'], boundaries['z_upper']
x = torch.arange(x_lower, x_upper, step_size, dtype=torch.float32) + step_size / 2
y = torch.arange(y_lower, y_upper, step_size, dtype=torch.float32) + step_size / 2
z = torch.arange(z_lower, z_upper, step_size, dtype=torch.float32) + step_size / 2
xx, yy, zz = torch.meshgrid(x, y, z)
coords = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3)
return coords, xx.shape
def instance2onehot(instance, N = None):
# :param instance: [**dim] numpy array uint8, val from 0 to N-1
# :return: [**dim, N] numpy array bool
if N is None:
N = instance.max() + 1
if type(instance) is np.ndarray:
assert instance.dtype == np.uint8
out = np.zeros(instance.shape + (N,), dtype=bool)
for i in range(N):
out[..., i] = (instance == i)
elif type(instance) is torch.Tensor:
assert instance.dtype == torch.uint8
# assert instance.min() == 0
out = torch.zeros(instance.shape + (N,), dtype=torch.bool, device=instance.device)
for i in range(N):
out[..., i] = (instance == i)
return out
def onehot2instance(one_hot_mask):
# :param one_hot_mask: [**dim, N] numpy array float32 or bool (probalistic or not)
# :return: [**dim] numpy array uint8, val from 0 to N-1
if type(one_hot_mask) == np.ndarray:
return np.argmax(one_hot_mask, axis=-1).astype(np.uint8)
elif type(one_hot_mask) == torch.Tensor:
return torch.argmax(one_hot_mask, dim=-1).to(dtype=torch.uint8)
else:
raise NotImplementedError
def _init_low_level_memory(lower_bound, higher_bound, voxel_size, voxel_num):
def pcd_to_voxel(pcds):
if type(pcds) == list:
pcds = np.array(pcds)
# The pc is in numpy array with shape (..., 3)
# The voxel is in numpy array with shape (..., 3)
voxels = np.floor((pcds - lower_bound) / voxel_size).astype(np.int32)
return voxels
def voxel_to_pcd(voxels):
if type(voxels) == list:
voxels = np.array(voxels)
# The voxel is in numpy array with shape (..., 3)
# The pc is in numpy array with shape (..., 3)
pcds = voxels * voxel_size + lower_bound
return pcds
def voxel_to_index(voxels):
if type(voxels) == list:
voxels = np.array(voxels)
# The voxel is in numpy array with shape (..., 3)
# The index is in numpy array with shape (...,)
indexes = (
voxels[..., 0] * voxel_num[1] * voxel_num[2]
+ voxels[..., 1] * voxel_num[2]
+ voxels[..., 2]
)
return indexes
def index_to_voxel(indexes):
if type(indexes) == list:
indexes = np.array(indexes)
# The index is in numpy array with shape (...,)
# The voxel is in numpy array with shape (..., 3)
voxels = np.zeros((indexes.shape + (3,)), dtype=np.int32)
voxels[..., 2] = indexes % voxel_num[2]
indexes = indexes // voxel_num[2]
voxels[..., 1] = indexes % voxel_num[1]
voxels[..., 0] = indexes // voxel_num[1]
return voxels
def pcd_to_index(pcds):
# The pc is in numpy array with shape (..., 3)
# The index is in numpy array with shape (...,)
voxels = pcd_to_voxel(pcds)
indexes = voxel_to_index(voxels)
return indexes
def index_to_pcd(indexes):
# The index is in numpy array with shape (...,)
# The pc is in numpy array with shape (..., 3)
voxels = index_to_voxel(indexes)
pcds = voxel_to_pcd(voxels)
return pcds
return (
pcd_to_voxel,
voxel_to_pcd,
voxel_to_index,
index_to_voxel,
pcd_to_index,
index_to_pcd,
)
def rm_mask_close_to_pcd(depth, mask, pcd, K, pose):
# remove the mask that is close to the pcd
# the mask is in the camera frame with intrinsics K and pose
# the pcd is in the world frame
# :param depth: (H, W) numpy array float32
# :param mask: (H, W) numpy array bool
# :param pcd: (N, 3) numpy array float32
# :param K: (3, 3) numpy array float32
# :param pose: (4, 4) numpy array float32, that transforms points from world frame to camera frame
# :return: (H, W) numpy array bool
cam_params = [K[0, 0], K[1, 1], K[0, 2], K[1, 2]]
pcd_in_cam = depth2fgpcd(depth=depth, mask=mask, cam_params=cam_params, preserve_zero=True)
pcd_in_world = np.linalg.inv(pose) @ np.concatenate([pcd_in_cam, np.ones([pcd_in_cam.shape[0], 1])], axis=-1).T # [4, N]
pcd_in_world = pcd_in_world[:3].T # [N, 3]
close_mask = np.linalg.norm(pcd_in_world[:, None, :] - pcd[None, ...], axis=-1).min(axis=-1) < 0.02
mask_idx = np.where(mask)
filter_mask_idx = (mask_idx[0][close_mask], mask_idx[1][close_mask])
mask[filter_mask_idx] = False
return mask
class Fusion():
def __init__(self, num_cam, feat_backbone='dinov2', device='cuda:0', dtype=torch.float32):
self.device = device
self.dtype = dtype
# hyper-parameters
self.mu = 0.02
# curr_obs_torch is a dict contains:
# - 'dino_feats': (K, patch_h, patch_w, feat_dim) torch tensor, dino features
# - 'depth': (K, H, W) torch tensor, depth images
# - 'pose': (K, 4, 4) torch tensor, poses of the images
# - 'K': (K, 3, 3) torch tensor, intrinsics of the images
self.curr_obs_torch = {}
self.H = -1
self.W = -1
self.num_cam = num_cam
# dino feature extractor
self.feat_backbone = feat_backbone
if self.feat_backbone == 'dinov2':
self.dinov2_feat_extractor = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14').to(self.device)
else:
raise NotImplementedError
self.dinov2_feat_extractor.eval()
self.dinov2_feat_extractor.to(dtype=self.dtype)
# load GroundedSAM model
curr_path = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(groundingdino.__path__[0], 'config/GroundingDINO_SwinT_OGC.py')
grounded_checkpoint = os.path.join(curr_path, 'ckpts/groundingdino_swint_ogc.pth')
# config_file = os.path.join(curr_path, '../gdino_config/GroundingDINO_SwinB.cfg.py')
# grounded_checkpoint = os.path.join(curr_path, 'ckpts/groundingdino_swinb_cogcoor.pth')
if not os.path.exists(grounded_checkpoint):
print('Downloading GroundedSAM model...')
ckpts_dir = os.path.join(curr_path, 'ckpts')
os.system(f'mkdir -p {ckpts_dir}')
# os.system('wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha2/groundingdino_swinb_cogcoor.pth')
# os.system(f'mv groundingdino_swinb_cogcoor.pth {ckpts_dir}')
os.system('wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth')
os.system(f'mv groundingdino_swint_ogc.pth {ckpts_dir}')
sam_checkpoint = os.path.join(curr_path, 'ckpts/sam_vit_h_4b8939.pth')
if not os.path.exists(sam_checkpoint):
print('Downloading SAM model...')
ckpts_dir = os.path.join(curr_path, 'ckpts')
os.system(f'mkdir -p {ckpts_dir}')
os.system('wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth')
os.system(f'mv sam_vit_h_4b8939.pth {ckpts_dir}')
self.ground_dino_model = GroundingDINOModel(config_file, grounded_checkpoint, device=self.device)
self.sam_model = SamPredictor(build_sam(checkpoint=sam_checkpoint))
self.sam_model.model = self.sam_model.model.to(self.device)
# load XMem model
XMem_path = os.path.join(curr_path, 'XMem/saves/XMem.pth')
if not os.path.exists(XMem_path):
print('Downloading XMem model...')
ckpts_dir = os.path.join(curr_path, 'XMem/saves')
os.system(f'mkdir -p {ckpts_dir}')
os.system(f'wget https://github.com/hkchengrex/XMem/releases/download/v1.0/XMem.pth')
os.system(f'mv XMem.pth {ckpts_dir}')
xmem_config = {
'model': XMem_path,
'disable_long_term': False,
'enable_long_term': True,
'max_mid_term_frames': 10,
'min_mid_term_frames': 5,
'max_long_term_elements': 10000,
'num_prototypes': 128,
'top_k': 30,
'mem_every': 5,
'deep_update_every': -1,
'save_scores': False,
'size': 480,
'key_dim': 64,
'value_dim': 512,
'hidden_dim': 64,
'enable_long_term_count_usage': True,
}
network = XMem(xmem_config, xmem_config['model']).to(self.device).eval()
model_weights = torch.load(xmem_config['model'])
network.load_weights(model_weights, init_as_zero_if_needed=True)
self.xmem_mapper = MaskMapper()
self.xmem_processors = [InferenceCore(network, config=xmem_config) for _ in range(self.num_cam)]
if xmem_config['size'] < 0:
self.xmem_im_transform = T.Compose([
T.ToTensor(),
im_normalization,
])
self.xmem_mask_transform = None
else:
self.xmem_im_transform = T.Compose([
T.ToTensor(),
im_normalization,
T.Resize(xmem_config['size'], interpolation=T.InterpolationMode.BILINEAR),
])
self.xmem_mask_transform = T.Compose([
T.Resize(xmem_config['size'], interpolation=T.InterpolationMode.NEAREST),
])
self.xmem_first_mask_loaded = False
self.track_ids = [0]
def eval(self, pts, return_names=['dino_feats', 'mask'], return_inter=False):
# :param pts: (N, 3) torch tensor in world frame
# :param return_names: a set of {'dino_feats', 'mask'}
# :return: output: dict contains:
# - 'dist': (N) torch tensor, dist to the closest point on the surface
# - 'dino_feats': (N, f) torch tensor, the features of the points
# - 'mask': (N, NQ) torch tensor, the query masks of the points
# - 'valid_mask': (N) torch tensor, whether the point is valid
try:
assert len(self.curr_obs_torch) > 0
except:
print('Please call update() first!')
exit()
assert type(pts) == torch.Tensor
assert len(pts.shape) == 2
assert pts.shape[1] == 3
# transform pts to camera pixel coords and get the depth
pts_2d, valid_mask, pts_depth = project_points_coords(pts, self.curr_obs_torch['pose'], self.curr_obs_torch['K'])
pts_depth = pts_depth[...,0] # [rfn,pn]
# get interpolated depth and features
inter_depth = interpolate_feats(self.curr_obs_torch['depth'].unsqueeze(1),
pts_2d,
h = self.H,
w = self.W,
padding_mode='zeros',
align_corners=True,
inter_mode='nearest')[...,0] # [rfn,pn,1]
# inter_normal = interpolate_feats(self.curr_obs_torch['normals'].permute(0,3,1,2),
# pts_2d,
# h = self.H,
# w = self.W,
# padding_mode='zeros',
# align_corners=True,
# inter_mode='bilinear') # [rfn,pn,3]
# compute the distance to the closest point on the surface
dist = inter_depth - pts_depth # [rfn,pn]
dist_valid = (inter_depth > 0.0) & valid_mask & (dist > -self.mu) # [rfn,pn]
# distance-based weight
dist_weight = torch.exp(torch.clamp(self.mu-torch.abs(dist), max=0) / self.mu) # [rfn,pn]
# # normal-based weight
# fxfy = [torch.Tensor([self.curr_obs_torch['K'][i,0,0].item(), self.curr_obs_torch['K'][i,1,1].item()]) for i in range(self.num_cam)] # [rfn, 2]
# fxfy = torch.stack(fxfy, dim=0).to(self.device) # [rfn, 2]
# view_dir = pts_2d / fxfy[:, None, :] # [rfn,pn,2]
# view_dir = torch.cat([view_dir, torch.ones_like(view_dir[...,0:1])], dim=-1) # [rfn,pn,3]
# view_dir = view_dir / torch.norm(view_dir, dim=-1, keepdim=True) # [rfn,pn,3]
# dist_weight = torch.abs(torch.sum(view_dir * inter_normal, dim=-1)) # [rfn,pn]
# dist_weight = dist_weight * dist_valid.float() # [rfn,pn]
dist = torch.clamp(dist, min=-self.mu, max=self.mu) # [rfn,pn]
# # weighted distance
# dist = (dist * dist_weight).sum(0) / (dist_weight.sum(0) + 1e-6) # [pn]
# valid-weighted distance
dist = (dist * dist_valid.float()).sum(0) / (dist_valid.float().sum(0) + 1e-6) # [pn]
dist_all_invalid = (dist_valid.float().sum(0) == 0) # [pn]
dist[dist_all_invalid] = 1e3
outputs = {'dist': dist,
'valid_mask': ~dist_all_invalid}
for k in return_names:
inter_k = interpolate_feats(self.curr_obs_torch[k].permute(0,3,1,2),
pts_2d,
h = self.H,
w = self.W,
padding_mode='zeros',
align_corners=True,
inter_mode='bilinear') # [rfn,pn,k_dim]
# weighted sum
# val = (inter_k * dist_weight.unsqueeze(-1)).sum(0) / (dist_weight.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,k_dim]
# # valid-weighted sum
val = (inter_k * dist_valid.float().unsqueeze(-1) * dist_weight.unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,k_dim]
val[dist_all_invalid] = 0.0
outputs[k] = val
if return_inter:
outputs[k+'_inter'] = inter_k
else:
del inter_k
return outputs
def eval_dist(self, pts):
# this version does not clamp the distance or change the invalid points to 1e3
# this is for grasper planner to find the grasping pose that does not penalize the depth
# :param pts: (N, 3) torch tensor in world frame
# :return: output: dict contains:
# - 'dist': (N) torch tensor, dist to the closest point on the surface
try:
assert len(self.curr_obs_torch) > 0
except:
print('Please call update() first!')
exit()
assert type(pts) == torch.Tensor
assert len(pts.shape) == 2
assert pts.shape[1] == 3
# transform pts to camera pixel coords and get the depth
pts_2d, valid_mask, pts_depth = project_points_coords(pts, self.curr_obs_torch['pose'], self.curr_obs_torch['K'])
pts_depth = pts_depth[...,0] # [rfn,pn]
# get interpolated depth and features
inter_depth = interpolate_feats(self.curr_obs_torch['depth'].unsqueeze(1),
pts_2d,
h = self.H,
w = self.W,
padding_mode='zeros',
align_corners=True,
inter_mode='nearest')[...,0] # [rfn,pn,1]
# compute the distance to the closest point on the surface
dist = inter_depth - pts_depth # [rfn,pn]
dist_valid = (inter_depth > 0.0) & valid_mask # [rfn,pn]
# valid-weighted distance
dist = (dist * dist_valid.float()).sum(0) / (dist_valid.float().sum(0) + 1e-6) # [pn]
dist_all_invalid = (dist_valid.float().sum(0) == 0) # [pn]
outputs = {'dist': dist,
'valid_mask': ~dist_all_invalid}
return outputs
# if 'dino_feats' in return_names:
# inter_feats = interpolate_feats(self.curr_obs_torch['dino_feats'].permute(0,3,1,2),
# pts_2d,
# h = self.H,
# w = self.W,
# padding_mode='zeros',
# align_corners=True,
# inter_mode='bilinear') # [rfn,pn,feat_dim]
# else:
# inter_feats = None
# if 'mask_shoe' in self.curr_obs_torch and 'mask_shoe' in return_names:
# inter_masks = interpolate_feats(self.curr_obs_torch['mask_shoe'].permute(0,3,1,2),
# pts_2d,
# h = self.H,
# w = self.W,
# padding_mode='zeros',
# align_corners=True,
# inter_mode='nearest') # [rfn,pn,nq]
# else:
# inter_masks = None
# # compute the features of the points
# if 'dino_feats' in return_names:
# features = (inter_feats * dist_valid.float().unsqueeze(-1) * dist_weight.unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,feat_dim]
# # features = (inter_feats * dist_valid.float().unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,feat_dim]
# features[dist_all_invalid] = 0.0
# else:
# features = None
# # compute the query masks of the points
# if inter_masks is not None and 'mask_shoe' in return_names:
# query_masks = (inter_masks * dist_valid.float().unsqueeze(-1) * dist_weight.unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,nq]
# # query_masks = (inter_masks * dist_valid.float().unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,nq]
# query_masks[dist_all_invalid] = 0.0
# else:
# query_masks = None
# return {'dist': dist,
# 'dino_feats': features,
# 'mask_shoe': query_masks,
# 'valid_mask': ~dist_all_invalid}
# if 'dino_feats' in return_names:
# inter_feats = interpolate_feats(self.curr_obs_torch['dino_feats'].permute(0,3,1,2),
# pts_2d,
# h = self.H,
# w = self.W,
# padding_mode='zeros',
# align_corners=True,
# inter_mode='bilinear') # [rfn,pn,feat_dim]
# else:
# inter_feats = None
# if 'mask_shoe' in self.curr_obs_torch and 'mask_shoe' in return_names:
# inter_masks = interpolate_feats(self.curr_obs_torch['mask_shoe'].permute(0,3,1,2),
# pts_2d,
# h = self.H,
# w = self.W,
# padding_mode='zeros',
# align_corners=True,
# inter_mode='nearest') # [rfn,pn,nq]
# else:
# inter_masks = None
# # compute the features of the points
# if 'dino_feats' in return_names:
# features = (inter_feats * dist_valid.float().unsqueeze(-1) * dist_weight.unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,feat_dim]
# # features = (inter_feats * dist_valid.float().unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,feat_dim]
# features[dist_all_invalid] = 0.0
# else:
# features = None
# # compute the query masks of the points
# if inter_masks is not None and 'mask_shoe' in return_names:
# query_masks = (inter_masks * dist_valid.float().unsqueeze(-1) * dist_weight.unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,nq]
# # query_masks = (inter_masks * dist_valid.float().unsqueeze(-1)).sum(0) / (dist_valid.float().sum(0).unsqueeze(-1) + 1e-6) # [pn,nq]
# query_masks[dist_all_invalid] = 0.0
# else:
# query_masks = None
# return {'dist': dist,
# 'dino_feats': features,
# 'mask_shoe': query_masks,
# 'valid_mask': ~dist_all_invalid}
def batch_eval(self, pts, return_names=['dino_feats', 'mask']):
batch_pts = 60000
outputs = {}
for i in range(0, pts.shape[0], batch_pts):
st_idx = i
ed_idx = min(i + batch_pts, pts.shape[0])
out = self.eval(pts[st_idx:ed_idx], return_names=return_names)
for k in out:
if k not in outputs:
outputs[k] = [out[k]]
else:
outputs[k].append(out[k])
# concat the outputs
for k in outputs:
if outputs[k][0] is not None:
outputs[k] = torch.cat(outputs[k], dim=0)
else:
outputs[k] = None
return outputs
# def extract_dist_vol(self, boundaries):
# step = 0.002
# init_grid, grid_shape = create_init_grid(boundaries, step)
# init_grid = init_grid.to(self.device, dtype=torch.float32)
# batch_pts = 10000
# dist_vol = torch.zeros(init_grid.shape[0], dtype=torch.float32, device=self.device)
# valid_mask = torch.zeros(init_grid.shape[0], dtype=torch.bool, device=self.device)
# for i in range(0, init_grid.shape[0], batch_pts):
# st_idx = i
# ed_idx = min(i + batch_pts, init_grid.shape[0])
# out = self.eval(init_grid[st_idx:ed_idx], return_names={})
# dist_vol[st_idx:ed_idx] = out['dist']
# valid_mask[st_idx:ed_idx] = out['valid_mask']
# return {'init_grid': init_grid,
# 'grid_shape': grid_shape,
# 'dist': dist_vol,
# 'valid_mask': valid_mask,}
# def extract_dist_vol(self, boundaries):
# step = 0.002
# init_grid, grid_shape = create_init_grid(boundaries, step)
# init_grid = init_grid.to(self.device, dtype=torch.float32)
# batch_pts = 10000
# dist_vol = torch.zeros(init_grid.shape[0], dtype=torch.float32, device=self.device)
# valid_mask = torch.zeros(init_grid.shape[0], dtype=torch.bool, device=self.device)
# for i in range(0, init_grid.shape[0], batch_pts):
# st_idx = i
# ed_idx = min(i + batch_pts, init_grid.shape[0])
# out = self.eval(init_grid[st_idx:ed_idx], return_names={})
# dist_vol[st_idx:ed_idx] = out['dist']
# valid_mask[st_idx:ed_idx] = out['valid_mask']
# return {'init_grid': init_grid,
# 'grid_shape': grid_shape,
# 'dist': dist_vol,
# 'valid_mask': valid_mask,}
def extract_dinov2_features(self, imgs, params):
K, H, W, _ = imgs.shape
patch_h = params['patch_h']
patch_w = params['patch_w']
# feat_dim = 384 # vits14
# feat_dim = 768 # vitb14
feat_dim = 1024 # vitl14
# feat_dim = 1536 # vitg14
transform = T.Compose([
# T.GaussianBlur(9, sigma=(0.1, 2.0)),
T.Resize((patch_h * 14, patch_w * 14)),
T.CenterCrop((patch_h * 14, patch_w * 14)),
T.ToTensor(),
T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
])
imgs_tensor = torch.zeros((K, 3, patch_h * 14, patch_w * 14), device=self.device)
for j in range(K):
img = Image.fromarray(imgs[j])
imgs_tensor[j] = transform(img)[:3]
with torch.no_grad():
features_dict = self.dinov2_feat_extractor.forward_features(imgs_tensor.to(dtype=self.dtype))
features = features_dict['x_norm_patchtokens']
features = features.reshape((K, patch_h, patch_w, feat_dim))
return features
def extract_features(self, imgs, params):
# :param imgs (K, H, W, 3) np array, color images
# :param params: dict contains:
# - 'patch_h', 'patch_w': int, the size of the patch
# :return features: (K, patch_h, patch_w, feat_dim) np array, features of the images
if self.feat_backbone == 'dinov2':
return self.extract_dinov2_features(imgs, params)
else:
raise NotImplementedError
def xmem_process(self, rgb, mask):
# track the mask using XMem
# :param: rgb: (K, H, W, 3) np array, color image
# :param: mask: None or (K, H, W) torch tensor, mask
# return: out_masks: (K, H, W) torch tensor, mask
# rgb_tensor = torch.zeros((self.num_cam, 3, self.H, self.W), device=self.device, dtype=torch.float32)
with torch.no_grad():
rgb_tensor = []
for i in range(self.num_cam):
rgb_tensor.append(self.xmem_im_transform(rgb[i]).to(self.device, dtype=torch.float32))
rgb_tensor = torch.stack(rgb_tensor, dim=0)
if self.xmem_mask_transform is not None and mask is not None:
mask = self.xmem_mask_transform(mask).to(self.device, dtype=torch.float32)
if mask is not None and not self.xmem_first_mask_loaded:
# converted_masks = []
for i in range(self.num_cam):
_, labels = self.xmem_mapper.convert_mask(mask[i].cpu().numpy(), exhaustive=True)
# converted_masks.append(converted_mask)
converted_masks = [self.xmem_mapper.convert_mask(mask[i].cpu().numpy(), exhaustive=True)[0] for i in range(self.num_cam)]
# # assume that labels for all views are the same
# for labels in labels_list:
# assert labels == labels_list[0]
converted_masks = torch.from_numpy(np.stack(converted_masks, axis=0)).to(self.device, dtype=torch.float32)
for processor in self.xmem_processors:
processor.set_all_labels(list(self.xmem_mapper.remappings.values()))
self.track_ids = [0,] + list(self.xmem_mapper.remappings.values())
elif mask is not None and self.xmem_first_mask_loaded:
converted_masks = instance2onehot(mask.to(torch.uint8), len(self.track_ids))
converted_masks = converted_masks.permute(0, 3, 1, 2).to(self.device, dtype=torch.float32)
converted_masks = converted_masks[:, 1:] # remove the background
if not self.xmem_first_mask_loaded:
if mask is not None:
self.xmem_first_mask_loaded = True
else:
# no point to do anything without a mask
raise ValueError('No mask provided for the first frame')
out_masks = torch.zeros((self.num_cam, self.H, self.W)).to(self.device, dtype=torch.uint8)
for view_i, processor in enumerate(self.xmem_processors):
prob = processor.step(rgb_tensor[view_i],
converted_masks[view_i] if mask is not None else None,
self.track_ids[1:] if mask is not None else None,
end=False)
prob = F.interpolate(prob.unsqueeze(1), (self.H, self.W), mode='bilinear', align_corners=False)[:,0]
out_mask = torch.argmax(prob, dim=0)
out_mask = (out_mask.detach().cpu().numpy()).astype(np.uint8)
out_mask = self.xmem_mapper.remap_index_mask(out_mask)
# out_mask = instance2onehot(out_mask)
out_masks[view_i] = torch.from_numpy(out_mask).to(self.device, dtype=torch.uint8)
out_masks = instance2onehot(out_masks, len(self.track_ids))
return out_masks.to(self.device, dtype=self.dtype)
def update(self, obs):
# :param obs: dict contains:
# - 'color': (K, H, W, 3) np array, color image
# - 'depth': (K, H, W) np array, depth image
# - 'pose': (K, 4, 4) np array, camera pose
# - 'K': (K, 3, 3) np array, camera intrinsics
self.num_cam = obs['color'].shape[0]
color = obs['color']
params = {
'patch_h': color.shape[1] // 10,
'patch_w': color.shape[2] // 10,
}
features = self.extract_features(color, params)
# self.curr_obs_torch = {
# 'dino_feats': features,
# 'color': color,
# 'depth': torch.from_numpy(obs['depth']).to(self.device, dtype=torch.float32),
# 'pose': torch.from_numpy(obs['pose']).to(self.device, dtype=torch.float32),
# 'K': torch.from_numpy(obs['K']).to(self.device, dtype=torch.float32),
# }
self.curr_obs_torch['dino_feats'] = features
self.curr_obs_torch['color'] = color
self.curr_obs_torch['color_tensor'] = torch.from_numpy(color).to(self.device, dtype=self.dtype) / 255.0
self.curr_obs_torch['depth'] = torch.from_numpy(obs['depth']).to(self.device, dtype=self.dtype)
self.curr_obs_torch['pose'] = torch.from_numpy(obs['pose']).to(self.device, dtype=self.dtype)
self.curr_obs_torch['K'] = torch.from_numpy(obs['K']).to(self.device, dtype=self.dtype)
_, self.H, self.W = obs['depth'].shape
def voxel_downsample(self, pcd, voxel_size):
# :param pcd: [N,3] numpy array
# :param voxel_size: float
# :return: [M,3] numpy array
pcd = o3d.geometry.PointCloud(o3d.utility.Vector3dVector(pcd))
pcd_down = pcd.voxel_down_sample(voxel_size)
return np.asarray(pcd_down.points)
def pcd_iou(self, pcd_1, pcd_2, threshold):
# :param pcd_1 [N,3] numpy array
# :param pcd_2 [M,3] numpy array
# voxel downsample
# voxel_size = threshold
# pcd_1 = self.voxel_downsample(pcd_1, voxel_size)
# pcd_2 = self.voxel_downsample(pcd_2, voxel_size)
dist = np.linalg.norm(pcd_1[:,None] - pcd_2[None], axis=-1) # [N,M]
min_dist_from_1_to_2 = dist.min(axis=1) # [N]
min_idx_from_1_to_2 = dist.argmin(axis=1) # [N]
min_dist_from_2_to_1 = dist.min(axis=0) # [M]
min_idx_from_2_to_1 = dist.argmin(axis=0) # [M]
iou = ((min_dist_from_1_to_2 < threshold).sum() + (min_dist_from_2_to_1 < threshold).sum()) / (pcd_1.shape[0] + pcd_2.shape[0])
iou_1 = (min_dist_from_1_to_2 < threshold).sum() / pcd_1.shape[0]
iou_2 = (min_dist_from_2_to_1 < threshold).sum() / pcd_2.shape[0]
overlap_idx_1 = np.where(min_dist_from_1_to_2 < threshold)[0]
overlap_idx_2 = np.where(min_dist_from_2_to_1 < threshold)[0]
return iou, iou_1, iou_2, overlap_idx_1, overlap_idx_2, min_idx_from_1_to_2, min_idx_from_2_to_1
def merge_instances_from_new_view(self, instances_info, i, boundaries):
mask_label = self.curr_obs_torch['mask_label'][i]
assert mask_label[0] == 'background'
for j, label in enumerate(mask_label):
# if j == 0:
# continue
pcd_i = self.extract_masked_pcd_in_views([j], [i], boundaries, downsample=True) # (N,3) in numpy array
is_new_inst = True
max_iou = 0
max_iou_idx = -1
for k, info in enumerate(instances_info):
# Check 1: name matches
if label != info['label']:
continue
# Check 2: compute iou
pcd_inst = np.concatenate([info['pcd'][view_idx] for view_idx in info['pcd'].keys()], axis=0)
iou, _, _, _, _, _, _ = self.pcd_iou(pcd_i, pcd_inst, threshold=self.iou_threshold)
if iou > max_iou:
max_iou = iou
max_iou_idx = k
if max_iou > 0.25:
is_new_inst = False
# update instances_info
if is_new_inst and (label != 'background' or i == 0):
conf = self.curr_obs_torch['mask_conf'][i][j]
instances_info.append({'label': label,
'pcd': {i: pcd_i},
'conf': {i: conf},
'idx': {i: j}})
else:
# Additional Check 1: whether this segmentation is already in the instance
if i in instances_info[max_iou_idx]['pcd'].keys():
# choose the one with higher iou with other pcd
other_pcd_ls = [instances_info[max_iou_idx]['pcd'][view_idx] for view_idx in instances_info[max_iou_idx]['pcd'].keys() if view_idx != i]
if len(other_pcd_ls) > 0:
other_pcd = np.concatenate([instances_info[max_iou_idx]['pcd'][view_idx] for view_idx in instances_info[max_iou_idx]['pcd'].keys() if view_idx != i], axis=0)
curr_iou = self.pcd_iou(pcd_i, other_pcd, threshold=self.iou_threshold)[0]
prev_pcd = instances_info[max_iou_idx]['pcd'][i]
prev_iou = self.pcd_iou(pcd_i, prev_pcd, threshold=self.iou_threshold)[0]
if curr_iou <= prev_iou:
continue
conf = self.curr_obs_torch['mask_conf'][i][j]
instances_info[max_iou_idx]['pcd'][i] = pcd_i
instances_info[max_iou_idx]['conf'][i] = conf
instances_info[max_iou_idx]['idx'][i] = j
return instances_info
def vox_idx_iou(self, vox_idx_1, vox_idx_2):
intersection = len(
set(vox_idx_1).intersection(set(vox_idx_2))
)
union = len(set(vox_idx_1).union(set(vox_idx_2)))
return intersection / union, len(vox_idx_1) / union, len(vox_idx_2) / union
def merge_instances_from_new_view_vox_ver(self, instances_info, i, boundaries):
mask_label = self.curr_obs_torch['mask_label'][i]
assert mask_label[0] == 'background'
for j, label in enumerate(mask_label):
# if j == 0:
# continue
pcd_i = self.extract_masked_pcd_in_views([j], [i], boundaries) # (N,3) in numpy array
index_i = self.pcd_to_index(pcd_i)
is_new_inst = True
max_iou = 0
max_iou_idx = -1
for k, info in enumerate(instances_info):
# Check 1: name matches
if label != info['label']:
continue
# Check 2: compute iou
vox_idx_inst = info['vox_idx']
iou = self.vox_idx_iou(index_i, vox_idx_inst)[0]
if iou > max_iou:
max_iou = iou
max_iou_idx = k
if max_iou > 0.20:
is_new_inst = False
# update instances_info
if is_new_inst and (label != 'background' or i == 0):
conf = self.curr_obs_torch['mask_conf'][i][j]
conf_per_pt = {vox_i: [conf] for vox_i in index_i}
instances_info.append({'label': label,
# 'pcd': {i: pcd_i},
'vox_idx': index_i,
'conf_per_pt': conf_per_pt,
'idx': {i: j}})
else:
conf = self.curr_obs_torch['mask_conf'][i][j]
instances_info[max_iou_idx]['vox_idx'] = np.unique(np.concatenate([instances_info[max_iou_idx]['vox_idx'], index_i]))
if i in instances_info[max_iou_idx]['idx']:
new_vox_idx = set(index_i).difference(set(instances_info[max_iou_idx]['vox_idx']))
update_idx = new_vox_idx
else:
update_idx = set(index_i)
for vox_i in update_idx:
if vox_i not in instances_info[max_iou_idx]['conf_per_pt']:
instances_info[max_iou_idx]['conf_per_pt'][vox_i] = []
instances_info[max_iou_idx]['conf_per_pt'][vox_i].append(conf)
instances_info[max_iou_idx]['idx'][i] = j
return instances_info
def del_partial_pcd(self, instance_info, pcd_idx):
start_idx = 0
for view_idx in instance_info['pcd'].keys():
end_idx = start_idx + instance_info['pcd'][view_idx].shape[0]
pcd_idx_in_view = pcd_idx[np.logical_and(pcd_idx >= start_idx, pcd_idx < end_idx)]
pcd_idx_in_view -= start_idx
instance_info['pcd'][view_idx] = np.delete(instance_info['pcd'][view_idx], pcd_idx_in_view, axis=0)
start_idx = end_idx
return instance_info
def del_partial_vox_idx(self, instance_info, vox_idx):
curr_vox_idx = set(instance_info['vox_idx'])
for vox_i in vox_idx:
if vox_i in instance_info['conf_per_pt']:
del instance_info['conf_per_pt'][vox_i]
if vox_i in instance_info['vox_idx']:
curr_vox_idx.remove(vox_i)
instance_info['vox_idx'] = np.array(list(curr_vox_idx))
return instance_info
def filter_instances(self, instances_info):
to_delete = []
# Filter 1: filter instances that have a large IoU with other instances
for idx_i, instance_i in enumerate(instances_info):
if idx_i in to_delete:
continue
for idx_j, instance_j in enumerate(instances_info):
if idx_j <= idx_i:
continue
if idx_j in to_delete:
continue
pcd_i = np.concatenate([instance_i['pcd'][view_idx] for view_idx in instance_i['pcd'].keys()], axis=0)
conf_per_pt_i = np.concatenate([np.ones(instance_i['pcd'][view_idx].shape[0]) * instance_i['conf'][view_idx] for view_idx in instance_i['pcd'].keys()])
pcd_j = np.concatenate([instance_j['pcd'][view_idx] for view_idx in instance_j['pcd'].keys()], axis=0)
conf_per_pt_j = np.concatenate([np.ones(instance_j['pcd'][view_idx].shape[0]) * instance_j['conf'][view_idx] for view_idx in instance_j['pcd'].keys()])
iou, iou_1, iou_2, overlap_idx_1, overlap_idx_2, min_idx_from_1_to_2, min_idx_from_2_to_1 = self.pcd_iou(pcd_i, pcd_j, threshold=0.005)
if iou > 0.25:
# we can only keep one
num_vis_view_i = len(instance_i['idx'])
num_vis_view_j = len(instance_j['idx'])
if num_vis_view_i > num_vis_view_j:
to_delete.append(idx_j)
elif num_vis_view_j > num_vis_view_i:
to_delete.append(idx_i)
else:
# # ver 1: delete the whole instance
# conf_i = np.mean([instance_i['conf'][view_idx] for view_idx in instance_i['conf'].keys()])
# conf_j = np.mean([instance_j['conf'][view_idx] for view_idx in instance_j['conf'].keys()])
# if conf_i > conf_j:
# to_delete.append(idx_j)
# else:
# to_delete.append(idx_i)
# ver 2: delete the point with less confidence
overlap_conf_1 = conf_per_pt_i[overlap_idx_1]
overlap_conf_2_corr_to_1 = conf_per_pt_j[min_idx_from_1_to_2[overlap_idx_1]]
overlap_conf_2 = conf_per_pt_j[overlap_idx_2]
overlap_conf_1_corr_to_2 = conf_per_pt_i[min_idx_from_2_to_1[overlap_idx_2]]
pcd_i_del_idx = overlap_idx_1[overlap_conf_1 < overlap_conf_2_corr_to_1]
pcd_j_del_idx = overlap_idx_2[overlap_conf_2 < overlap_conf_1_corr_to_2]
# remove points in instance_i
instance_i = self.del_partial_pcd(instance_i, pcd_i_del_idx)
instance_j = self.del_partial_pcd(instance_j, pcd_j_del_idx)
# instance_i is a subset of instance_j
elif iou_1 > 0.5:
# we may delete instance_i or remove overlapping points in instance_j
num_vis_view_i = len(instance_i['idx'])
num_vis_view_j = len(instance_j['idx'])
if (instance_j['label'] == 'background' and num_vis_view_i < self.num_cam // 2) or \
(instance_j['label'] != 'background' and num_vis_view_i < num_vis_view_j // 2):
# delete instance_i
to_delete.append(idx_i)
else:
# remove overlapping points in instance_j
instance_j = self.del_partial_pcd(instance_j, overlap_idx_2)
# instance_j is a subset of instance_i
elif iou_2 > 0.5:
# we may delete instance_j or remove overlapping points in instance_i
num_vis_view_i = len(instance_i['idx'])
num_vis_view_j = len(instance_j['idx'])
if (instance_i['label'] == 'background' and num_vis_view_j < self.num_cam // 2) or \
(instance_i['label'] != 'background' and num_vis_view_j < num_vis_view_i // 2):
# delete instance_j
to_delete.append(idx_j)
else:
# remove overlapping points in instance_i
instance_i = self.del_partial_pcd(instance_i, overlap_idx_1)
# immediately put instance to delete if it is too small
pcd_i = np.concatenate([instance_i['pcd'][view_idx] for view_idx in instance_i['pcd'].keys()], axis=0)
if pcd_i.shape[0] < 10:
to_delete.append(idx_i)
pcd_j = np.concatenate([instance_j['pcd'][view_idx] for view_idx in instance_j['pcd'].keys()], axis=0)
if pcd_j.shape[0] < 10:
to_delete.append(idx_j)
# Filter 2: filter certain instances used as background
for idx_i, instance_i in enumerate(instances_info):
if idx_i in to_delete:
continue
bg_name_ls = ['table']
if instance_i['label'] in bg_name_ls:
to_delete.append(idx_i)
continue
# Filter 3: filter instances that are too small
for idx_i, instance_i in enumerate(instances_info):
if idx_i in to_delete:
continue
pcd_i = np.concatenate([instance_i['pcd'][view_idx] for view_idx in instance_i['pcd'].keys()], axis=0)
if pcd_i.shape[0] < 10:
to_delete.append(idx_i)
continue
for idx in sorted(to_delete, reverse=True):
del instances_info[idx]
return instances_info
def filter_instances_vox_ver(self, instances_info):
to_delete = []
# Filter 1: filter instances that have a large IoU with other instances
for idx_i, instance_i in enumerate(instances_info):
if idx_i in to_delete:
continue
for idx_j, instance_j in enumerate(instances_info):
if idx_j <= idx_i:
continue
if idx_j in to_delete:
continue
vox_idx_i = instance_i['vox_idx']
conf_per_pt_i = instance_i['conf_per_pt']
vox_idx_j = instance_j['vox_idx']
conf_per_pt_j = instance_j['conf_per_pt']
iou, iou_1, iou_2 = self.vox_idx_iou(vox_idx_i, vox_idx_j)
if iou > 0.25 or iou_1 > 0.5 or iou_2 > 0.5:
# ver 2: delete the point with less views and less confidence
to_delete_i = []
for vox_i in conf_per_pt_i.keys():
# keep points that are not in vox_idx_j
if vox_i not in conf_per_pt_j:
continue
if len(conf_per_pt_i[vox_i]) < len(conf_per_pt_j[vox_i]):