Skip to content

sampling

Transforms that select a subset of the points.

Classes:

  • RandomSample –

    Randomly sample a fixed number of points from dict entries.

  • RandomSampleFaceVertices –

    Randomly sample a fixed number of vertices from a 3D mesh stored in a dictionary.

  • FarthestPointSample –

    Farthest-point sampling (FPS) of a dictionary entry.

  • RandomDropout –

    Randomly drop a fraction of points across all listed keys.

  • SphereCrop –

    Keep only points inside an L2 sphere of given radius.

  • RandomBlockCrop –

    Keep the points of a random vertical block: a square window of the ground plane, full height.

  • Slice –

    Slice each listed tensor along a chosen dimension via standard Python slicing.

  • ShufflePoint –

    Randomly permute the order of points across listed keys.

RandomSample [source] ΒΆ

RandomSample(
    keys: KeyCollection,
    num_samples: int,
    replace: bool = False,
    seed: Optional[int] = None,
    dst_index_key: Optional[str] = None,
    allow_missing_keys: bool = False,
    allow_fewer: bool = False,
)

Bases: DictTransform, Randomizable

Randomly sample a fixed number of points from dict entries.

If multiple keys are provided, the same indices are used for all keys, ensuring correspondence between the sampled values.

RandomSample on an object

RandomSample on a room

See Also

torch_pointcloud.transforms.functional.random_sample

Parameters:

  • keys (KeyCollection) –

    The keys to sample from.

  • num_samples (int) –

    The number of values to sample.

  • replace (bool, default: False ) –

    If True, sample with replacement (duplicates allowed). If False (default), sample without replacement when the first sampled key has at least num_samples points; when num_samples exceeds that count the draw falls back to replacement so the output always has num_samples rows.

  • seed (Optional[int], default: None ) –

    Seed of the transform's own random stream; None draws from the global generator (see Randomizable).

  • dst_index_key (Optional[str], default: None ) –

    Key for the output-to-input row map (see the module docs on sampling keys); None (the default) disables it.

  • allow_missing_keys (bool, default: False ) –

    If True, the transform will not raise an error if the keys are not present in the data.

  • allow_fewer (bool, default: False ) –

    If True, a cloud with at most num_samples points passes through unchanged instead of being completed by draws with replacement.

Raises:

  • ValueError –

    If the first sampled tensor is empty and num_samples > 0.

RandomSampleFaceVertices [source] ΒΆ

RandomSampleFaceVertices(
    *,
    keys: KeyCollection,
    face_key: KeyCollection,
    dst_normal_key: Optional[KeyCollection] = "normal",
    num_samples: int,
    seed: Optional[int] = None,
    allow_missing_keys: bool = False,
)

Bases: DictTransform, Randomizable

Randomly sample a fixed number of vertices from a 3D mesh stored in a dictionary.

RandomSampleFaceVertices before / after

See Also

torch_pointcloud.transforms.functional.random_sample_face_vertices

Parameters:

  • keys (KeyCollection) –

    The keys holding vertex positions.

  • face_key (KeyCollection) –

    The keys holding the face indices.

  • dst_normal_key (Optional[KeyCollection], default: 'normal' ) –

    The key to store the computed normals in.

  • num_samples (int) –

    The number of vertices to sample.

  • seed (Optional[int], default: None ) –

    Seed of the transform's own random stream; None draws from the global generator (see Randomizable).

  • allow_missing_keys (bool, default: False ) –

    If True, the transform will not raise an error if the keys are not present in the data.

FarthestPointSample [source] ΒΆ

FarthestPointSample(
    pos_key: str,
    keys: Optional[KeyCollection] = None,
    num_samples: Optional[int] = None,
    ratio: Optional[float] = None,
    random_start: bool = False,
    dst_index_key: Optional[str] = None,
    allow_missing_keys: bool = False,
)

Bases: DictTransform

Farthest-point sampling (FPS) of a dictionary entry.

Iteratively picks the point that maximizes the minimum distance to the already-selected set, producing a well-distributed subset. Matches the FPS convention used by PointNet++, PointNeXt, KPConv, and others.

