-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathPointCloud.cpp
More file actions
1882 lines (1685 loc) · 74.7 KB
/
Copy pathPointCloud.cpp
File metadata and controls
1882 lines (1685 loc) · 74.7 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
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// Copyright (c) 2018-2024 www.open3d.org
// SPDX-License-Identifier: MIT
// ----------------------------------------------------------------------------
#include "open3d/t/geometry/PointCloud.h"
#include <libqhullcpp/PointCoordinates.h>
#include <libqhullcpp/Qhull.h>
#include <libqhullcpp/QhullFacet.h>
#include <libqhullcpp/QhullFacetList.h>
#include <libqhullcpp/QhullVertexSet.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <algorithm>
#include <limits>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "open3d/core/CUDAUtils.h"
#include "open3d/core/EigenConverter.h"
#include "open3d/core/ShapeUtil.h"
#include "open3d/core/Tensor.h"
#include "open3d/core/TensorCheck.h"
#include "open3d/core/TensorFunction.h"
#include "open3d/core/hashmap/HashSet.h"
#include "open3d/core/linalg/Matmul.h"
#include "open3d/core/nns/NearestNeighborSearch.h"
#include "open3d/t/geometry/TensorMap.h"
#include "open3d/t/geometry/TriangleMesh.h"
#include "open3d/t/geometry/VtkUtils.h"
#include "open3d/t/geometry/kernel/GeometryMacros.h"
#include "open3d/t/geometry/kernel/Metrics.h"
#include "open3d/t/geometry/kernel/PCAPartition.h"
#include "open3d/t/geometry/kernel/PointCloud.h"
#include "open3d/t/geometry/kernel/Transform.h"
#include "open3d/t/pipelines/registration/Registration.h"
#include "open3d/utility/Random.h"
namespace open3d {
namespace t {
namespace geometry {
namespace {
// ---------------------------------------------------------------------------
// Ivanic–Ruedenberg real-SH rotation helpers.
// Ivanic and K. Ruedenberg, "Rotation Matrices for Real Spherical Harmonics.
// Direct Determination by Recursion", J. Phys. Chem., vol. 100, no. 15, pp.
// 6342-6347, 1996. http://pubs.acs.org/doi/pdf/10.1021/jp953350u
// Corrections (1998): http://pubs.acs.org/doi/pdf/10.1021/jp9833350
// Conventions: No Condon-Shortley phase, same as GraphDECO 3DGS.
//
// BuildIrR1 : degree-1 IR matrix — maps (y,z,x) SH ordering to the
// shader's EvaluateShDegree1 convention (m=-1→y, m=0→z, m=+1→x).
// BuildIrRl : degree l≥2 matrix via u,v,w recursion (Ivanic 1996 eq.).
// RotateGSSplat: updates rot + f_rest for a GS PointCloud after Rotate().
// ---------------------------------------------------------------------------
Eigen::Matrix3f BuildIrR1(const Eigen::Matrix3f& R) {
// SH degree-1 basis index → Cartesian axis: {y=1, z=2, x=0}
constexpr int idx[3] = {1, 2, 0};
Eigen::Matrix3f R1;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) R1(i, j) = R(idx[i], idx[j]);
return R1;
}
Eigen::MatrixXf BuildIrRl(int l,
const Eigen::Matrix3f& R1,
const Eigen::MatrixXf& Rp) {
// Rp: IR matrix for degree l-1 (shape (2(l-1)+1) × (2(l-1)+1)).
// Ivanic–Ruedenberg (1996) + 1998 erratum.
// P(i, a, b) accesses Rp with row index a ∈ [-(l-1), l-1].
auto P = [&](int i, int a, int b) -> float {
// g(m, n) indexes Rp with offset so m ∈ [-(l-1), l-1] maps to [0, 2l-2]
auto g = [&](int m, int n) -> float {
return Rp(m + l - 1, n + l - 1);
};
if (b == l)
return R1(i + 1, 2) * g(a, l - 1) - R1(i + 1, 0) * g(a, -(l - 1));
if (b == -l)
return R1(i + 1, 2) * g(a, -(l - 1)) + R1(i + 1, 0) * g(a, l - 1);
return R1(i + 1, 1) * g(a, b);
};
int s = 2 * l + 1;
Eigen::MatrixXf Rl = Eigen::MatrixXf::Zero(s, s);
for (int m = -l; m <= l; ++m) {
for (int n = -l; n <= l; ++n) {
float d = (m == 0) ? 1.f : 0.f;
float denom = std::abs(n) < l ? float(l * l - n * n)
: float(l * (2 * l - 1));
float am = std::abs(float(m));
// u weight (zero when |m| == l, so P(0, m, n) is never
// out-of-bounds).
float u = std::sqrt(float(l * l - m * m) / denom);
// v weight — incorporates sqrt(1+delta_{m,1}) / sqrt(2) factors.
float v = 0.5f *
std::sqrt((1.f + d) * (l + am - 1.f) * (l + am) / denom) *
(1.f - 2.f * d);
// w weight (zero when m == 0).
float w = am > 0.f ? -0.5f * std::sqrt((l - am - 1.f) * (l - am) /
denom)
: 0.f;
float res = 0.f;
// U term: row index = m (safe because u == 0 when |m| == l).
if (u != 0.f) res += u * P(0, m, n);
// V term (Table 2 of Ivanic & Ruedenberg 1998 erratum).
if (v != 0.f) {
if (m == 0) {
res += v * (P(1, 1, n) + P(-1, -1, n));
} else if (m > 0) {
float dv = (m == 1) ? 1.f : 0.f;
res += v * (P(1, m - 1, n) * std::sqrt(1.f + dv) -
P(-1, -m + 1, n) * (1.f - dv));
} else {
// m < 0
float dv = (m == -1) ? 1.f : 0.f;
res += v * (P(1, m + 1, n) * (1.f - dv) +
P(-1, -m - 1, n) * std::sqrt(1.f + dv));
}
}
// W term: uses shifted row indices (w == 0 when m == 0).
if (w != 0.f) {
if (m > 0) {
res += w * (P(1, m + 1, n) + P(-1, -m - 1, n));
} else {
// m < 0 (m == 0 excluded by w == 0)
res += w * (P(1, m - 1, n) - P(-1, -m + 1, n));
}
}
Rl(m + l, n + l) = res;
}
}
return Rl;
}
// Update rot and f_rest in-place after Rotate(R, center).
// Proper rotation is assumed (same policy as RotateNormalsKernel).
// rot: CPU Eigen loop. f_rest: IR matrices computed on CPU, Matmul on device.
void RotateGSSplat(const core::Tensor& R_tensor, PointCloud& pcd) {
auto device = pcd.GetDevice();
int64_t N = pcd.GetPointPositions().GetLength();
// Read R into Eigen (float32, row-major).
auto R_f32 = R_tensor.To(core::Device("CPU:0"), core::Float32).Contiguous();
const float* rp = R_f32.GetDataPtr<float>();
Eigen::Matrix3f R;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) R(i, j) = rp[i * 3 + j];
// --- Quaternion rotation (CPU only) ---
// q_new = Quaternion(R) * q_old per splat; improper R gives undefined
// results (same policy as normals not being renormalised for non-orthogonal
// R).
auto rot_attr = pcd.GetPointAttr("rot").To(core::Device("CPU:0"));
Eigen::Quaternionf qR(R);
float* rptr = rot_attr.GetDataPtr<float>();
for (int64_t n = 0; n < N; ++n) {
Eigen::Quaternionf q(rptr[n * 4 + 0], rptr[n * 4 + 1], rptr[n * 4 + 2],
rptr[n * 4 + 3]);
Eigen::Quaternionf qn = qR * q;
rptr[n * 4 + 0] = qn.w();
rptr[n * 4 + 1] = qn.x();
rptr[n * 4 + 2] = qn.y();
rptr[n * 4 + 3] = qn.z();
}
if (!pcd.GetDevice().IsCPU()) {
pcd.SetPointAttr("rot", rot_attr.To(device));
}
// --- SH rotation (all devices via Tensor Matmul) ---
// f_dc (degree-0) is invariant; f_rest holds degrees 1 … sh_degree.
int sh_degree = pcd.GaussianSplatGetSHOrder();
if (sh_degree == 0) return;
auto& f_rest_attr = pcd.GetPointAttr("f_rest");
int64_t Nc = f_rest_attr.GetShape(1); // (sh_degree+1)² − 1
// Build block-diagonal rotation matrix R_full (Nc×Nc) on CPU, then
// transpose it — we need R_full^T for the right-multiply: f @ R_full^T.
Eigen::MatrixXf R_full_T = Eigen::MatrixXf::Zero(Nc, Nc);
Eigen::Matrix3f R1 = BuildIrR1(R);
Eigen::MatrixXf Rp = R1;
int offset = 0;
for (int l = 1; l <= sh_degree; ++l) {
int sl = 2 * l + 1;
Eigen::MatrixXf Rl =
(l == 1) ? Eigen::MatrixXf(R1) : BuildIrRl(l, R1, Rp);
R_full_T.block(offset, offset, sl, sl) = Rl.transpose();
Rp = Rl;
offset += sl;
}
// Pack into a float32 Tensor and move to device.
std::vector<float> rft_data(Nc * Nc);
for (int r = 0; r < Nc; ++r)
for (int c = 0; c < Nc; ++c) rft_data[r * Nc + c] = R_full_T(r, c);
core::Tensor Rft(rft_data, {Nc, Nc}, core::Float32, core::Device("CPU:0"));
Rft = Rft.To(device, core::Float32);
// f_rest {N, Nc, 3} → permute {N, 3, Nc} → reshape {N*3, Nc}
// @ Rft {Nc, Nc} → {N*3, Nc} → reshape {N, 3, Nc} → permute {N, Nc, 3}
auto f_2d = f_rest_attr.To(core::Float32)
.Permute({0, 2, 1})
.Contiguous()
.Reshape({N * 3, Nc});
f_rest_attr = f_2d.Matmul(Rft)
.Reshape({N, 3, Nc})
.Permute({0, 2, 1})
.Contiguous();
}
} // namespace
PointCloud::PointCloud(const core::Device& device)
: Geometry(Geometry::GeometryType::PointCloud, 3),
device_(device),
point_attr_(TensorMap("positions")) {}
PointCloud::PointCloud(const core::Tensor& points)
: PointCloud(points.GetDevice()) {
core::AssertTensorShape(points, {std::nullopt, 3});
SetPointPositions(points);
}
PointCloud::PointCloud(const std::unordered_map<std::string, core::Tensor>&
map_keys_to_tensors)
: Geometry(Geometry::GeometryType::PointCloud, 3),
point_attr_(TensorMap("positions")) {
if (map_keys_to_tensors.count("positions") == 0) {
utility::LogError("\"positions\" attribute must be specified.");
}
device_ = map_keys_to_tensors.at("positions").GetDevice();
core::AssertTensorShape(map_keys_to_tensors.at("positions"),
{std::nullopt, 3});
point_attr_ = TensorMap("positions", map_keys_to_tensors.begin(),
map_keys_to_tensors.end());
}
std::string PointCloud::ToString() const {
size_t num_points = 0;
std::string points_dtype_str = "";
if (point_attr_.count(point_attr_.GetPrimaryKey())) {
num_points = GetPointPositions().GetLength();
points_dtype_str =
fmt::format(" ({})", GetPointPositions().GetDtype().ToString());
}
auto str =
fmt::format("PointCloud on {} [{} points{}].\nAttributes:",
GetDevice().ToString(), num_points, points_dtype_str);
if ((point_attr_.size() - point_attr_.count(point_attr_.GetPrimaryKey())) ==
0)
return str + " None.";
for (const auto& keyval : point_attr_) {
if (keyval.first != "positions") {
str += fmt::format(" {} (dtype = {}, shape = {}),", keyval.first,
keyval.second.GetDtype().ToString(),
keyval.second.GetShape().ToString());
}
}
str[str.size() - 1] = '.';
return str;
}
core::Tensor PointCloud::GetMinBound() const {
return GetPointPositions().Min({0});
}
core::Tensor PointCloud::GetMaxBound() const {
return GetPointPositions().Max({0});
}
core::Tensor PointCloud::GetCenter() const {
return GetPointPositions().Mean({0});
}
PointCloud PointCloud::To(const core::Device& device, bool copy) const {
if (!copy && GetDevice() == device) {
return *this;
}
PointCloud pcd(device);
for (auto& kv : point_attr_) {
pcd.SetPointAttr(kv.first, kv.second.To(device, /*copy=*/true));
}
return pcd;
}
PointCloud PointCloud::Clone() const { return To(GetDevice(), /*copy=*/true); }
PointCloud PointCloud::Append(const PointCloud& other) const {
// A PointCloud with no declared attributes has no dtype or shape to
// validate. Treat it as the identity and adopt the populated schema.
if (point_attr_.empty()) {
return other.point_attr_.empty() ? Clone() : other.Clone();
}
if (other.point_attr_.empty()) {
return Clone();
}
PointCloud pcd(GetDevice());
int64_t length = GetPointPositions().GetLength();
for (auto& kv : point_attr_) {
if (other.HasPointAttr(kv.first)) {
auto other_attr = other.GetPointAttr(kv.first);
core::AssertTensorDtype(other_attr, kv.second.GetDtype());
core::AssertTensorDevice(other_attr, kv.second.GetDevice());
// Checking shape compatibility.
auto other_attr_shape = other_attr.GetShape();
auto attr_shape = kv.second.GetShape();
int64_t combined_length = other_attr_shape[0] + attr_shape[0];
other_attr_shape[0] = combined_length;
attr_shape[0] = combined_length;
if (other_attr_shape != attr_shape) {
utility::LogError(
"Shape mismatch. Attribute {}, shape {}, is not "
"compatible with {}.",
kv.first, other_attr.GetShape(), kv.second.GetShape());
}
core::Tensor combined_attr =
core::Tensor::Empty(other_attr_shape, kv.second.GetDtype(),
kv.second.GetDevice());
combined_attr.SetItem(core::TensorKey::Slice(0, length, 1),
kv.second);
combined_attr.SetItem(
core::TensorKey::Slice(length, combined_length, 1),
other_attr);
pcd.SetPointAttr(kv.first, combined_attr.Clone());
} else {
utility::LogError(
"The pointcloud is missing attribute {}. The pointcloud "
"being appended, must have all the attributes present in "
"the pointcloud it is being appended to.",
kv.first);
}
}
return pcd;
}
PointCloud& PointCloud::Transform(const core::Tensor& transformation) {
core::AssertTensorShape(transformation, {4, 4});
kernel::transform::TransformPoints(transformation, GetPointPositions());
if (HasPointNormals()) {
kernel::transform::TransformNormals(transformation, GetPointNormals());
}
// The linear part of a general 4×4 may be non-orthogonal, so covariance
// (rot, scale) and SH (f_rest) cannot be updated generically.
// Compose Rotate() + Scale() + Translate() instead for GS clouds.
if (IsGaussianSplat()) {
utility::LogWarning(
"PointCloud::Transform() does not update Gaussian splat "
"attributes (rot, scale, f_rest). Use Rotate(), Scale(), and "
"Translate() instead.");
}
return *this;
}
PointCloud& PointCloud::Translate(const core::Tensor& translation,
bool relative) {
core::AssertTensorShape(translation, {3});
core::Tensor transform =
translation.To(GetDevice(), GetPointPositions().GetDtype());
if (!relative) {
transform -= GetCenter();
}
GetPointPositions() += transform;
return *this;
}
PointCloud& PointCloud::Scale(double scale, const core::Tensor& center) {
core::AssertTensorShape(center, {3});
const core::Tensor center_d =
center.To(GetDevice(), GetPointPositions().GetDtype());
GetPointPositions().Sub_(center_d).Mul_(scale).Add_(center_d);
// For GS splats, negative uniform scale means point inversion plus
// positive scaling: positions are mirrored (above), axis lengths scale by
// |scale|, and odd-degree SH bands flip sign because Y_lm(-d) = (-1)^l
// Y_lm(d).
if (IsGaussianSplat()) {
GetPointAttr("scale").Mul_(std::abs(scale));
if (scale < 0.0) {
int sh_degree = GaussianSplatGetSHOrder();
for (int l = 1; l <= sh_degree; l += 2) {
const int offset = l * l - 1;
const int size_l = 2 * l + 1;
GetPointAttr("f_rest")
.Slice(1, offset, offset + size_l)
.Mul_(-1.0);
}
}
}
return *this;
}
PointCloud& PointCloud::Rotate(const core::Tensor& R,
const core::Tensor& center) {
core::AssertTensorShape(R, {3, 3});
core::AssertTensorShape(center, {3});
kernel::transform::RotatePoints(R, GetPointPositions(), center);
if (HasPointNormals()) {
kernel::transform::RotateNormals(R, GetPointNormals());
}
// For GS splats: rotate quaternions (CPU) and SH coefficients (all
// devices). Proper rotation is assumed, consistent with RotateNormalsKernel
// which applies R directly without orthogonality checks.
if (IsGaussianSplat()) {
RotateGSSplat(R, *this);
}
return *this;
}
PointCloud PointCloud::SelectByMask(const core::Tensor& boolean_mask,
bool invert /* = false */) const {
const int64_t length = GetPointPositions().GetLength();
core::AssertTensorDtype(boolean_mask, core::Dtype::Bool);
core::AssertTensorShape(boolean_mask, {length});
core::AssertTensorDevice(boolean_mask, GetDevice());
core::Tensor indices_local;
if (invert) {
indices_local = boolean_mask.LogicalNot();
} else {
indices_local = boolean_mask;
}
PointCloud pcd(GetDevice());
for (auto& kv : GetPointAttr()) {
if (HasPointAttr(kv.first)) {
pcd.SetPointAttr(kv.first, kv.second.IndexGet({indices_local}));
}
}
utility::LogDebug("Pointcloud down sampled from {} points to {} points.",
length, pcd.GetPointPositions().GetLength());
return pcd;
}
PointCloud PointCloud::SelectByIndex(
const core::Tensor& indices,
bool invert /* = false */,
bool remove_duplicates /* = false */) const {
const int64_t length = GetPointPositions().GetLength();
core::AssertTensorDtype(indices, core::Int64);
core::AssertTensorDevice(indices, GetDevice());
PointCloud pcd(GetDevice());
if (!remove_duplicates && !invert) {
core::TensorKey key = core::TensorKey::IndexTensor(indices);
for (auto& kv : GetPointAttr()) {
if (HasPointAttr(kv.first)) {
pcd.SetPointAttr(kv.first, kv.second.GetItem(key));
}
}
utility::LogDebug(
"Pointcloud down sampled from {} points to {} points.", length,
pcd.GetPointPositions().GetLength());
} else {
// The indices may have duplicate index value and will result in
// identity point cloud attributes. We convert indices Tensor into mask
// Tensor and call SelectByMask to avoid this situation.
core::Tensor mask =
core::Tensor::Zeros({length}, core::Bool, GetDevice());
mask.SetItem(core::TensorKey::IndexTensor(indices),
core::Tensor::Init<bool>(true, GetDevice()));
pcd = SelectByMask(mask, invert);
}
return pcd;
}
PointCloud PointCloud::VoxelDownSample(double voxel_size,
const std::string& reduction) const {
if (voxel_size <= 0) {
utility::LogError("voxel_size must be positive.");
}
if (reduction != "mean") {
utility::LogError("Reduction can only be 'mean' for VoxelDownSample.");
}
// Discretize voxels.
core::Tensor voxeld = GetPointPositions() / voxel_size;
core::Tensor voxeli = voxeld.Floor().To(core::Int64);
// Map discrete voxels to indices.
core::HashSet voxeli_hashset(voxeli.GetLength(), core::Int64, {3}, device_);
// Insertion pass: masks==true marks the first occurrence (one per unique
// voxel); the returned buf_indices are gather indices into the hash buffer.
core::Tensor insert_buf_indices, insert_masks;
voxeli_hashset.Insert(voxeli, insert_buf_indices, insert_masks);
int64_t num_points = voxeli.GetLength();
int64_t num_voxels = voxeli_hashset.Size();
// buf_indices are not guaranteed dense on SYCL; relabel to [0, num_voxels).
core::Tensor remap = core::Tensor::Zeros({voxeli_hashset.GetCapacity()},
core::Int64, device_);
core::Tensor unique_slots =
insert_buf_indices.IndexGet({insert_masks}).To(core::Int64);
remap.IndexSet({unique_slots},
core::Tensor::Arange(int64_t(0), num_voxels, int64_t(1),
core::Int64, device_));
// Find pass: per-point gather index of its voxel slot, then relabel dense.
core::Tensor index_map_point2voxel, masks;
voxeli_hashset.Find(voxeli, index_map_point2voxel, masks);
index_map_point2voxel =
remap.IndexGet({index_map_point2voxel.To(core::Int64)});
// Count the number of points in each voxel.
auto voxel_num_points =
core::Tensor::Zeros({num_voxels}, core::Float32, device_);
voxel_num_points.IndexAdd_(
/*dim*/ 0, index_map_point2voxel,
core::Tensor::Ones({num_points}, core::Float32, device_));
// Create a new point cloud.
PointCloud pcd_down(device_);
for (auto& kv : point_attr_) {
auto point_attr = kv.second;
std::string attr_string = kv.first;
auto attr_dtype = point_attr.GetDtype();
// Use float to avoid unsupported tensor types.
core::SizeVector attr_shape = point_attr.GetShape();
attr_shape[0] = num_voxels;
auto voxel_attr =
core::Tensor::Zeros(attr_shape, core::Float32, device_);
if (reduction == "mean") {
voxel_attr.IndexAdd_(0, index_map_point2voxel,
point_attr.To(core::Float32));
voxel_attr /= voxel_num_points.View({-1, 1});
voxel_attr = voxel_attr.To(attr_dtype);
} else {
utility::LogError("Unsupported reduction type {}.", reduction);
}
pcd_down.SetPointAttr(attr_string, voxel_attr);
}
return pcd_down;
}
PointCloud PointCloud::UniformDownSample(size_t every_k_points) const {
if (every_k_points == 0) {
utility::LogError(
"Illegal sample rate, every_k_points must be larger than 0.");
}
const int64_t length = GetPointPositions().GetLength();
PointCloud pcd_down(GetDevice());
for (auto& kv : GetPointAttr()) {
pcd_down.SetPointAttr(
kv.first,
kv.second.Slice(0, 0, length, (int64_t)every_k_points));
}
return pcd_down;
}
PointCloud PointCloud::RandomDownSample(double sampling_ratio) const {
if (sampling_ratio < 0 || sampling_ratio > 1) {
utility::LogError(
"Illegal sampling_ratio {}, sampling_ratio must be between 0 "
"and 1.");
}
const int64_t length = GetPointPositions().GetLength();
std::vector<int64_t> indices(length);
std::iota(std::begin(indices), std::end(indices), 0);
{
std::lock_guard<std::mutex> lock(*utility::random::GetMutex());
std::shuffle(indices.begin(), indices.end(),
*utility::random::GetEngine());
}
const int sample_size = sampling_ratio * length;
indices.resize(sample_size);
// TODO: Generate random indices in GPU using CUDA rng maybe more efficient
// than copy indices data from CPU to GPU.
return SelectByIndex(
core::Tensor(indices, {sample_size}, core::Int64, GetDevice()),
false, false);
}
PointCloud PointCloud::FarthestPointDownSample(const size_t num_samples,
const size_t start_index) const {
const core::Dtype dtype = GetPointPositions().GetDtype();
const int64_t num_points = GetPointPositions().GetLength();
if (num_samples == 0) {
return PointCloud(GetDevice());
} else if (num_samples == size_t(num_points)) {
return Clone();
} else if (num_samples > size_t(num_points)) {
utility::LogError(
"Illegal number of samples: {}, must <= point size: {}",
num_samples, num_points);
} else if (start_index >= size_t(num_points)) {
utility::LogError("Illegal start index: {}, must <= point size: {}",
start_index, num_points);
}
core::Tensor selection_mask =
core::Tensor::Zeros({num_points}, core::Bool, GetDevice());
core::Tensor smallest_distances = core::Tensor::Full(
{num_points}, std::numeric_limits<double>::infinity(), dtype,
GetDevice());
int64_t farthest_index = static_cast<int64_t>(start_index);
for (size_t i = 0; i < num_samples; i++) {
selection_mask[farthest_index] = true;
core::Tensor selected = GetPointPositions()[farthest_index];
core::Tensor diff = GetPointPositions() - selected;
core::Tensor distances_to_selected = (diff * diff).Sum({1});
smallest_distances = open3d::core::Minimum(distances_to_selected,
smallest_distances);
farthest_index = smallest_distances.ArgMax({0}).Item<int64_t>();
}
return SelectByMask(selection_mask);
}
std::tuple<PointCloud, core::Tensor> PointCloud::RemoveRadiusOutliers(
size_t nb_points, double search_radius) const {
if (nb_points < 1 || search_radius <= 0) {
utility::LogError(
"Illegal input parameters, number of points and radius must be "
"positive");
}
core::nns::NearestNeighborSearch target_nns(GetPointPositions());
const bool check = target_nns.FixedRadiusIndex(search_radius);
if (!check) {
utility::LogError("Fixed radius search index is not set.");
}
core::Tensor indices, distance, row_splits;
std::tie(indices, distance, row_splits) = target_nns.FixedRadiusSearch(
GetPointPositions(), search_radius, false);
row_splits = row_splits.To(GetDevice());
const int64_t size = row_splits.GetLength();
const core::Tensor num_neighbors =
row_splits.Slice(0, 1, size) - row_splits.Slice(0, 0, size - 1);
const core::Tensor valid =
num_neighbors.Ge(static_cast<int64_t>(nb_points));
return std::make_tuple(SelectByMask(valid), valid);
}
std::tuple<PointCloud, core::Tensor> PointCloud::RemoveStatisticalOutliers(
size_t nb_neighbors, double std_ratio) const {
if (nb_neighbors < 1 || std_ratio <= 0) {
utility::LogError(
"Illegal input parameters, the number of neighbors and "
"standard deviation ratio must be positive.");
}
if (GetPointPositions().GetLength() == 0) {
return std::make_tuple(PointCloud(GetDevice()),
core::Tensor({0}, core::Bool, GetDevice()));
}
core::nns::NearestNeighborSearch nns(GetPointPositions().Contiguous());
const bool check = nns.KnnIndex();
if (!check) {
utility::LogError("Knn search index is not set.");
}
core::Tensor indices, distance2;
std::tie(indices, distance2) =
nns.KnnSearch(GetPointPositions(), nb_neighbors);
core::Tensor avg_distances = distance2.Sqrt().Mean({1});
const double cloud_mean =
avg_distances.Mean({0}).To(core::Float64).Item<double>();
const core::Tensor std_distances_centered = avg_distances - cloud_mean;
const double sq_sum = (std_distances_centered * std_distances_centered)
.Sum({0})
.To(core::Float64)
.Item<double>();
const double std_dev =
std::sqrt(sq_sum / (avg_distances.GetShape()[0] - 1));
const double distance_threshold = cloud_mean + std_ratio * std_dev;
const core::Tensor valid = avg_distances.Le(distance_threshold);
return std::make_tuple(SelectByMask(valid), valid);
}
std::tuple<PointCloud, core::Tensor> PointCloud::RemoveNonFinitePoints(
bool remove_nan, bool remove_inf) const {
core::Tensor finite_indices_mask;
const core::SizeVector dim = {1};
if (remove_nan && remove_inf) {
finite_indices_mask =
this->GetPointPositions().IsFinite().All(dim, false);
} else if (remove_nan) {
finite_indices_mask =
this->GetPointPositions().IsNan().LogicalNot().All(dim, false);
} else if (remove_inf) {
finite_indices_mask =
this->GetPointPositions().IsInf().LogicalNot().All(dim, false);
} else {
finite_indices_mask = core::Tensor::Full(
{this->GetPointPositions().GetLength()}, true, core::Bool,
this->GetPointPositions().GetDevice());
}
utility::LogDebug("Removing non-finite points.");
return std::make_tuple(SelectByMask(finite_indices_mask),
finite_indices_mask);
}
std::tuple<PointCloud, core::Tensor> PointCloud::RemoveDuplicatedPoints()
const {
core::Tensor points_voxeli;
const core::Dtype dtype = GetPointPositions().GetDtype();
if (dtype.ByteSize() == 4) {
points_voxeli = GetPointPositions().ReinterpretCast(core::Int32);
} else if (dtype.ByteSize() == 8) {
points_voxeli = GetPointPositions().ReinterpretCast(core::Int64);
} else {
utility::LogError(
"Unsupported point position data-type. Only support "
"Int32, Int64, Float32 and Float64.");
}
core::HashSet points_voxeli_hashset(points_voxeli.GetLength(),
points_voxeli.GetDtype(), {3}, device_);
core::Tensor buf_indices, masks;
points_voxeli_hashset.Insert(points_voxeli, buf_indices, masks);
return std::make_tuple(SelectByMask(masks), masks);
}
PointCloud& PointCloud::NormalizeNormals() {
if (!HasPointNormals()) {
utility::LogWarning("PointCloud has no normals.");
return *this;
} else {
SetPointNormals(GetPointNormals().Contiguous());
}
core::Tensor& normals = GetPointNormals();
if (IsCPU()) {
kernel::pointcloud::NormalizeNormalsCPU(normals);
} else if (IsCUDA()) {
CUDA_CALL(kernel::pointcloud::NormalizeNormalsCUDA, normals);
} else if (IsSYCL()) {
#ifdef BUILD_SYCL_MODULE
kernel::pointcloud::NormalizeNormalsSYCL(normals);
#else
utility::LogError("Not compiled with SYCL, but SYCL device is used.");
#endif
} else {
utility::LogError("Unimplemented device");
}
return *this;
}
PointCloud& PointCloud::PaintUniformColor(const core::Tensor& color) {
core::AssertTensorShape(color, {3});
core::Tensor clipped_color = color.To(GetDevice());
if (color.GetDtype() == core::Float32 ||
color.GetDtype() == core::Float64) {
clipped_color = clipped_color.Clip(0.0f, 1.0f);
}
core::Tensor pcd_colors =
core::Tensor::Empty({GetPointPositions().GetLength(), 3},
clipped_color.GetDtype(), GetDevice());
pcd_colors.AsRvalue() = clipped_color;
SetPointColors(pcd_colors);
return *this;
}
std::tuple<PointCloud, core::Tensor> PointCloud::ComputeBoundaryPoints(
double radius, int max_nn, double angle_threshold) const {
core::AssertTensorDtypes(this->GetPointPositions(),
{core::Float32, core::Float64});
if (!HasPointNormals()) {
utility::LogError(
"PointCloud must have normals attribute to compute boundary "
"points.");
}
const core::Device device = GetDevice();
const int64_t num_points = GetPointPositions().GetLength();
const core::Tensor points_d = GetPointPositions().Contiguous();
const core::Tensor normals_d = GetPointNormals().Contiguous();
// Compute nearest neighbors.
core::Tensor indices, distance2, counts;
core::nns::NearestNeighborSearch tree(points_d, core::Int32);
bool check = tree.HybridIndex(radius);
if (!check) {
utility::LogError("Building HybridIndex failed.");
}
std::tie(indices, distance2, counts) =
tree.HybridSearch(points_d, radius, max_nn);
utility::LogDebug(
"Use HybridSearch [max_nn: {} | radius {}] for computing "
"boundary points.",
max_nn, radius);
core::Tensor mask = core::Tensor::Zeros({num_points}, core::Bool, device);
if (IsCPU()) {
kernel::pointcloud::ComputeBoundaryPointsCPU(
points_d, normals_d, indices, counts, mask, angle_threshold);
} else if (IsCUDA()) {
CUDA_CALL(kernel::pointcloud::ComputeBoundaryPointsCUDA, points_d,
normals_d, indices, counts, mask, angle_threshold);
} else if (IsSYCL()) {
#ifdef BUILD_SYCL_MODULE
kernel::pointcloud::ComputeBoundaryPointsSYCL(
points_d, normals_d, indices, counts, mask, angle_threshold);
#else
utility::LogError("Not compiled with SYCL, but SYCL device is used.");
#endif
} else {
utility::LogError("Unimplemented device");
}
return std::make_tuple(SelectByMask(mask), mask);
}
void PointCloud::EstimateNormals(
const std::optional<int> max_knn /* = 30*/,
const std::optional<double> radius /*= std::nullopt*/) {
core::AssertTensorDtypes(this->GetPointPositions(),
{core::Float32, core::Float64});
const core::Dtype dtype = this->GetPointPositions().GetDtype();
const core::Device device = GetDevice();
const bool has_normals = HasPointNormals();
if (!has_normals) {
this->SetPointNormals(core::Tensor::Empty(
{GetPointPositions().GetLength(), 3}, dtype, device));
} else {
core::AssertTensorDtype(this->GetPointNormals(), dtype);
this->SetPointNormals(GetPointNormals().Contiguous());
}
this->SetPointAttr(
"covariances",
core::Tensor::Empty({GetPointPositions().GetLength(), 3, 3}, dtype,
device));
if (radius.has_value() && max_knn.has_value()) {
utility::LogDebug("Using Hybrid Search for computing covariances");
// Computes and sets `covariances` attribute using Hybrid Search
// method.
if (IsCPU()) {
kernel::pointcloud::EstimateCovariancesUsingHybridSearchCPU(
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), radius.value(),
max_knn.value());
} else if (IsCUDA()) {
CUDA_CALL(kernel::pointcloud::
EstimateCovariancesUsingHybridSearchCUDA,
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), radius.value(),
max_knn.value());
} else if (IsSYCL()) {
#ifdef BUILD_SYCL_MODULE
kernel::pointcloud::EstimateCovariancesUsingHybridSearchSYCL(
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), radius.value(),
max_knn.value());
#else
utility::LogError(
"Not compiled with SYCL, but SYCL device is used.");
#endif
} else {
utility::LogError("Unimplemented device");
}
} else if (max_knn.has_value() && !radius.has_value()) {
utility::LogDebug("Using KNN Search for computing covariances");
// Computes and sets `covariances` attribute using KNN Search method.
if (IsCPU()) {
kernel::pointcloud::EstimateCovariancesUsingKNNSearchCPU(
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), max_knn.value());
} else if (IsCUDA()) {
CUDA_CALL(kernel::pointcloud::EstimateCovariancesUsingKNNSearchCUDA,
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), max_knn.value());
} else if (IsSYCL()) {
#ifdef BUILD_SYCL_MODULE
kernel::pointcloud::EstimateCovariancesUsingKNNSearchSYCL(
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), max_knn.value());
#else
utility::LogError(
"Not compiled with SYCL, but SYCL device is used.");
#endif
} else {
utility::LogError("Unimplemented device");
}
} else if (!max_knn.has_value() && radius.has_value()) {
utility::LogDebug("Using Radius Search for computing covariances");
// Computes and sets `covariances` attribute using KNN Search method.
if (IsCPU()) {
kernel::pointcloud::EstimateCovariancesUsingRadiusSearchCPU(
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), radius.value());
} else if (IsCUDA()) {
CUDA_CALL(kernel::pointcloud::
EstimateCovariancesUsingRadiusSearchCUDA,
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), radius.value());
} else if (IsSYCL()) {
#ifdef BUILD_SYCL_MODULE
kernel::pointcloud::EstimateCovariancesUsingRadiusSearchSYCL(
this->GetPointPositions().Contiguous(),
this->GetPointAttr("covariances"), radius.value());
#else
utility::LogError(
"Not compiled with SYCL, but SYCL device is used.");
#endif
} else {
utility::LogError("Unimplemented device");
}
} else {
utility::LogError("Both max_nn and radius are none.");
}
// Estimate `normal` of each point using its `covariance` matrix.
if (IsCPU()) {
kernel::pointcloud::EstimateNormalsFromCovariancesCPU(
this->GetPointAttr("covariances"), this->GetPointNormals(),
has_normals);
} else if (IsCUDA()) {
CUDA_CALL(kernel::pointcloud::EstimateNormalsFromCovariancesCUDA,
this->GetPointAttr("covariances"), this->GetPointNormals(),
has_normals);
} else if (IsSYCL()) {
#ifdef BUILD_SYCL_MODULE
kernel::pointcloud::EstimateNormalsFromCovariancesSYCL(
this->GetPointAttr("covariances"), this->GetPointNormals(),
has_normals);
#else
utility::LogError("Not compiled with SYCL, but SYCL device is used.");
#endif
} else {
utility::LogError("Unimplemented device");
}
// TODO (@rishabh): Don't remove covariances attribute, when
// EstimateCovariance functionality is exposed.
RemovePointAttr("covariances");
}
void PointCloud::OrientNormalsToAlignWithDirection(
const core::Tensor& orientation_reference) {
core::AssertTensorDevice(orientation_reference, GetDevice());
core::AssertTensorShape(orientation_reference, {3});
if (!HasPointNormals()) {