Skip to content

Structuring Elements

Create and expand multidimensional connectivity structures for morphological operations.

torchmorph.generate_binary_structure

generate_binary_structure(rank, connectivity)

Generate an N-dimensional binary structuring element

The returned tensor has shape (3,) * rank. Elements whose offset differs from the center along at most connectivity axes are True; all other elements are False. This matches SciPy's ndimage.generate_binary_structure connectivity convention.

Parameters:

Name Type Description Default
rank int

Number of spatial dimensions in the structuring element. Must be at least 1.

required
connectivity int

Neighborhood connectivity from 1 to rank. 1 includes axis-adjacent neighbors; rank includes the full 3 ** rank neighborhood.

required

Returns:

Type Description
Tensor

torch.Tensor: Boolean tensor with shape (3,) * rank.

Example
>>> import torch
>>> import torchmorph as tm
>>> tm.generate_binary_structure(2, 1).to(dtype=torch.int32)
tensor([[0, 1, 0],
        [1, 1, 1],
        [0, 1, 0]], dtype=torch.int32)
>>> tm.generate_binary_structure(2, 2).to(dtype=torch.int32)
tensor([[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]], dtype=torch.int32)

torchmorph.iterate_structure

iterate_structure(structure, iterations, origin=None)

Dilate a binary structuring element with itself repeatedly

The result is equivalent to applying the original structuring element iterations times in a morphology operation. Nonzero input values are treated as part of the structure.

Parameters:

Name Type Description Default
structure Tensor

N-dimensional binary structuring element.

required
iterations int

Number of copies to combine. Values below 2 return a boolean clone of structure.

required
origin int or tuple[int, ...]

Original anchor offset. A scalar is applied to every dimension. When supplied, the adjusted origin is returned with the iterated structure.

None

Returns:

Type Description
Tensor | tuple[Tensor, list[int]]

torch.Tensor or tuple[torch.Tensor, list[int]]: Boolean iterated

Tensor | tuple[Tensor, list[int]]

structure. If origin is supplied, returns (structure, origin)

Tensor | tuple[Tensor, list[int]]

with each origin component multiplied by iterations.

Example
>>> import torch
>>> import torchmorph as tm
>>> structure = tm.generate_binary_structure(2, 1)
>>> tm.iterate_structure(structure, 2).to(dtype=torch.int32)
tensor([[0, 0, 1, 0, 0],
        [0, 1, 1, 1, 0],
        [1, 1, 1, 1, 1],
        [0, 1, 1, 1, 0],
        [0, 0, 1, 0, 0]], dtype=torch.int32)