FarthestPointSample on an object

FarthestPointSample on a room

See Also

torch_pointcloud.transforms.functional.farthest_point_sample

Note

The underlying fps does not accept a torch.Generator. To make random_start=True reproducible, seed PyTorch globally via torch.manual_seed(...) before applying this transform.

Parameters:

  • pos_key (str) –

    The key holding the positions used for FPS.

  • keys (Optional[KeyCollection], default: None ) –

    Extra keys to subsample with the same indices.

  • num_samples (Optional[int], default: None ) –

    The number of points to sample.

  • ratio (Optional[float], default: None ) –

    The ratio of points to sample.

  • random_start (bool, default: False ) –

    Whether to start the sampling from a random point.

  • dst_index_key (Optional[str], default: None ) –

    Key for the output-to-input row map (see the module docs on sampling keys); None (the default) disables it.

  • allow_missing_keys (bool, default: False ) –

    If True, the transform will not raise an error if the keys are not present in the data.

RandomDropout [source] ΒΆ

RandomDropout(
    keys: KeyCollection,
    drop_ratio_range: Tuple[float, float] = (0.1, 0.1),
    p: float = 1.0,
    seed: Optional[int] = None,
    dst_index_key: Optional[str] = None,
    allow_missing_keys: bool = False,
)

Bases: DictTransform, Randomizable

Randomly drop a fraction of points across all listed keys.

The same boolean keep-mask is applied to every key so per-point correspondence is preserved. Sampling is once per call, with a drop ratio drawn uniformly from drop_ratio_range.

RandomDropout on an object

RandomDropout on a room

See Also

torch_pointcloud.transforms.functional.random_dropout_mask

Parameters:

  • keys (KeyCollection) –

    Keys to subset. All must share the same leading dimension \(N\).

  • drop_ratio_range (Tuple[float, float], default: (0.1, 0.1) ) –

    Min and max fraction of points to drop; (r, r) drops a fixed fraction. Must lie in \([0, 1)\).

  • p (float, default: 1.0 ) –

    Probability of applying the transform.

  • seed (Optional[int], default: None ) –

    Seed of the transform's own random stream; None draws from the global generator (see Randomizable).

  • dst_index_key (Optional[str], default: None ) –

    Key for the output-to-input row map (see the module docs on sampling keys); None (the default) disables it.

  • allow_missing_keys (bool, default: False ) –

    If True, silently skip absent keys.

SphereCrop [source] ΒΆ

SphereCrop(
    pos_key: str,
    radius: float,
    max_nodes: Optional[int] = None,
    keys: Optional[KeyCollection] = None,
    center: Any = "centroid",
    p: float = 1.0,
    seed: Optional[int] = None,
    dst_index_key: Optional[str] = None,
    allow_missing_keys: bool = False,
    max_ratio: Optional[float] = None,
    dst_center_key: Optional[str] = None,
)

Bases: DictTransform, Randomizable

Keep only points inside an L2 sphere of given radius.

The mask is computed from pos_key and applied to every listed keys. Equivalent to Compose([SphereMask(...), ApplyMask(...)]), kept as a convenience preset (the dual of RemoveNearOrigin).

When max_nodes is set and the sphere holds more than max_nodes points, only the max_nodes nearest the center are kept, bounding memory on large scenes.

SphereCrop on an object

SphereCrop on a room

