pointtree 0.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pointtree/__init__.py +0 -0
- pointtree/config/__init__.py +5 -0
- pointtree/config/_config.py +19 -0
- pointtree/evaluation/__init__.py +7 -0
- pointtree/evaluation/_metrics.py +233 -0
- pointtree/evaluation/_time_tracker.py +45 -0
- pointtree/evaluation/_timer.py +29 -0
- pointtree/instance_segmentation/__init__.py +7 -0
- pointtree/instance_segmentation/_instance_segmentation_algorithm.py +232 -0
- pointtree/instance_segmentation/_multi_stage_algorithm.py +1218 -0
- pointtree/instance_segmentation/_priority_queue.py +107 -0
- pointtree/instance_segmentation/_utils.py +45 -0
- pointtree/io/__init__.py +19 -0
- pointtree/io/_base_point_cloud_reader.py +88 -0
- pointtree/io/_base_point_cloud_writer.py +90 -0
- pointtree/io/_csv_reader.py +83 -0
- pointtree/io/_csv_writer.py +76 -0
- pointtree/io/_las_reader.py +103 -0
- pointtree/io/_las_writer.py +145 -0
- pointtree/io/_point_cloud_io_data.py +19 -0
- pointtree/io/_point_cloud_reader.py +46 -0
- pointtree/io/_point_cloud_writer.py +45 -0
- pointtree/operations/__init__.py +9 -0
- pointtree/operations/_knn_search.py +277 -0
- pointtree/operations/_make_labels_consecutive.py +64 -0
- pointtree/operations/_pack_batch.py +61 -0
- pointtree/operations/_ravel_index.py +121 -0
- pointtree/operations/_voxel_downsampling.py +170 -0
- pointtree/visualization/__init__.py +7 -0
- pointtree/visualization/_color_palette.py +39 -0
- pointtree/visualization/_color_point_cloud.py +107 -0
- pointtree/visualization/_hex_to_rgb.py +29 -0
- pointtree/visualization/_save_tree_map.py +85 -0
- pointtree-0.0.0.dist-info/LICENSE +21 -0
- pointtree-0.0.0.dist-info/METADATA +114 -0
- pointtree-0.0.0.dist-info/RECORD +38 -0
- pointtree-0.0.0.dist-info/WHEEL +5 -0
- pointtree-0.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
""" Point cloud file writer for las and laz files. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["LasWriter"]
|
|
4
|
+
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
import laspy
|
|
8
|
+
import numpy
|
|
9
|
+
import pandas
|
|
10
|
+
|
|
11
|
+
from ._base_point_cloud_writer import BasePointCloudWriter
|
|
12
|
+
from ._point_cloud_io_data import PointCloudIoData
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class LasWriter(BasePointCloudWriter):
|
|
16
|
+
r"""
|
|
17
|
+
Point cloud file writer for las and laz files.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
maximum_resolution: Maximum resolution of point coordinates in meter. Corresponds to the scale parameter
|
|
21
|
+
used in the las/laz compression. Larger values result in a stronger compression and lower point cloud
|
|
22
|
+
resolution. Defaults to :math:`10^{-6}` m.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
maximum_resolution: Maximum resolution of point coordinates in meter.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
_standard_field_defaults = {"return_number": 1, "number_of_returns": 1}
|
|
29
|
+
|
|
30
|
+
_supported_las_formats = list(range(9))
|
|
31
|
+
|
|
32
|
+
def __init__(self, maximum_resolution: float = 1e-6) -> None:
|
|
33
|
+
super().__init__()
|
|
34
|
+
self.maximum_resolution = maximum_resolution
|
|
35
|
+
|
|
36
|
+
def supported_file_formats(self) -> List[str]:
|
|
37
|
+
"""
|
|
38
|
+
Returns:
|
|
39
|
+
File formats supported by the point cloud file writer.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
return ["las", "laz"]
|
|
43
|
+
|
|
44
|
+
def _select_point_format(self, point_cloud: pandas.DataFrame) -> int:
|
|
45
|
+
"""
|
|
46
|
+
Determines the las file format that covers the most columns of the given point cloud.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
ID of the chosen las file format.
|
|
50
|
+
"""
|
|
51
|
+
columns = point_cloud.columns
|
|
52
|
+
best_format = 0
|
|
53
|
+
covered_columns = 0
|
|
54
|
+
|
|
55
|
+
for f in LasWriter._supported_las_formats:
|
|
56
|
+
current_format = laspy.point.format.PointFormat(f)
|
|
57
|
+
columns_covered_by_current_format = len(set(current_format.standard_dimension_names).intersection(columns))
|
|
58
|
+
if columns_covered_by_current_format > covered_columns:
|
|
59
|
+
covered_columns = columns_covered_by_current_format
|
|
60
|
+
best_format = current_format
|
|
61
|
+
|
|
62
|
+
return best_format
|
|
63
|
+
|
|
64
|
+
def _write_data(
|
|
65
|
+
self,
|
|
66
|
+
point_cloud: pandas.DataFrame,
|
|
67
|
+
file_path: str,
|
|
68
|
+
*,
|
|
69
|
+
x_max_resolution: Optional[float] = None,
|
|
70
|
+
y_max_resolution: Optional[float] = None,
|
|
71
|
+
z_max_resolution: Optional[float] = None,
|
|
72
|
+
) -> None:
|
|
73
|
+
"""
|
|
74
|
+
Writes a point cloud to a file.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
point_cloud: Point cloud to be written.
|
|
78
|
+
file_path: Path of the output file.
|
|
79
|
+
x_max_resolution: Maximum resolution of the point cloud's x-coordinates in meter. Defaults to `None`.
|
|
80
|
+
y_max_resolution: Maximum resolution of the point cloud's y-coordinates in meter. Defaults to `None`.
|
|
81
|
+
z_max_resolution: Maximum resolution of the point cloud's z-coordinates in meter. Defaults to `None`.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
if set(["x", "x", "z"]).issubset(point_cloud.columns) and not set(["X", "Y", "Z"]).issubset(
|
|
85
|
+
point_cloud.columns
|
|
86
|
+
):
|
|
87
|
+
point_cloud = point_cloud.rename({"x": "X", "y": "Y", "z": "Z"}, axis=1)
|
|
88
|
+
|
|
89
|
+
if set(["r", "g", "b"]).issubset(point_cloud.columns) and not set(["red", "green", "blue"]).issubset(
|
|
90
|
+
point_cloud.columns
|
|
91
|
+
):
|
|
92
|
+
point_cloud = point_cloud.rename({"r": "red", "g": "green", "b": "blue"}, axis=1)
|
|
93
|
+
|
|
94
|
+
las_data = laspy.create(point_format=self._select_point_format(point_cloud))
|
|
95
|
+
point_coords = point_cloud[["X", "Y", "Z"]].values
|
|
96
|
+
offsets = point_coords.min(axis=0)
|
|
97
|
+
scales = [self.maximum_resolution] * 3
|
|
98
|
+
if x_max_resolution is not None:
|
|
99
|
+
scales[0] = x_max_resolution
|
|
100
|
+
if y_max_resolution is not None:
|
|
101
|
+
scales[1] = y_max_resolution
|
|
102
|
+
if z_max_resolution is not None:
|
|
103
|
+
scales[2] = z_max_resolution
|
|
104
|
+
|
|
105
|
+
las_data.change_scaling(scales=scales, offsets=offsets)
|
|
106
|
+
las_data.xyz = point_coords
|
|
107
|
+
|
|
108
|
+
extra_columns = list(point_cloud.columns)
|
|
109
|
+
|
|
110
|
+
for column_name in las_data.header.point_format.standard_dimension_names:
|
|
111
|
+
if column_name.lower() in ["x", "y", "z"]:
|
|
112
|
+
continue
|
|
113
|
+
|
|
114
|
+
if column_name.lower() in point_cloud.columns:
|
|
115
|
+
las_data[column_name] = point_cloud[column_name.lower()]
|
|
116
|
+
extra_columns.remove(column_name.lower())
|
|
117
|
+
else:
|
|
118
|
+
default_value = LasWriter._standard_field_defaults.get(column_name, 0)
|
|
119
|
+
las_data[column_name] = numpy.full_like(las_data[column_name], fill_value=default_value)
|
|
120
|
+
|
|
121
|
+
for column_name in extra_columns:
|
|
122
|
+
if column_name.lower() in ["x", "y", "z"]:
|
|
123
|
+
continue
|
|
124
|
+
las_data.add_extra_dim(laspy.point.ExtraBytesParams(column_name, point_cloud[column_name].dtype))
|
|
125
|
+
las_data.update_header()
|
|
126
|
+
las_data[column_name] = point_cloud[column_name]
|
|
127
|
+
|
|
128
|
+
las_data.write(file_path)
|
|
129
|
+
|
|
130
|
+
def write(self, point_cloud: PointCloudIoData, file_path: str, columns: Optional[List[str]] = None) -> None:
|
|
131
|
+
"""
|
|
132
|
+
Writes a point cloud to a file.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
point_cloud: Point cloud to be written.
|
|
136
|
+
file_path: Path of the output file.
|
|
137
|
+
columns: Point cloud columns to be written. The x, y, and z columns are always written.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
ValueError: If the point cloud format is not supported by the writer or if `columns` contains a column name
|
|
141
|
+
that is not existing in the point cloud.
|
|
142
|
+
"""
|
|
143
|
+
# The method from the base is called explicitly so that the read method appears in the documentation of this
|
|
144
|
+
# class.
|
|
145
|
+
super().write(point_cloud, file_path, columns=columns)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
""" Point cloud data structure used for I/O. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["PointCloudIoData"]
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import pandas
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class PointCloudIoData:
|
|
13
|
+
"""Point cloud data structure used ."""
|
|
14
|
+
|
|
15
|
+
data: pandas.DataFrame
|
|
16
|
+
identifier: Optional[str] = None
|
|
17
|
+
x_max_resolution: Optional[float] = None
|
|
18
|
+
y_max_resolution: Optional[float] = None
|
|
19
|
+
z_max_resolution: Optional[float] = None
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
""" Point cloud file reader for csv, las, laz, and txt files. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["PointCloudReader"]
|
|
4
|
+
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
from ._csv_reader import CsvReader
|
|
8
|
+
from ._las_reader import LasReader
|
|
9
|
+
from ._point_cloud_io_data import PointCloudIoData
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PointCloudReader:
|
|
13
|
+
"""Point cloud file reader for csv, las, laz, and txt files."""
|
|
14
|
+
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self._readers = {}
|
|
17
|
+
for reader in [CsvReader(), LasReader()]:
|
|
18
|
+
for file_format in reader.supported_file_formats():
|
|
19
|
+
self._readers[file_format] = reader
|
|
20
|
+
|
|
21
|
+
def supported_file_formats(self) -> List[str]:
|
|
22
|
+
"""
|
|
23
|
+
Returns:
|
|
24
|
+
File formats supported by the point cloud file reader.
|
|
25
|
+
"""
|
|
26
|
+
return list(self._readers.keys())
|
|
27
|
+
|
|
28
|
+
def read(self, file_path: str, columns: Optional[List[str]] = None) -> PointCloudIoData:
|
|
29
|
+
"""
|
|
30
|
+
Reads a point cloud file.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
file_path: Path of the point cloud file to be read.
|
|
34
|
+
columns: Name of the point cloud columns to be read. The x, y, and z columns are always read.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
Point cloud object.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
ValueError: If the point cloud format is not supported by the reader.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
file_format = file_path.split(".")[-1]
|
|
44
|
+
if file_format not in self.supported_file_formats():
|
|
45
|
+
raise ValueError(f"The {file_format} format is not supported by the point cloud reader.")
|
|
46
|
+
return self._readers[file_format].read(file_path, columns=columns)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
""" Point cloud file writer for csv, las, laz, and txt files. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["PointCloudWriter"]
|
|
4
|
+
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
from ._csv_writer import CsvWriter
|
|
8
|
+
from ._las_writer import LasWriter
|
|
9
|
+
from ._point_cloud_io_data import PointCloudIoData
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PointCloudWriter:
|
|
13
|
+
"""Point cloud file writer for csv, las, laz, and txt files."""
|
|
14
|
+
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self._writers = {}
|
|
17
|
+
for writer in [CsvWriter(), LasWriter()]:
|
|
18
|
+
for file_format in writer.supported_file_formats():
|
|
19
|
+
self._writers[file_format] = writer
|
|
20
|
+
|
|
21
|
+
def supported_file_formats(self) -> List[str]:
|
|
22
|
+
"""
|
|
23
|
+
Returns:
|
|
24
|
+
File formats supported by the point cloud file writer.
|
|
25
|
+
"""
|
|
26
|
+
return list(self._writers.keys())
|
|
27
|
+
|
|
28
|
+
def write(self, point_cloud: PointCloudIoData, file_path: str, columns: Optional[List[str]] = None) -> None:
|
|
29
|
+
"""
|
|
30
|
+
Writes a point cloud to a file.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
point_cloud: Point cloud to be written.
|
|
34
|
+
file_path: Path of the output file.
|
|
35
|
+
columns: Point cloud columns to be written. The x, y, and z columns are always written.
|
|
36
|
+
|
|
37
|
+
Raises:
|
|
38
|
+
ValueError: If the point cloud format is not supported by the writer or if `columns` contains a column name
|
|
39
|
+
that is not existing in the point cloud.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
file_format = file_path.split(".")[-1]
|
|
43
|
+
if file_format not in self.supported_file_formats():
|
|
44
|
+
raise ValueError(f"The {file_format} format is not supported by the point cloud writer.")
|
|
45
|
+
return self._writers[file_format].write(point_cloud, file_path, columns=columns)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
""" Algorithms for tree instance segmentation. """
|
|
2
|
+
|
|
3
|
+
from ._knn_search import *
|
|
4
|
+
from ._make_labels_consecutive import *
|
|
5
|
+
from ._pack_batch import *
|
|
6
|
+
from ._ravel_index import *
|
|
7
|
+
from ._voxel_downsampling import *
|
|
8
|
+
|
|
9
|
+
__all__ = [name for name in globals().keys() if not name.startswith("_")]
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
""" Different implementations of kNN search. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["knn_search", "knn_search_pytorch3d", "knn_search_torch_cluster"]
|
|
4
|
+
|
|
5
|
+
from typing import Tuple
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
import torch_cluster
|
|
9
|
+
|
|
10
|
+
from pointtree.config import pytorch3d_is_available
|
|
11
|
+
from ._pack_batch import pack_batch
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def knn_search(
|
|
15
|
+
coords_support_points: torch.Tensor,
|
|
16
|
+
coords_query_points: torch.Tensor,
|
|
17
|
+
batch_indices_support_points: torch.Tensor,
|
|
18
|
+
batch_indices_query_points: torch.Tensor,
|
|
19
|
+
point_cloud_sizes_support_points: torch.Tensor,
|
|
20
|
+
point_cloud_sizes_query_points: torch.Tensor,
|
|
21
|
+
k: int,
|
|
22
|
+
return_sorted: bool = True,
|
|
23
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
24
|
+
r"""
|
|
25
|
+
Computes the indices of `k` nearest neighbors. Decides between different implementations:
|
|
26
|
+
|
|
27
|
+
- **Implementation from PyTorch3D:** This implementation is always used if PyTorch3D is installed because its more \
|
|
28
|
+
efficient in terms of runtime and memory consumption than the other available implementations.
|
|
29
|
+
- **Implementation from torch-cluster:** This implementation is used when PyTorch3D is not installed. It is \
|
|
30
|
+
similar to the PyTorch3D implementation but is slighlty slower.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
coords_support_points: Coordinates of the support points to be searched for neighbors.
|
|
34
|
+
coords_query_points: Coordinates of the query points.
|
|
35
|
+
batch_indices_support_points: Indices indicating to which point cloud in the batch each support point belongs.
|
|
36
|
+
batch_indices_query_points: Indices indicating to which point cloud in the batch each query point belongs.
|
|
37
|
+
point_cloud_sizes_support_points: Number of points in each point cloud in the batch of support points.
|
|
38
|
+
point_cloud_sizes_query_points: Number of points in each point cloud in the batch of query points.
|
|
39
|
+
k: The number of nearest neighbors to search.
|
|
40
|
+
return_sorted: Whether the returned neighbors should be sorted by their distance to the query point. Defaults to
|
|
41
|
+
`True`. Setting it to `False` can improve performance for some implementations.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
Tuple of two tensors. The first tensor contains the indices of the neighbors of each query point. The
|
|
45
|
+
second tensor contains the distances between the neighbors and the query points.
|
|
46
|
+
|
|
47
|
+
Shape:
|
|
48
|
+
- :attr:`coords_support_points`: :math:`(N, 3)`
|
|
49
|
+
- :attr:`coords_query_points`: :math:`(N', 3)`
|
|
50
|
+
- :attr:`batch_indices_support_points`: :math:`(N)`
|
|
51
|
+
- :attr:`batch_indices_query_points`: :math:`(N')`
|
|
52
|
+
- :attr:`point_cloud_sizes_support_points`: :math:`(B)`
|
|
53
|
+
- :attr:`point_cloud_sizes_query_points`: :math:`(B)`
|
|
54
|
+
- Output: Tuple of two tensors, both with shape :math:`(N', k)` if :attr:`k` :math:`\leq n_{max}`, \
|
|
55
|
+
otherwise :math:`(N', n_{max})`.
|
|
56
|
+
|
|
57
|
+
| where
|
|
58
|
+
|
|
|
59
|
+
| :math:`B = \text{ batch size}`
|
|
60
|
+
| :math:`N = \text{ number of support points}`
|
|
61
|
+
| :math:`N' = \text{ number of query points}`
|
|
62
|
+
| :math:`n_{max} = \text{ maximum number of neighbors a query point has}`
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
if pytorch3d_is_available():
|
|
66
|
+
return knn_search_pytorch3d(
|
|
67
|
+
coords_support_points,
|
|
68
|
+
coords_query_points,
|
|
69
|
+
batch_indices_query_points,
|
|
70
|
+
point_cloud_sizes_support_points,
|
|
71
|
+
point_cloud_sizes_query_points,
|
|
72
|
+
k,
|
|
73
|
+
return_sorted=return_sorted,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
return knn_search_torch_cluster(
|
|
77
|
+
coords_support_points,
|
|
78
|
+
coords_query_points,
|
|
79
|
+
batch_indices_support_points,
|
|
80
|
+
batch_indices_query_points,
|
|
81
|
+
point_cloud_sizes_support_points,
|
|
82
|
+
k,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def knn_search_pytorch3d(
|
|
87
|
+
coords_support_points: torch.Tensor,
|
|
88
|
+
coords_query_points: torch.Tensor,
|
|
89
|
+
batch_indices_query_points: torch.Tensor,
|
|
90
|
+
point_cloud_sizes_support_points: torch.Tensor,
|
|
91
|
+
point_cloud_sizes_query_points: torch.Tensor,
|
|
92
|
+
k: int,
|
|
93
|
+
return_sorted: bool = True,
|
|
94
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
95
|
+
r"""
|
|
96
|
+
Computes the indices of `k` nearest neighbors. This implementation is based on
|
|
97
|
+
`PyTorch3D's knn_points <https://pytorch3d.readthedocs.io/en/latest/modules/ops.html#pytorch3d.ops.knn_points>`_
|
|
98
|
+
function.
|
|
99
|
+
|
|
100
|
+
The GPU-based KNN search implementation from PyTorch3D launches one CUDA thread per query point and each thread then
|
|
101
|
+
loops through all the support points to find the k-nearest neighbors. It is similar to the torch-cluster
|
|
102
|
+
implementation but it requires input batches of regular shape. Therefore, the variable size point cloud batches are
|
|
103
|
+
packed into regular shaped batches before passing them to PyTorch3D.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
coords_support_points: Coordinates of the support points to be searched for neighbors.
|
|
107
|
+
coords_query_points: Coordinates of the query points.
|
|
108
|
+
batch_indices_query_points: Indices indicating to which point cloud in the batch each query point belongs.
|
|
109
|
+
point_cloud_sizes_support_points: Number of points in each point cloud in the batch of support points.
|
|
110
|
+
point_cloud_sizes_query_points: Number of points in each point cloud in the batch of query points.
|
|
111
|
+
k: The number of nearest neighbors to search.
|
|
112
|
+
return_sorted: Whether the returned neighbors should be sorted by their distance to the query point. Defaults to
|
|
113
|
+
`True`. Setting it to `False` can improve performance for some implementations.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
Tuple of two tensors. The first tensor contains the indices of the neighbors of each query point. The
|
|
117
|
+
second tensor contains the distances between the neighbors and the query points.
|
|
118
|
+
|
|
119
|
+
Shape:
|
|
120
|
+
- :attr:`coords_support_points`: :math:`(N, 3)`
|
|
121
|
+
- :attr:`coords_query_points`: :math:`(N', 3)`
|
|
122
|
+
- :attr:`batch_indices_query_points`: :math:`(N')`
|
|
123
|
+
- :attr:`point_cloud_sizes_support_points`: :math:`(B)`
|
|
124
|
+
- :attr:`point_cloud_sizes_query_points`: :math:`(B)`
|
|
125
|
+
- Output: Tuple of two tensors, both with shape :math:`(N', k)` if :attr:`k` :math:`\leq n_{max}`, \
|
|
126
|
+
otherwise :math:`(N', n_{max})`.
|
|
127
|
+
|
|
128
|
+
| where
|
|
129
|
+
|
|
|
130
|
+
| :math:`B = \text{ batch size}`
|
|
131
|
+
| :math:`N = \text{ number of support points}`
|
|
132
|
+
| :math:`N' = \text{ number of query points}`
|
|
133
|
+
| :math:`n_{max} = \text{ maximum number of neighbors a query point has}`
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
# the import is placed inside this method because the Pytorch3D package is an optional dependency and might not be
|
|
137
|
+
# available on all systems
|
|
138
|
+
from pytorch3d.ops import knn_points # pylint: disable=import-error,import-outside-toplevel
|
|
139
|
+
|
|
140
|
+
invalid_neighbor_index = len(coords_support_points)
|
|
141
|
+
|
|
142
|
+
k = min(k, int(point_cloud_sizes_support_points.amax().item()))
|
|
143
|
+
|
|
144
|
+
coords_support_points = coords_support_points.float()
|
|
145
|
+
coords_query_points = coords_query_points.float()
|
|
146
|
+
|
|
147
|
+
coords_query_points, mask_query_points = pack_batch(
|
|
148
|
+
coords_query_points, point_cloud_sizes_query_points, fill_value=-torch.inf
|
|
149
|
+
)
|
|
150
|
+
coords_support_points, _ = pack_batch(coords_support_points, point_cloud_sizes_support_points, fill_value=torch.inf)
|
|
151
|
+
|
|
152
|
+
neighbor_distances, neighbor_indices, _ = knn_points(
|
|
153
|
+
coords_query_points,
|
|
154
|
+
coords_support_points,
|
|
155
|
+
point_cloud_sizes_query_points,
|
|
156
|
+
point_cloud_sizes_support_points,
|
|
157
|
+
K=k,
|
|
158
|
+
return_sorted=return_sorted,
|
|
159
|
+
return_nn=False,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
# PyTorch3D return squared distances
|
|
163
|
+
neighbor_distances = torch.sqrt(neighbor_distances)
|
|
164
|
+
|
|
165
|
+
# flatten packed batch
|
|
166
|
+
batch_start_index = torch.cumsum(point_cloud_sizes_support_points, dim=0) - point_cloud_sizes_support_points
|
|
167
|
+
batch_start_index = batch_start_index.unsqueeze(-1).unsqueeze(-1) # convert to shape (B, 1, 1)
|
|
168
|
+
neighbor_indices += batch_start_index
|
|
169
|
+
|
|
170
|
+
neighbor_indices = neighbor_indices[mask_query_points].view(-1, k) # (N' k)
|
|
171
|
+
neighbor_distances = neighbor_distances[mask_query_points].view(-1, k)
|
|
172
|
+
|
|
173
|
+
if not (point_cloud_sizes_support_points >= k).all():
|
|
174
|
+
invalid_neighbor_mask = torch.arange(
|
|
175
|
+
k, dtype=point_cloud_sizes_support_points.dtype, device=point_cloud_sizes_support_points.device
|
|
176
|
+
).unsqueeze(
|
|
177
|
+
0
|
|
178
|
+
) # (1, k)
|
|
179
|
+
invalid_neighbor_mask = invalid_neighbor_mask.repeat((len(batch_indices_query_points), 1)) # (N', k)
|
|
180
|
+
max_neighbors = (point_cloud_sizes_support_points[batch_indices_query_points]).unsqueeze(-1)
|
|
181
|
+
invalid_neighbor_mask = invalid_neighbor_mask >= max_neighbors
|
|
182
|
+
neighbor_indices[invalid_neighbor_mask] = invalid_neighbor_index
|
|
183
|
+
neighbor_distances[invalid_neighbor_mask] = torch.inf
|
|
184
|
+
|
|
185
|
+
return neighbor_indices, neighbor_distances
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def knn_search_torch_cluster( # pylint: disable=too-many-locals
|
|
189
|
+
coords_support_points: torch.Tensor,
|
|
190
|
+
coords_query_points: torch.Tensor,
|
|
191
|
+
batch_indices_support_points: torch.Tensor,
|
|
192
|
+
batch_indices_query_points: torch.Tensor,
|
|
193
|
+
point_cloud_sizes_support_points: torch.Tensor,
|
|
194
|
+
k: int,
|
|
195
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
196
|
+
r"""
|
|
197
|
+
Computes the indices of `k` nearest neighbors. This implementation is based on the
|
|
198
|
+
`knn method from torch-cluster <https://github.com/rusty1s/pytorch_cluster>`_.
|
|
199
|
+
|
|
200
|
+
The GPU-based KNN search implementation from torch-cluster launches one CUDA thread per query point and each thread
|
|
201
|
+
then loops through all the support points to find the k-nearest neighbors. It is similar to the PyTorch3D
|
|
202
|
+
implementation but can handle variable size point clouds directly.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
coords_support_points: Coordinates of the support points to be searched for neighbors.
|
|
206
|
+
coords_query_points: Coordinates of the query points.
|
|
207
|
+
batch_indices_support_points: Indices indicating to which point cloud in the batch each support point belongs.
|
|
208
|
+
batch_indices_query_points: Indices indicating to which point cloud in the batch each query point belongs.
|
|
209
|
+
point_cloud_sizes_support_points: Number of points in each point cloud in the batch of support points.
|
|
210
|
+
k: The number of nearest neighbors to search.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
Tuple of two tensors. The first tensor contains the indices of the neighbors of each query point. The
|
|
214
|
+
second tensor contains the distances between the neighbors and the query points.
|
|
215
|
+
|
|
216
|
+
Shape:
|
|
217
|
+
- :attr:`coords_support_points`: :math:`(N, 3)`
|
|
218
|
+
- :attr:`coords_query_points`: :math:`(N', 3)`
|
|
219
|
+
- :attr:`batch_indices_support_points`: :math:`(N)`
|
|
220
|
+
- :attr:`batch_indices_query_points`: :math:`(N')`
|
|
221
|
+
- :attr:`point_cloud_sizes_support_points`: :math:`(B)`
|
|
222
|
+
- Output: Tuple of two tensors, both with shape :math:`(N', k)` if :attr:`k` :math:`\leq n_{max}`, \
|
|
223
|
+
otherwise :math:`(N', n_{max})`.
|
|
224
|
+
|
|
225
|
+
| where
|
|
226
|
+
|
|
|
227
|
+
| :math:`B = \text{ batch size}`
|
|
228
|
+
| :math:`N = \text{ number of support points}`
|
|
229
|
+
| :math:`N' = \text{ number of query points}`
|
|
230
|
+
| :math:`n_{max} = \text{ maximum number of neighbors a query point has}`
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
device = coords_query_points.device
|
|
234
|
+
num_query_points = len(coords_query_points)
|
|
235
|
+
invalid_neighbor_index = len(coords_support_points)
|
|
236
|
+
|
|
237
|
+
k = min(k, int(point_cloud_sizes_support_points.amax().item()))
|
|
238
|
+
|
|
239
|
+
neighbor_graph_edge_indices = torch_cluster.knn(
|
|
240
|
+
coords_support_points,
|
|
241
|
+
coords_query_points,
|
|
242
|
+
k,
|
|
243
|
+
batch_indices_support_points,
|
|
244
|
+
batch_indices_query_points,
|
|
245
|
+
batch_size=len(torch.unique(batch_indices_query_points)),
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
query_indices = neighbor_graph_edge_indices[0]
|
|
249
|
+
support_indices = neighbor_graph_edge_indices[1]
|
|
250
|
+
|
|
251
|
+
# compute neighbor distances
|
|
252
|
+
query_coords = coords_query_points[query_indices]
|
|
253
|
+
support_coords = coords_support_points[support_indices]
|
|
254
|
+
neighbor_distances = torch.linalg.norm(query_coords - support_coords, dim=-1) # pylint: disable=not-callable
|
|
255
|
+
|
|
256
|
+
if (point_cloud_sizes_support_points >= k).all():
|
|
257
|
+
neighbor_indices = support_indices.view(num_query_points, k)
|
|
258
|
+
neighbor_distances = neighbor_distances.view(num_query_points, k)
|
|
259
|
+
else:
|
|
260
|
+
_, neighbor_counts = torch.unique(query_indices, return_counts=True)
|
|
261
|
+
|
|
262
|
+
neighbor_indices = torch.full(
|
|
263
|
+
(num_query_points * k,), fill_value=invalid_neighbor_index, device=device, dtype=torch.long
|
|
264
|
+
)
|
|
265
|
+
valid_neighbor_mask = torch.arange(k, device=device).unsqueeze(0).repeat(num_query_points, 1)
|
|
266
|
+
valid_neighbor_mask = (valid_neighbor_mask < neighbor_counts.unsqueeze(-1)).view(-1)
|
|
267
|
+
|
|
268
|
+
neighbor_indices[valid_neighbor_mask] = support_indices
|
|
269
|
+
neighbor_indices = neighbor_indices.view(num_query_points, k)
|
|
270
|
+
|
|
271
|
+
neighbor_distances_full = torch.full(
|
|
272
|
+
(num_query_points * k,), fill_value=torch.inf, device=device, dtype=torch.float
|
|
273
|
+
)
|
|
274
|
+
neighbor_distances_full[valid_neighbor_mask] = neighbor_distances
|
|
275
|
+
neighbor_distances = neighbor_distances_full.view(num_query_points, k)
|
|
276
|
+
|
|
277
|
+
return neighbor_indices, neighbor_distances
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
""" Transformation of input labels into consecutive integer labels. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["make_labels_consecutive"]
|
|
4
|
+
|
|
5
|
+
from typing import Optional, Tuple, Union
|
|
6
|
+
|
|
7
|
+
import numpy
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_labels_consecutive(
|
|
11
|
+
labels: numpy.ndarray,
|
|
12
|
+
start_id: int = 0,
|
|
13
|
+
ignore_id: Optional[int] = None,
|
|
14
|
+
inplace: bool = False,
|
|
15
|
+
return_unique_labels: bool = False,
|
|
16
|
+
) -> Union[numpy.ndarray, Tuple[numpy.ndarray, numpy.ndarray]]:
|
|
17
|
+
"""
|
|
18
|
+
Transforms the input labels into consecutive integer labels starting from a given :code:`start_id`.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
labels: An array of original labels.
|
|
22
|
+
start_id: The starting ID for the consecutive labels. Defaults to zero.
|
|
23
|
+
ignore_id: A label ID that should not be changed when transforming the labels.
|
|
24
|
+
inplace: Whether the transformation should be applied inplace to the :code:`labels` array. Defaults to
|
|
25
|
+
:code:`False`.
|
|
26
|
+
return_unique_labels: Whether the unique labels after applying the transformation (excluding :code:`ignore_id`)
|
|
27
|
+
should be returned. Defaults to :code:`False`.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
An array with the transformed consecutive labels. If :code:`return_unique_labels` is set to :code:`True`, a
|
|
31
|
+
tuple of two arrays is returned, where the second array contains the unique labels after the transformation.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
if len(labels) == 0:
|
|
35
|
+
if return_unique_labels:
|
|
36
|
+
return labels, numpy.empty_like(labels)
|
|
37
|
+
return labels
|
|
38
|
+
|
|
39
|
+
if not inplace:
|
|
40
|
+
labels = labels.copy()
|
|
41
|
+
|
|
42
|
+
labels_to_remap: Union[numpy.ndarray, numpy.ma.MaskedArray]
|
|
43
|
+
if ignore_id is not None:
|
|
44
|
+
mask = labels != ignore_id
|
|
45
|
+
labels_to_remap = labels[mask]
|
|
46
|
+
else:
|
|
47
|
+
labels_to_remap = labels
|
|
48
|
+
|
|
49
|
+
unique_labels = numpy.unique(labels_to_remap)
|
|
50
|
+
unique_labels = numpy.sort(unique_labels)
|
|
51
|
+
key = numpy.arange(0, len(unique_labels))
|
|
52
|
+
index = numpy.digitize(labels_to_remap, unique_labels, right=True)
|
|
53
|
+
labels_to_remap[:] = key[index]
|
|
54
|
+
labels_to_remap += start_id
|
|
55
|
+
|
|
56
|
+
if ignore_id is not None:
|
|
57
|
+
labels[mask] = labels_to_remap
|
|
58
|
+
else:
|
|
59
|
+
labels[:] = labels_to_remap
|
|
60
|
+
|
|
61
|
+
if return_unique_labels:
|
|
62
|
+
return labels, key + start_id
|
|
63
|
+
|
|
64
|
+
return labels
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
""" Packing of batches containing point clouds of varying size into a regular batch structures. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["pack_batch"]
|
|
4
|
+
|
|
5
|
+
from typing import Tuple
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def pack_batch(
|
|
11
|
+
input_batch: torch.Tensor, point_cloud_sizes: torch.Tensor, fill_value: float = torch.inf
|
|
12
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
13
|
+
r"""
|
|
14
|
+
Packs a batch containing point clouds of varying size into a regular batch structure by padding all point clouds to
|
|
15
|
+
the same size.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
input_batch: Batch to be packed.
|
|
19
|
+
point_cloud_sizes: Number of points in each point cloud in the batch.
|
|
20
|
+
fill_value: Value to be used to pad point clouds that contain less points than the largest point cloud in the
|
|
21
|
+
batch. Defaults to `torch.inf`.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
Tuple of two tensors. The first tensor is the packed batch. Point clouds containing less than :math:`N_{max}`
|
|
25
|
+
points are padded with :attr:`fill_value`. The second tensor is a boolean mask, which is `True` in all positions
|
|
26
|
+
where the packed batch contains valid points and `False` in all positions filled with :attr:`fill_value`.
|
|
27
|
+
|
|
28
|
+
Shape:
|
|
29
|
+
- | :attr:`input_batch`: :math:`(N_1 + ... + N_B, D)`
|
|
30
|
+
- | :attr:`point_cloud_sizes`: :math:`(B)`
|
|
31
|
+
- | Output: Tuple of two tensors with shape :math:`(B, N_{max}, D)` and :math:`(B, N_{max})`.
|
|
32
|
+
|
|
|
33
|
+
| where
|
|
34
|
+
|
|
|
35
|
+
| :math:`B = \text{ batch size}`
|
|
36
|
+
| :math:`D = \text{ number of feature channels}`
|
|
37
|
+
| :math:`N_i = \text{ number of points in the i-th point cloud}`
|
|
38
|
+
| :math:`N_{max} = \text{ number of points in the largest point cloud in the batch}`
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
batch_size = len(point_cloud_sizes)
|
|
42
|
+
max_point_cloud_size = int(point_cloud_sizes.max().item())
|
|
43
|
+
num_channels = input_batch.size(-1)
|
|
44
|
+
|
|
45
|
+
if (point_cloud_sizes == max_point_cloud_size).all():
|
|
46
|
+
# in this case, all point clouds already have the same size and no padding is needed
|
|
47
|
+
|
|
48
|
+
mask = input_batch.new_ones((batch_size, max_point_cloud_size), dtype=torch.bool)
|
|
49
|
+
|
|
50
|
+
return input_batch.view(batch_size, max_point_cloud_size, num_channels), mask
|
|
51
|
+
|
|
52
|
+
packed_batch = input_batch.new_full((batch_size * max_point_cloud_size, num_channels), fill_value=fill_value)
|
|
53
|
+
|
|
54
|
+
mask = torch.arange(max_point_cloud_size, device=input_batch.device).unsqueeze(0).repeat(batch_size, 1)
|
|
55
|
+
mask = (mask < point_cloud_sizes.unsqueeze(-1)).view(-1)
|
|
56
|
+
|
|
57
|
+
packed_batch[mask] = input_batch
|
|
58
|
+
packed_batch = packed_batch.view(batch_size, max_point_cloud_size, num_channels)
|
|
59
|
+
mask = mask.view(batch_size, max_point_cloud_size)
|
|
60
|
+
|
|
61
|
+
return packed_batch, mask
|