-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform.py
More file actions
executable file
·1782 lines (1556 loc) · 72.1 KB
/
transform.py
File metadata and controls
executable file
·1782 lines (1556 loc) · 72.1 KB
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 random
import numbers
import scipy
import scipy.ndimage
import scipy.interpolate
import scipy.stats
import numpy as np
import torch
import copy
from collections.abc import Sequence, Mapping
from scipy.spatial.transform import Rotation as R
import time
from scipy.ndimage import gaussian_filter,zoom
from pointcept.utils.registry import Registry
TRANSFORMS = Registry("transforms")
# SSL attribute transforms
@TRANSFORMS.register_module()
class CollectContrast(object):
def __init__(self, keys_prefix, offset_keys_dict=None, **kwargs):
"""
e.g. Collect(keys=[coord], feat_keys=[coord, color])
"""
# keys=("coord", "grid_coord", "segment"),
# feat_keys=("color", "normal"),
if offset_keys_dict is None:
offset_keys_dict = dict(offset="coord") # {'offset': 'coord'}
# use offset to get the shape of the data
self.keys = keys_prefix
self.offset_keys = offset_keys_dict
self.kwargs = kwargs
def __call__(self, data_dict):
data = dict()
if isinstance(self.keys, str):
self.keys = [self.keys]
for key in self.keys:
for key_i in data_dict.keys():
if key_i.startswith(key):
data[key_i] = data_dict[key_i]
# print(key_i, data_dict[key_i].shape)
# data[key] = data_dict[key]
for key, value in self.offset_keys.items():
data[key] = torch.tensor([data_dict[value].shape[0]])
for name, keys in self.kwargs.items():
# print("name", name)
# print("keys", keys)
name = name.replace("_keys", "")
assert isinstance(keys, Sequence)
data[name] = torch.cat([data_dict[key].float() for key in keys], dim=1) # featre concat
return data
# efficent version
@TRANSFORMS.register_module()
class GSGaussianBlurVoxelOpc(object):
def __init__(self, p=0.5, sigma=[0.1,2,0], extra_keys=None):
self.p = p
self.sigma = sigma
self.extra_keys = extra_keys
def __call__(self, data_dict):
# efficient for 3D point cloud color blur
t0 = time.time()
if np.random.rand() < self.p:
assert 'grid_coord' in data_dict.keys(), f"grid_coord is required for GSGaussianBlur, but only {data_dict.keys()} is provided"
coord = data_dict["coord"] # already go through grid sampler and crop operation
grid_coord = data_dict["grid_coord"] # is uniformed!
opacity = data_dict["opacity"]
random_sigma = np.random.uniform(self.sigma[0], self.sigma[1])
# we only blur the color with opacity > 0.2
blur_mask = opacity > 0.5
blur_mask = blur_mask.ravel()
grid_coord_masked = grid_coord[blur_mask] # Use ravel() instead of reshape(-1)
grid_coord_max = grid_coord.max(axis=0)
grid_coord_min = grid_coord.min(axis=0)
grid_size = grid_coord_max - grid_coord_min + 1
# Convert coordinates to grid indices
grid_indices = (grid_coord_masked - grid_coord_min).astype(int)
# Create compact color and weight grids using broadcasting
color_grid = np.zeros((*grid_size, 3), dtype=np.float32)
weight_grid = np.zeros((*grid_size, 1), dtype=np.float32)
color_index = [0,1,2]
weight_index = [3]
grid_index = [0,1,2,3]
# for extra key
if 'opacity' in self.extra_keys:
opacity_grid = np.zeros((*grid_size, 1), dtype=np.float32)
opacity_index = np.array([0]) + len(grid_index)
grid_index.extend(opacity_index.tolist())
if 'scale' in self.extra_keys:
scale_grid = np.zeros((*grid_size, 3), dtype=np.float32)
scale_index = np.array([0,1,2]) + len(grid_index)
grid_index.extend(scale_index.tolist())
if 'quat' in self.extra_keys:
quat_grid = np.zeros((*grid_size, 4), dtype=np.float32)
quat_index = np.array([0,1,2,3]) + len(grid_index)
grid_index.extend(quat_index.tolist())
# do achieve lerp + normalize,
if "normal" in self.extra_keys:
normal_grid = np.zeros((*grid_size, 3), dtype=np.float32)
normal_index = np.array([0,1,2]) + len(grid_index)
grid_index.extend(normal_index.tolist())
# Vectorized assignment using advanced indexing
color_grid[tuple(grid_indices.T)] = data_dict["color"][blur_mask]
weight_grid[tuple(grid_indices.T)] = 1 # Use 3D array for weights
# print("color_grid", color_grid.shape, "sigma", random_sigma)
# print("weight_grid", weight_grid.shape)
feature_grid = np.concatenate([color_grid, weight_grid], axis=-1)
if 'opacity' in self.extra_keys:
opacity_grid[tuple(grid_indices.T)] = data_dict["opacity"][blur_mask]
feature_grid = np.concatenate([feature_grid, opacity_grid], axis=-1)
if 'scale' in self.extra_keys:
scale_grid[tuple(grid_indices.T)] = data_dict["scale"][blur_mask]
feature_grid = np.concatenate([feature_grid, scale_grid], axis=-1)
if 'quat' in self.extra_keys:
quat_grid[tuple(grid_indices.T)] = data_dict["quat"][blur_mask]
feature_grid = np.concatenate([feature_grid, quat_grid], axis=-1)
if "normal" in self.extra_keys:
normal_grid[tuple(grid_indices.T)] = data_dict["normal"][blur_mask]
feature_grid = np.concatenate([feature_grid, normal_grid], axis=-1)
# we can concate all feature together and do the blur
truncate = 2.0
# print("color_grid", color_grid.shape, "sigma", random_sigma)
# Use float32 for better memory usage and faster computation
blur_feature_grid = gaussian_filter(feature_grid, sigma=random_sigma,truncate=truncate, axes=(0, 1, 2))
blur_color = blur_feature_grid[..., color_index]
blur_weights = blur_feature_grid[..., weight_index] + 1e-7 # Prevent division by zero
# Get updated colors through advanced indexing
result_colors = data_dict["color"].copy()
result_colors[blur_mask] = blur_color[tuple(grid_indices.T)] / blur_weights[tuple(grid_indices.T)]
data_dict["color"] = result_colors
if 'opacity' in self.extra_keys:
result_opacity = data_dict["opacity"].copy()
result_opacity[blur_mask] = blur_feature_grid[tuple(grid_indices.T)][..., opacity_index] / blur_weights[tuple(grid_indices.T)]
# print("result_opacity", result_opacity.shape)
data_dict["opacity"] = result_opacity
if 'scale' in self.extra_keys:
result_scale = data_dict["scale"].copy()
result_scale[blur_mask] = blur_feature_grid[tuple(grid_indices.T)][..., scale_index] / blur_weights[tuple(grid_indices.T)]
# print("result_scale", result_scale.shape)
data_dict["scale"] = result_scale
if 'quat' in self.extra_keys:
result_quat = data_dict["quat"].copy()
result_quat[blur_mask] = blur_feature_grid[tuple(grid_indices.T)][..., quat_index] / blur_weights[tuple(grid_indices.T)]
# renormalization
result_quat = result_quat / np.linalg.norm(result_quat, axis=1, keepdims=True)
# print("result_quat", result_quat.shape)
data_dict["quat"] = result_quat
if "normal" in self.extra_keys:
result_normal = data_dict["normal"].copy()
result_normal[blur_mask] = blur_feature_grid[tuple(grid_indices.T)][..., normal_index] / blur_weights[tuple(grid_indices.T)]
# print("result_normal", result_normal.shape)
data_dict["normal"] = result_normal
return data_dict
@TRANSFORMS.register_module()
class RandomColorSolarize(object):
def __init__(self, p=0.2, threshold=128):
self.p = p
self.threshold = threshold
def __call__(self, data_dict):
if "color" in data_dict.keys() and np.random.rand() < self.p:
masked_color = data_dict["color"]
mask = data_dict["color"] < self.threshold
# change to add and substract
mask_sign = np.ones_like(mask)
mask_sign[mask] = -1
mask_add_on = np.zeros_like(masked_color)
mask_add_on[mask] = 255
masked_color = masked_color * mask_sign + mask_add_on
return data_dict
@TRANSFORMS.register_module()
class SphereCropRandomMaxPoints(object):
"""
reduce the point cloud to a fixed maximum number of points
"""
def __init__(self, random_scale=[0.5,1.0], point_max=80000):
self.point_max = point_max
self.random_scale = random_scale
self.point_max = point_max
def __call__(self, data_dict):
assert "coord" in data_dict.keys()
# pts_num = data_dict["coord"].shape[0]
point_max = int(np.random.uniform(self.random_scale[0], self.random_scale[1]) * self.point_max)
if data_dict["coord"].shape[0] > point_max:
center = data_dict["coord"][
np.random.randint(data_dict["coord"].shape[0])
]
idx_crop = np.argsort(np.sum(np.square(data_dict["coord"] - center), 1))[
:point_max
]
if "coord" in data_dict.keys():
data_dict["coord"] = data_dict["coord"][idx_crop]
if "origin_coord" in data_dict.keys():
data_dict["origin_coord"] = data_dict["origin_coord"][idx_crop]
if "grid_coord" in data_dict.keys():
data_dict["grid_coord"] = data_dict["grid_coord"][idx_crop]
if "color" in data_dict.keys():
data_dict["color"] = data_dict["color"][idx_crop]
if "quat" in data_dict.keys():
data_dict["quat"] = data_dict["quat"][idx_crop]
if "scale" in data_dict.keys():
data_dict["scale"] = data_dict["scale"][idx_crop]
if "opacity" in data_dict.keys():
data_dict["opacity"] = data_dict["opacity"][idx_crop]
if "sh" in data_dict.keys():
data_dict["sh"] = data_dict["sh"][idx_crop]
if "normal" in data_dict.keys():
data_dict["normal"] = data_dict["normal"][idx_crop]
if "lang_feat" in data_dict.keys():
data_dict["lang_feat"] = data_dict["lang_feat"][idx_crop]
if "lang_feat_64" in data_dict.keys():
data_dict["lang_feat_64"] = data_dict["lang_feat_64"][idx_crop]
if "valid_feat_mask" in data_dict.keys():
data_dict["valid_feat_mask"] = data_dict["valid_feat_mask"][idx_crop]
if "segment" in data_dict.keys():
data_dict["segment"] = data_dict["segment"][idx_crop]
if "instance" in data_dict.keys():
data_dict["instance"] = data_dict["instance"][idx_crop]
if "displacement" in data_dict.keys():
data_dict["displacement"] = data_dict["displacement"][idx_crop]
if "strength" in data_dict.keys():
data_dict["strength"] = data_dict["strength"][idx_crop]
return data_dict
@TRANSFORMS.register_module()
class ContrastiveViewsGenerator_SSL(object):
def __init__(
self,
view_keys=("coord", "color", "normal", "origin_coord"),
# basic_trans_cfg=None, # already in basic_trans_cfg before
global_base_transform=None,
local_base_transform=None,
global_transform0=None,
global_transform1=None,
local_transform=None,
local_crop_num=4,
):
self.view_keys = view_keys
# self.basic_trans = Compose(basic_trans_cfg)
# follow dinov2, we have two global transform and one local transform
self.global_base_transform = Compose(global_base_transform)
self.local_base_transform = Compose(local_base_transform)
self.global_transform0 = Compose(global_transform0)
self.global_transform1 = Compose(global_transform1)
self.local_transform = Compose(local_transform)
self.local_crop_num = local_crop_num
def __call__(self, data_dict):
# print("data_dict", data_dict.keys())
global_base_dict = dict()
local_base_dict = dict()
# we want lang feat to be similar in both global view
for key in self.view_keys:
global_base_dict[key] = data_dict[key].copy()
local_base_dict[key] = data_dict[key].copy()
global_base_dict = self.global_base_transform(global_base_dict)
global_crop_1_dict = {key: global_base_dict[key].copy() for key in self.view_keys}
global_crop_2_dict = {key: global_base_dict[key].copy() for key in self.view_keys}
global_crop_1_dict = self.global_transform0(global_crop_1_dict)
global_crop_2_dict = self.global_transform1(global_crop_2_dict)
local_crop_dict_list = []
local_base_dict = self.local_base_transform(local_base_dict)
for i in range(self.local_crop_num):
local_crop_dict = {key: local_base_dict[key].copy() for key in self.view_keys}
local_crop_dict = self.local_transform(local_crop_dict)
local_crop_dict_list.append(local_crop_dict)
# collect results
for key, value in global_crop_1_dict.items():
data_dict["global_crop0_" + key] = value
for key, value in global_crop_2_dict.items():
data_dict["global_crop1_" + key] = value
for i, local_crop_dict in enumerate(local_crop_dict_list):
for key, value in local_crop_dict.items():
data_dict["local_crop{}_".format(i) + key] = value
return data_dict
@TRANSFORMS.register_module()
class Collect(object):
def __init__(self, keys, offset_keys_dict=None, **kwargs):
"""
e.g. Collect(keys=[coord], feat_keys=[coord, color])
"""
# keys=("coord", "grid_coord", "segment"),
# feat_keys=("color", "normal"),
if offset_keys_dict is None:
offset_keys_dict = dict(offset="coord") # {'offset': 'coord'}
self.keys = keys
self.offset_keys = offset_keys_dict
self.kwargs = kwargs
def __call__(self, data_dict):
data = dict()
if isinstance(self.keys, str):
self.keys = [self.keys]
for key in self.keys:
if key in data_dict.keys():
data[key] = data_dict[key]
for key, value in self.offset_keys.items():
data[key] = torch.tensor(
[data_dict[value].shape[0]]
) # record the shape of the data
for name, keys in self.kwargs.items():
name = name.replace("_keys", "")
assert isinstance(keys, Sequence)
data[name] = torch.cat(
[data_dict[key].float() for key in keys], dim=1
) # feat_keys concat
return data
@TRANSFORMS.register_module()
class Copy(object):
def __init__(self, keys_dict=None):
if keys_dict is None:
keys_dict = dict(coord="origin_coord", segment="origin_segment")
self.keys_dict = keys_dict
def __call__(self, data_dict):
for key, value in self.keys_dict.items():
if key in data_dict.keys():
if isinstance(data_dict[key], np.ndarray):
data_dict[value] = data_dict[key].copy()
elif isinstance(data_dict[key], torch.Tensor):
data_dict[value] = data_dict[key].clone().detach()
else:
data_dict[value] = copy.deepcopy(data_dict[key])
return data_dict
@TRANSFORMS.register_module()
class ToTensor(object):
def __call__(self, data):
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, str):
# note that str is also a kind of sequence, judgement should before sequence
return data
elif isinstance(data, int):
return torch.LongTensor([data])
elif isinstance(data, float):
return torch.FloatTensor([data])
elif isinstance(data, np.ndarray) and np.issubdtype(data.dtype, bool):
return torch.from_numpy(data)
elif isinstance(data, np.ndarray) and np.issubdtype(data.dtype, np.integer):
return torch.from_numpy(data).long()
elif isinstance(data, np.ndarray) and np.issubdtype(data.dtype, np.floating):
return torch.from_numpy(data).float()
elif isinstance(data, Mapping):
result = {sub_key: self(item) for sub_key, item in data.items()}
return result
elif isinstance(data, Sequence):
result = [self(item) for item in data]
return result
else:
raise TypeError(f"type {type(data)} cannot be converted to tensor.")
@TRANSFORMS.register_module()
class Add(object):
def __init__(self, keys_dict=None):
if keys_dict is None:
keys_dict = dict()
self.keys_dict = keys_dict
def __call__(self, data_dict):
for key, value in self.keys_dict.items():
data_dict[key] = value
return data_dict
@TRANSFORMS.register_module()
class NormalizeColor(object):
def __call__(self, data_dict):
if "color" in data_dict.keys():
data_dict["color"] = data_dict["color"] / 127.5 - 1
return data_dict
@TRANSFORMS.register_module()
class NormalizeScales(object):
def __call__(self, data_dict):
if "scale" in data_dict.keys():
scale = data_dict["scale"]
scale = scale - scale.mean(dim=0, keepdim=True)
scale = scale / (scale.std(dim=0, keepdim=True) + 1e-6)
data_dict["scale"] = scale
return data_dict
@TRANSFORMS.register_module()
class NormalizeOpacities(object):
def __call__(self, data_dict):
if "opacity" in data_dict.keys():
opacity = data_dict["opacity"]
opacity = opacity - opacity.mean(dim=0, keepdim=True)
opacity = opacity / (opacity.std(dim=0, keepdim=True) + 1e-6)
data_dict["opacity"] = opacity
return data_dict
@TRANSFORMS.register_module()
class NormalizeCoord(object):
def __call__(self, data_dict):
if "coord" in data_dict.keys():
# modified from pointnet2
centroid = np.mean(data_dict["coord"], axis=0)
data_dict["coord"] -= centroid
m = np.max(np.sqrt(np.sum(data_dict["coord"] ** 2, axis=1)))
data_dict["coord"] = data_dict["coord"] / m
#if "scale" in data_dict.keys():
# data_dict["scale"] = data_dict["scale"] / m
return data_dict
@TRANSFORMS.register_module()
class PositiveShift(object):
def __call__(self, data_dict):
if "coord" in data_dict.keys():
coord_min = np.min(data_dict["coord"], 0)
data_dict["coord"] -= coord_min
return data_dict
@TRANSFORMS.register_module()
class CenterShift(object):
def __init__(self, apply_z=True):
self.apply_z = apply_z
def __call__(self, data_dict):
if "coord" in data_dict.keys():
x_min, y_min, z_min = data_dict["coord"].min(axis=0)
x_max, y_max, _ = data_dict["coord"].max(axis=0)
if self.apply_z:
shift = [(x_min + x_max) / 2, (y_min + y_max) / 2, z_min]
else:
shift = [(x_min + x_max) / 2, (y_min + y_max) / 2, 0]
data_dict["coord"] -= shift
if "pc_coord" in data_dict.keys():
# we apply the same shift to pc_coord
data_dict["pc_coord"] -= shift
return data_dict
@TRANSFORMS.register_module()
class RandomShift(object):
def __init__(self, shift=((-0.2, 0.2), (-0.2, 0.2), (0, 0))):
self.shift = shift
def __call__(self, data_dict):
if "coord" in data_dict.keys():
shift_x = np.random.uniform(self.shift[0][0], self.shift[0][1])
shift_y = np.random.uniform(self.shift[1][0], self.shift[1][1])
shift_z = np.random.uniform(self.shift[2][0], self.shift[2][1])
data_dict["coord"] += [shift_x, shift_y, shift_z]
return data_dict
@TRANSFORMS.register_module()
class PointClip(object):
def __init__(self, point_cloud_range=(-80, -80, -3, 80, 80, 1)):
self.point_cloud_range = point_cloud_range
def __call__(self, data_dict):
if "coord" in data_dict.keys():
data_dict["coord"] = np.clip(
data_dict["coord"],
a_min=self.point_cloud_range[:3],
a_max=self.point_cloud_range[3:],
)
return data_dict
@TRANSFORMS.register_module()
class RandomDropout(object):
def __init__(self, dropout_ratio=0.2, dropout_application_ratio=0.5):
"""
upright_axis: axis index among x,y,z, i.e. 2 for z
"""
self.dropout_ratio = dropout_ratio
self.dropout_application_ratio = dropout_application_ratio
def __call__(self, data_dict):
if random.random() < self.dropout_application_ratio:
n = len(data_dict["coord"])
idx = np.random.choice(n, int(n * (1 - self.dropout_ratio)), replace=False)
if "sampled_index" in data_dict:
# for ScanNet data efficient, we need to make sure labeled point is sampled.
idx = np.unique(np.append(idx, data_dict["sampled_index"]))
# remaps the original indices of the important points to their new positions in the subsampled data
mask = np.zeros_like(data_dict["segment"]).astype(bool)
mask[data_dict["sampled_index"]] = True
data_dict["sampled_index"] = np.where(mask[idx])[0]
if "coord" in data_dict.keys():
data_dict["coord"] = data_dict["coord"][idx]
if "color" in data_dict.keys():
data_dict["color"] = data_dict["color"][idx]
if "normal" in data_dict.keys():
data_dict["normal"] = data_dict["normal"][idx]
if "strength" in data_dict.keys():
data_dict["strength"] = data_dict["strength"][idx]
if "segment" in data_dict.keys():
data_dict["segment"] = data_dict["segment"][idx]
if "instance" in data_dict.keys():
data_dict["instance"] = data_dict["instance"][idx]
if "quat" in data_dict.keys():
data_dict["quat"] = data_dict["quat"][idx]
if "scale" in data_dict.keys():
data_dict["scale"] = data_dict["scale"][idx]
if "opacity" in data_dict.keys():
data_dict["opacity"] = data_dict["opacity"][idx]
if "sh" in data_dict.keys():
data_dict["sh"] = data_dict["sh"][idx]
if "s0" in data_dict.keys():
data_dict["s0"] = data_dict["s0"][idx]
if "lang_feat" in data_dict.keys():
data_dict["lang_feat"] = data_dict["lang_feat"][idx]
if "valid_feat_mask" in data_dict.keys():
data_dict["valid_feat_mask"] = data_dict["valid_feat_mask"][idx]
return data_dict
@TRANSFORMS.register_module()
class RandomRotate(object):
def __init__(self, angle=None, center=None, axis="z", always_apply=False, p=0.5):
self.angle = [-1, 1] if angle is None else angle
self.axis = axis
self.always_apply = always_apply
self.p = p if not self.always_apply else 1
self.center = center
def __call__(self, data_dict):
if random.random() > self.p:
return data_dict
angle = np.random.uniform(self.angle[0], self.angle[1]) * np.pi
rot_cos, rot_sin = np.cos(angle), np.sin(angle)
if self.axis == "x":
rot_t = np.array([[1, 0, 0], [0, rot_cos, -rot_sin], [0, rot_sin, rot_cos]])
elif self.axis == "y":
rot_t = np.array([[rot_cos, 0, rot_sin], [0, 1, 0], [-rot_sin, 0, rot_cos]])
elif self.axis == "z":
rot_t = np.array([[rot_cos, -rot_sin, 0], [rot_sin, rot_cos, 0], [0, 0, 1]])
else:
raise NotImplementedError
# Rotate coordinates (and pc_coord if available)
if "coord" in data_dict:
if self.center is None:
# compute center of bounding box
x_min, y_min, z_min = data_dict["coord"].min(axis=0)
x_max, y_max, z_max = data_dict["coord"].max(axis=0)
center = [(x_min + x_max) / 2, (y_min + y_max) / 2, (z_min + z_max) / 2]
else:
center = self.center
data_dict["coord"] = (data_dict["coord"] - center) @ rot_t.T + center
if "pc_coord" in data_dict:
data_dict["pc_coord"] = (
data_dict["pc_coord"] - center
) @ rot_t.T + center
# Rotate quaternions.
if "quat" in data_dict:
# 3DGS stores quaternions in wxyz format.
# SciPy expects quaternions in xyzw order.
# Convert from wxyz to xyzw by rolling left by 1.
quat_wxyz = data_dict["quat"]
quat_xyzw = np.roll(quat_wxyz, shift=-1, axis=1)
input_quat = R.from_quat(quat_xyzw)
rot = R.from_matrix(rot_t)
# Apply the rotation: left-multiply with the global rotation.
new_quat_xyzw = (rot * input_quat).as_quat()
# Convert back from xyzw to wxyz by rolling right by 1.
new_quat_wxyz = np.roll(new_quat_xyzw, shift=1, axis=1)
data_dict["quat"] = new_quat_wxyz
# Rotate normals if present
if "normal" in data_dict:
data_dict["normal"] = data_dict["normal"] @ rot_t.T
return data_dict
@TRANSFORMS.register_module()
class RandomRotateTargetAngle(object):
def __init__(
self, angle=(1 / 2, 1, 3 / 2), center=None, axis="z", always_apply=False, p=0.75
):
self.angle = angle
self.axis = axis
self.always_apply = always_apply
self.p = p if not self.always_apply else 1
self.center = center
def __call__(self, data_dict):
if random.random() > self.p:
return data_dict
angle = np.random.choice(self.angle) * np.pi
rot_cos, rot_sin = np.cos(angle), np.sin(angle)
if self.axis == "x":
rot_t = np.array([[1, 0, 0], [0, rot_cos, -rot_sin], [0, rot_sin, rot_cos]])
elif self.axis == "y":
rot_t = np.array([[rot_cos, 0, rot_sin], [0, 1, 0], [-rot_sin, 0, rot_cos]])
elif self.axis == "z":
rot_t = np.array([[rot_cos, -rot_sin, 0], [rot_sin, rot_cos, 0], [0, 0, 1]])
else:
raise NotImplementedError
if "coord" in data_dict.keys():
if self.center is None:
x_min, y_min, z_min = data_dict["coord"].min(axis=0)
x_max, y_max, z_max = data_dict["coord"].max(axis=0)
center = [(x_min + x_max) / 2, (y_min + y_max) / 2, (z_min + z_max) / 2]
else:
center = self.center
data_dict["coord"] -= center
data_dict["coord"] = np.dot(data_dict["coord"], np.transpose(rot_t))
data_dict["coord"] += center
if "pc_coord" in data_dict.keys():
data_dict["pc_coord"] -= center
data_dict["pc_coord"] = np.dot(
data_dict["pc_coord"], np.transpose(rot_t)
)
data_dict["pc_coord"] += center
if "quat" in data_dict:
# 3DGS stores quaternions in wxyz format.
# SciPy expects quaternions in xyzw order.
# Convert from wxyz to xyzw by rolling left by 1.
quat_wxyz = data_dict["quat"]
quat_xyzw = np.roll(quat_wxyz, shift=-1, axis=1)
input_quat = R.from_quat(quat_xyzw)
rot = R.from_matrix(rot_t)
# Apply the rotation: left-multiply with the global rotation.
new_quat_xyzw = (rot * input_quat).as_quat()
# Convert back from xyzw to wxyz by rolling right by 1.
new_quat_wxyz = np.roll(new_quat_xyzw, shift=1, axis=1)
data_dict["quat"] = new_quat_wxyz
if "normal" in data_dict.keys():
data_dict["normal"] = np.dot(data_dict["normal"], np.transpose(rot_t))
return data_dict
@TRANSFORMS.register_module()
class RandomScale(object):
def __init__(self, scale=None, anisotropic=False):
self.scale = scale if scale is not None else [0.95, 1.05]
self.anisotropic = anisotropic
def __call__(self, data_dict):
if "coord" in data_dict.keys():
scale = np.random.uniform(
self.scale[0], self.scale[1], 3 if self.anisotropic else 1
)
data_dict["coord"] *= scale
if "pc_coord" in data_dict.keys():
data_dict["pc_coord"] *= scale
if "scale" in data_dict.keys():
data_dict["scale"] *= scale
return data_dict
@TRANSFORMS.register_module()
class RandomFlip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, data_dict):
R_reflect = np.eye(3)
flipped = False
if np.random.rand() < self.p:
# Flip along x-axis.
reflect_x = np.diag([-1, 1, 1])
R_reflect = reflect_x @ R_reflect
flipped = True
if "coord" in data_dict:
data_dict["coord"][:, 0] = -data_dict["coord"][:, 0]
if "pc_coord" in data_dict:
data_dict["pc_coord"][:, 0] = -data_dict["pc_coord"][:, 0]
if "normal" in data_dict:
data_dict["normal"][:, 0] = -data_dict["normal"][:, 0]
if np.random.rand() < self.p:
# Flip along y-axis.
reflect_y = np.diag([1, -1, 1])
R_reflect = reflect_y @ R_reflect
flipped = True
if "coord" in data_dict:
data_dict["coord"][:, 1] = -data_dict["coord"][:, 1]
if "pc_coord" in data_dict:
data_dict["pc_coord"][:, 1] = -data_dict["pc_coord"][:, 1]
if "normal" in data_dict:
data_dict["normal"][:, 1] = -data_dict["normal"][:, 1]
if flipped and "quat" in data_dict:
# 3DGS stores quaternions in wxyz order.
# SciPy expects xyzw, so convert by rolling left.
quat_wxyz = data_dict["quat"]
quat_xyzw = np.roll(quat_wxyz, shift=-1, axis=1)
current_rot = R.from_quat(quat_xyzw).as_matrix()
new_rot = R_reflect @ current_rot @ R_reflect
new_quat_xyzw = R.from_matrix(new_rot).as_quat()
# Convert back to wxyz by rolling right.
new_quat_wxyz = np.roll(new_quat_xyzw, shift=1, axis=1)
data_dict["quat"] = new_quat_wxyz
return data_dict
@TRANSFORMS.register_module()
class RandomJitter(object):
def __init__(self, sigma=0.01, clip=0.05):
assert clip > 0
self.sigma = sigma
self.clip = clip
def __call__(self, data_dict):
if "coord" in data_dict.keys():
jitter = np.clip(
self.sigma * np.random.randn(data_dict["coord"].shape[0], 3),
-self.clip,
self.clip,
)
data_dict["coord"] += jitter
return data_dict
@TRANSFORMS.register_module()
class ClipGaussianJitter(object):
def __init__(self, scalar=0.02, store_jitter=False):
self.scalar = scalar
self.mean = np.mean(3)
self.cov = np.identity(3)
self.quantile = 1.96
self.store_jitter = store_jitter
def __call__(self, data_dict):
if "coord" in data_dict.keys():
jitter = np.random.multivariate_normal(
self.mean, self.cov, data_dict["coord"].shape[0]
)
jitter = self.scalar * np.clip(jitter / 1.96, -1, 1)
data_dict["coord"] += jitter
if self.store_jitter:
data_dict["jitter"] = jitter
return data_dict
@TRANSFORMS.register_module()
class ChromaticAutoContrast(object):
def __init__(self, p=0.2, blend_factor=None):
self.p = p
self.blend_factor = blend_factor
def __call__(self, data_dict):
if "color" in data_dict.keys() and np.random.rand() < self.p:
lo = np.min(data_dict["color"], 0, keepdims=True)
hi = np.max(data_dict["color"], 0, keepdims=True)
scale = 255 / (hi - lo)
contrast_feat = (data_dict["color"][:, :3] - lo) * scale
blend_factor = (
np.random.rand() if self.blend_factor is None else self.blend_factor
)
data_dict["color"][:, :3] = (1 - blend_factor) * data_dict["color"][
:, :3
] + blend_factor * contrast_feat
return data_dict
@TRANSFORMS.register_module()
class ChromaticTranslation(object):
def __init__(self, p=0.95, ratio=0.05):
self.p = p
self.ratio = ratio
def __call__(self, data_dict):
if "color" in data_dict.keys() and np.random.rand() < self.p:
tr = (np.random.rand(1, 3) - 0.5) * 255 * 2 * self.ratio
data_dict["color"][:, :3] = np.clip(tr + data_dict["color"][:, :3], 0, 255)
return data_dict
@TRANSFORMS.register_module()
class ChromaticJitter(object):
def __init__(self, p=0.95, std=0.005):
self.p = p
self.std = std
def __call__(self, data_dict):
if "color" in data_dict.keys() and np.random.rand() < self.p:
noise = np.random.randn(data_dict["color"].shape[0], 3)
noise *= self.std * 255
data_dict["color"][:, :3] = np.clip(
noise + data_dict["color"][:, :3], 0, 255
)
return data_dict
@TRANSFORMS.register_module()
class RandomColorGrayScale(object):
def __init__(self, p):
self.p = p
@staticmethod
def rgb_to_grayscale(color, num_output_channels=1):
if color.shape[-1] < 3:
raise TypeError(
"Input color should have at least 3 dimensions, but found {}".format(
color.shape[-1]
)
)
if num_output_channels not in (1, 3):
raise ValueError("num_output_channels should be either 1 or 3")
r, g, b = color[..., 0], color[..., 1], color[..., 2]
gray = (0.2989 * r + 0.587 * g + 0.114 * b).astype(color.dtype)
gray = np.expand_dims(gray, axis=-1)
if num_output_channels == 3:
gray = np.broadcast_to(gray, color.shape)
return gray
def __call__(self, data_dict):
if np.random.rand() < self.p:
data_dict["color"] = self.rgb_to_grayscale(data_dict["color"], 3)
return data_dict
@TRANSFORMS.register_module()
class RandomColorJitter(object):
"""
Random Color Jitter for 3D point cloud (refer torchvision)
"""
def __init__(self, brightness=0, contrast=0, saturation=0, hue=0, p=0.95):
self.brightness = self._check_input(brightness, "brightness")
self.contrast = self._check_input(contrast, "contrast")
self.saturation = self._check_input(saturation, "saturation")
self.hue = self._check_input(
hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False
)
self.p = p
@staticmethod
def _check_input(
value, name, center=1, bound=(0, float("inf")), clip_first_on_zero=True
):
if isinstance(value, numbers.Number):
if value < 0:
raise ValueError(
"If {} is a single number, it must be non negative.".format(name)
)
value = [center - float(value), center + float(value)]
if clip_first_on_zero:
value[0] = max(value[0], 0.0)
elif isinstance(value, (tuple, list)) and len(value) == 2:
if not bound[0] <= value[0] <= value[1] <= bound[1]:
raise ValueError("{} values should be between {}".format(name, bound))
else:
raise TypeError(
"{} should be a single number or a list/tuple with length 2.".format(
name
)
)
# if value is 0 or (1., 1.) for brightness/contrast/saturation
# or (0., 0.) for hue, do nothing
if value[0] == value[1] == center:
value = None
return value
@staticmethod
def blend(color1, color2, ratio):
ratio = float(ratio)
bound = 255.0
return (
(ratio * color1 + (1.0 - ratio) * color2)
.clip(0, bound)
.astype(color1.dtype)
)
@staticmethod
def rgb2hsv(rgb):
r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
maxc = np.max(rgb, axis=-1)
minc = np.min(rgb, axis=-1)
eqc = maxc == minc
cr = maxc - minc
s = cr / (np.ones_like(maxc) * eqc + maxc * (1 - eqc))
cr_divisor = np.ones_like(maxc) * eqc + cr * (1 - eqc)
rc = (maxc - r) / cr_divisor
gc = (maxc - g) / cr_divisor
bc = (maxc - b) / cr_divisor
hr = (maxc == r) * (bc - gc)
hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc)
hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc)
h = hr + hg + hb
h = (h / 6.0 + 1.0) % 1.0
return np.stack((h, s, maxc), axis=-1)
@staticmethod
def hsv2rgb(hsv):
h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
i = np.floor(h * 6.0)
f = (h * 6.0) - i
i = i.astype(np.int32)
p = np.clip((v * (1.0 - s)), 0.0, 1.0)
q = np.clip((v * (1.0 - s * f)), 0.0, 1.0)
t = np.clip((v * (1.0 - s * (1.0 - f))), 0.0, 1.0)
i = i % 6
mask = np.expand_dims(i, axis=-1) == np.arange(6)
a1 = np.stack((v, q, p, p, t, v), axis=-1)
a2 = np.stack((t, v, v, q, p, p), axis=-1)
a3 = np.stack((p, p, t, v, v, q), axis=-1)
a4 = np.stack((a1, a2, a3), axis=-1)
return np.einsum("...na, ...nab -> ...nb", mask.astype(hsv.dtype), a4)
def adjust_brightness(self, color, brightness_factor):
if brightness_factor < 0:
raise ValueError(
"brightness_factor ({}) is not non-negative.".format(brightness_factor)
)
return self.blend(color, np.zeros_like(color), brightness_factor)
def adjust_contrast(self, color, contrast_factor):
if contrast_factor < 0:
raise ValueError(
"contrast_factor ({}) is not non-negative.".format(contrast_factor)
)
mean = np.mean(RandomColorGrayScale.rgb_to_grayscale(color))
return self.blend(color, mean, contrast_factor)
def adjust_saturation(self, color, saturation_factor):
if saturation_factor < 0:
raise ValueError(
"saturation_factor ({}) is not non-negative.".format(saturation_factor)
)
gray = RandomColorGrayScale.rgb_to_grayscale(color)
return self.blend(color, gray, saturation_factor)
def adjust_hue(self, color, hue_factor):
if not (-0.5 <= hue_factor <= 0.5):
raise ValueError(
"hue_factor ({}) is not in [-0.5, 0.5].".format(hue_factor)
)