Parameters:

  • pos_key (str) –

    Key with positions used to compute the mask.

  • keys (Optional[KeyCollection], default: None ) –

    Extra keys to filter with the same mask.

  • center (Any, default: 'centroid' ) –

    Center of the sphere. If "centroid", uses the per-cloud centroid; if "random_point", picks a random point as the center; otherwise treat as a 3-vector.

  • radius (float) –

    Radius of the sphere (Euclidean).

  • max_nodes (Optional[int], default: None ) –

    Optional cap on the number of kept points. If None (default), no cap is applied; otherwise the max_nodes points nearest the center are kept.

  • max_ratio (Optional[float], default: None ) –

    Optional cap as a fraction of the input point count (keeps that fraction of the points nearest the center); combined with max_nodes by the minimum.

  • dst_center_key (Optional[str], default: None ) –

    Key receiving the center \((D,)\) the crop was taken around; None does not store it.

  • p (float, default: 1.0 ) –

    Probability of applying the transform.

  • seed (Optional[int], default: None ) –

    Seed for the random center (center="random_point") and the probability draw; None draws from the global generator (see Randomizable).

  • dst_index_key (Optional[str], default: None ) –

    Key for the output-to-input row map (see the module docs on sampling keys); None (the default) disables it.

  • allow_missing_keys (bool, default: False ) –

    If True, silently skip absent keys.

RandomBlockCrop [source] ΒΆ

RandomBlockCrop(
    pos_key: str,
    keys: Optional[KeyCollection] = None,
    block_size: float = 1.0,
    min_nodes: int = 1024,
    max_tries: int = 100,
    axes: Sequence[int] = (0, 1),
    dst_center_key: Optional[str] = None,
    seed: Optional[int] = None,
    dst_index_key: Optional[str] = None,
    allow_missing_keys: bool = False,
)

Bases: DictTransform, Randomizable

Keep the points of a random vertical block: a square window of the ground plane, full height.

A random point centers a block_size x block_size window over axes (the ground plane); the window is redrawn until it holds more than min_nodes points, up to max_tries draws, after which the largest draw is kept. The center is written under dst_center_key so SubtractItems(axes=...) can center the block on it.

Parameters:

  • pos_key (str) –

    Key holding the positions, \((N, D)\).

  • keys (Optional[KeyCollection], default: None ) –

    Extra per-point keys to crop with the same mask.

  • block_size (float, default: 1.0 ) –

    Side of the window, in the units of the positions.

  • min_nodes (int, default: 1024 ) –

    A draw is accepted once the window holds more than this many points.

  • max_tries (int, default: 100 ) –

    Number of draws before the largest window is kept.

  • axes (Sequence[int], default: (0, 1) ) –

    Axes of the window (the other axes are unbounded).

  • dst_center_key (Optional[str], default: None ) –

    Key receiving the window center, the drawn point \((D,)\); None does not store it.

  • seed (Optional[int], default: None ) –

    Seed of the transform's own random stream; None draws from the global generator (see Randomizable).

  • dst_index_key (Optional[str], default: None ) –

    Key for the output-to-input row map (see the module docs on sampling keys); None (the default) does not record it.

  • allow_missing_keys (bool, default: False ) –

    If True, silently skip absent keys.

Example
import torch
from torch_pointcloud.transforms import RandomBlockCrop
crop = RandomBlockCrop(pos_key="pos", keys="segment", block_size=1.0, min_nodes=10, seed=0)
data = {"pos": torch.rand(500, 3) * 4, "segment": torch.zeros(500, dtype=torch.long)}
out = crop(data)
bool((out["pos"].max(0).values - out["pos"].min(0).values)[:2].max() <= 1.0)  # True

Slice [source] ΒΆ

Slice(
    keys: KeyCollection,
    start: Optional[int] = None,
    stop: Optional[int] = None,
    step: Optional[int] = None,
    dim: int = 0,
    dst_keys: Optional[KeyCollection] = None,
    dst_index_key: Optional[str] = None,
    allow_missing_keys: bool = False,
)

Bases: DictTransform

Slice each listed tensor along a chosen dimension via standard Python slicing.

Useful for taking the first \(N\) rows (e.g. on FPS-sorted point clouds), or extracting a single column of pos into a separate key (set dim=1 with start=axis, stop=axis+1).

Slice diagram

Parameters:

  • keys (KeyCollection) –

    Keys to slice.

  • start (Optional[int], default: None ) –

    Start index (inclusive). None is equivalent to 0.

  • stop (Optional[int], default: None ) –

    Stop index (exclusive). None means "to the end".

  • step (Optional[int], default: None ) –

    Stride between selected positions. None is equivalent to 1.

  • dim (int, default: 0 ) –

    Dimension along which to slice. Defaults to 0 (the row axis).

  • dst_keys (Optional[KeyCollection], default: None ) –

    Where to store results. Defaults to keys.

  • dst_index_key (Optional[str], default: None ) –

    Key for the output-to-input row map (see the module docs on sampling keys), written only when dim == 0; None (the default) disables it. Leave it unset when dst_keys differ from keys, since the map would describe the dst_keys rows.

  • allow_missing_keys (bool, default: False ) –

    If True, silently skip absent keys.

Example
from torch_pointcloud.transforms import Slice

# First 1024 rows of `pos` (e.g. an FPS-sorted ModelNet sample).
Slice(keys="pos", stop=1024)

# Extract the gravity axis (z=2) into a `(N, 1)` `height` key.
Slice(keys="pos", start=2, stop=3, dim=1, dst_keys="height")

ShufflePoint [source] ΒΆ

ShufflePoint(
    keys: KeyCollection,
    p: float = 1.0,
    seed: Optional[int] = None,
    dst_index_key: Optional[str] = None,
    allow_missing_keys: bool = False,
)

Bases: DictTransform, Randomizable

Randomly permute the order of points across listed keys.

The same permutation is applied to every key so per-point correspondence is preserved. Useful before RandomSample when you want to break any structural ordering in the input.

See Also

torch_pointcloud.transforms.functional.shuffle_indices

ShufflePoint on an object

ShufflePoint on a room

Parameters:

  • keys (KeyCollection) –

    Keys to permute. All must share the same leading dimension \(N\).

  • p (float, default: 1.0 ) –

    Probability of applying the transform.

  • seed (Optional[int], default: None ) –

    Seed of the transform's own random stream; None draws from the global generator (see Randomizable).

  • dst_index_key (Optional[str], default: None ) –

    Key for the output-to-input row map (see the module docs on sampling keys); None (the default) disables it.

  • allow_missing_keys (bool, default: False ) –

    If True, silently skip absent keys.

random_sample [source] ΒΆ

random_sample(
    tensor: Tensor,
    num_samples: int,
    return_indices: Literal[True],
    replace: bool = False,
    generator: Optional[Generator] = None,
) -> Tuple[Tensor, Tensor]
random_sample(
    tensor: Tensor,
    num_samples: int,
    return_indices: Literal[False] = False,
    replace: bool = False,
    generator: Optional[Generator] = None,
) -> Tensor
random_sample(
    tensor: Tensor,
    num_samples: int,
    return_indices: bool = False,
    replace: bool = False,
    generator: Optional[Generator] = None,
) -> Union[Tensor, Tuple[Tensor, Tensor]]

Randomly sample a fixed number of values from a tensor.

Note

The data is sampled uniformly along dim=0.

Parameters:

  • tensor (Tensor) –

    The input tensor of shape \((N, \ldots)\).

  • num_samples (int) –

    The number of values to sample.

  • return_indices (bool, default: False ) –

    Whether to return the indices of the sampled values.

  • replace (bool, default: False ) –

    If True, sample with replacement (duplicates allowed). If False, sample without replacement when \(N \geq \text{num\_samples}\); when \(\text{num\_samples} > N\) the draw falls back to replacement so the output always has num_samples rows.

  • generator (Optional[Generator], default: None ) –

    The generator for the random number generator.

Returns:

  • Union[Tensor, Tuple[Tensor, Tensor]] –

    If return_indices is True, the function returns a tuple of the sampled values and their indices.

  • Union[Tensor, Tuple[Tensor, Tensor]] –

    Otherwise, it returns the sampled values.

Raises:

  • ValueError –

    If num_samples > 0 and the input is empty.

random_sample_face_vertices [source] ΒΆ

random_sample_face_vertices(
    vertices: Tensor,
    face: Tensor,
    num_samples: int,
    return_normals: Literal[True],
    generator: Optional[Generator] = None,
) -> Tuple[Tensor, Tensor]
random_sample_face_vertices(
    vertices: Tensor,
    face: Tensor,
    num_samples: int,
    return_normals: Literal[False] = False,
    generator: Optional[Generator] = None,
) -> Tensor
random_sample_face_vertices(
    vertices: Tensor,
    face: Tensor,
    num_samples: int,
    return_normals: bool,
    generator: Optional[Generator] = None,
) -> Union[Tensor, Tuple[Tensor, Tensor]]
random_sample_face_vertices(
    vertices: Tensor,
    face: Tensor,
    num_samples: int,
    return_normals: bool = False,
    generator: Optional[Generator] = None,
) -> Union[Tensor, Tuple[Tensor, Tensor]]

Randomly sample a fixed number of vertices from a 3D mesh (vertices, face), using:

Note

The data is sampled uniformly from the mesh.

Parameters:

  • vertices (Tensor) –

    The input tensor.

  • face (Tensor) –

    The input tensor.

  • num_samples (int) –

    The number of vertices to sample.

  • return_normals (bool, default: False ) –

    Whether to return the normal of the sampled vertices.

  • generator (Optional[Generator], default: None ) –

    The generator for the random number generator.

Returns:

  • Union[Tensor, Tuple[Tensor, Tensor]] –

    If return_normals is True, the function returns a tuple of the sampled vertices and their normal.

  • Union[Tensor, Tuple[Tensor, Tensor]] –

    Otherwise, it returns the sampled vertices.

farthest_point_sample [source] ΒΆ

farthest_point_sample(
    pos: Tensor,
    num_samples: Optional[int] = None,
    ratio: Optional[float] = None,
    random_start: bool = False,
) -> Tensor

Farthest-point sampling (FPS) from a tensor of positions.

Thin wrapper around torch_pointcloud.ops.cluster.fps, provided for convenience and naming symmetry with random_sample.

See Also

torch_pointcloud.ops.cluster.fps for more details and advanced usage.

Parameters:

  • pos (Tensor) –

    The input tensor of shape \((N, D)\).

  • num_samples (Optional[int], default: None ) –

    The number of points to sample.

  • ratio (Optional[float], default: None ) –

    The ratio of points to sample.

  • random_start (bool, default: False ) –

    Whether to start the sampling from a random point.

Returns:

  • Tensor –

    The indices of the sampled points, always num_samples of them when num_samples is given. A cloud with at

  • Tensor –

    most num_samples points keeps its original order instead of being reordered by farthest-point rank, and a

  • Tensor –

    smaller one is completed by cycling through its points, the repetition fps applies too. ratio >= 1

  • Tensor –

    returns torch.arange(N).

Examples:

>>> import torch
>>> from torch_pointcloud.transforms.functional import farthest_point_sample
>>> pos = torch.randn(100, 3)
>>> idx = farthest_point_sample(pos, num_samples=10)  # doctest: +SKIP
>>> print(idx.shape)  # doctest: +SKIP
torch.Size([10])

random_dropout_mask [source] ΒΆ

random_dropout_mask(
    n: int,
    drop_ratio: float,
    device: Optional[device] = None,
    generator: Optional[Generator] = None,
) -> Tensor

Return a boolean keep-mask of length n where each entry is kept with probability 1 - drop_ratio.

Parameters:

  • n (int) –

    Number of points.

  • drop_ratio (float) –

    Probability of dropping a point. Must be in \([0, 1)\).

  • device (Optional[device], default: None ) –

    Output device.

  • generator (Optional[Generator], default: None ) –

    Random generator for reproducibility.

Returns:

  • Tensor –

    Boolean tensor of shape \((n,)\).

Raises:

  • ValueError –

    If drop_ratio is not in [0, 1).

shuffle_indices [source] ΒΆ

shuffle_indices(
    n: int,
    device: Optional[device] = None,
    generator: Optional[Generator] = None,
) -> Tensor

Return a random permutation of [0, n).

Parameters:

  • n (int) –

    Sequence length.

  • device (Optional[device], default: None ) –

    Output device.

  • generator (Optional[Generator], default: None ) –

    Random generator for reproducibility.

Returns:

  • Tensor –

    Long tensor of shape \((n,)\).