kornia.morphology#

Dilate, erode, open and close images (B, C, H, W) by a structuring element, and reconstruct them from a seed. Every function applies one 2D kernel to every channel: its non-zero cells form the neighborhood, and in every function except reconstruction() a structuring_element of the same shape makes the operation non-flat. dilation() reflects the kernel and erosion() does not, as in scipy.ndimage; Conventions & Pitfalls maps the kernels and the border modes onto scipy, scikit-image and OpenCV.

kornia.morphology.dilation(tensor, kernel, structuring_element=None, origin=None, border_type='geodesic', border_value=0.0, max_val=1e4, engine='auto')[source]#

Dilate an image: the maximum over each pixel’s neighborhood, with the kernel reflected.

out = dilation(tensor, kernel) takes a floating-point image (B, C, H, W) and a (k_h, k_w) kernel whose non-zero cells mark the neighborhood. It returns the (B, C, H, W) image whose every pixel is the maximum of tensor over the neighborhood placed at it.

_images/dilation.png
Convention:
  • dilation reflects the kernel: it is the Minkowski dilation \(\delta_B f(x) = \max_{b \in B} f(x - b)\), as in scipy.ndimage; erosion() does not reflect. Conventions & Pitfalls maps the kernels and the border modes onto scipy, scikit-image and OpenCV.

  • Under geodesic a window with no kernel cell inside the image is empty and returns the reduction identity, -inf here and +inf in erosion(), as scipy and scikit-image do; so does every window of a kernel with no non-zero cell. The composite operations inherit these infinities.

Parameters:
  • tensor (Tensor) – floating-point image (B, C, H, W); another dtype raises TypeError, another rank ValueError.

  • kernel (Tensor) – (k_h, k_w) mask laid over the image’s (H, W) axes. Its non-zero cells form the neighborhood and their values are ignored; a floating-point kernel sets the dtype of the result (see Returns). For a full window pass torch.ones(k_h, k_w). Another rank raises ValueError.

  • structuring_element (Optional[Tensor], optional) – non-flat structuring element of kernel’s shape, added to the neighbor values before the maximum. Another shape raises ValueError. Default: None, a flat element.

  • origin (Optional[List[int]], optional) – [row, col] cell of kernel placed on the output pixel. Default: None, which uses [k_h // 2, k_w // 2] for odd and even sizes alike ([1, 1] for a \(2 \times 2\) kernel).

  • border_type (str, optional) – "geodesic" (default) leaves the pixels outside the image out of the window; "constant", "reflect", "replicate" and "circular" pad with torch.nn.functional.pad(). "reflect" needs the pad the kernel asks for to stay below the image size and "circular" to stay at most equal to it; both raise RuntimeError otherwise. Any other value raises ValueError. Default: "geodesic"

  • border_value (float, optional) – fill value for border_type="constant"; the other modes ignore it. Default: 0.0.

  • max_val (float, optional) – no effect; excluded kernel cells and geodesic padding use the reduction identity \(\mp\infty\). Retained for backward compatibility. Default: 1e4

  • engine (str, optional) – "auto" (default), "unfold", "shift" or "convolution"; another value raises NotImplementedError. "unfold" and "shift" compute the same max-plus expression and, for finite inputs, return equal output up to the sign of a zero. "auto" picks "unfold" on CUDA and "shift" elsewhere, except that a CPU call which computes in float32 or float64 (the image dtype widened as described under Returns) and records a backward graph takes "unfold", where "shift" is slower. "convolution" runs through the backend’s conv2d and inherits its precision: a conv2d that computes float32 in reduced precision, as on macOS CPU, rounds the output. Forward-only, "shift" needs no k_h k_w-sized intermediate. Under autograd it saves 2 (k_h k_w - 1) output-sized tensors for backward, more memory than "unfold". Default: "auto"

Return type:

Tensor

Returns:

Dilated image (B, C, H, W). Its dtype is the image dtype promoted with that of structuring_element, or, without one, with that of a floating-point kernel: a float16 image with the float32 torch.ones(3, 3) returns float32, and with a bool kernel or a float16 one it stays float16.

See also

  • erosion(): the minimum over the neighborhood, with the kernel not reflected.

  • closing(): a dilation followed by an erosion, which fills dark details and keeps the rest.

  • gradient(): the dilation minus the erosion, an edge-strength map.

  • reconstruction(): repeats a dilation clipped to a mask until the result stops changing.

Note

See a working example here.

Example

>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> dilated_img = dilation(tensor, kernel)
kornia.morphology.erosion(tensor, kernel, structuring_element=None, origin=None, border_type='geodesic', border_value=0.0, max_val=1e4, engine='auto')[source]#

Erode an image: the minimum over each pixel’s neighborhood, without reflecting the kernel.

out = erosion(tensor, kernel) takes the inputs of dilation() and returns the (B, C, H, W) image whose every pixel is the minimum of tensor over the neighborhood placed at it.

_images/erosion.png
Convention:

As dilation(), except that erosion does not reflect the kernel: it is the Minkowski erosion \(\varepsilon_B f(x) = \min_{b \in B} f(x + b)\), as in scipy.ndimage and OpenCV.

Parameters:
  • tensor (Tensor) – floating-point image (B, C, H, W); another dtype raises TypeError, another rank ValueError.

  • kernel (Tensor) – (k_h, k_w) mask of the neighborhood, as in dilation().

  • structuring_element (Optional[Tensor], optional) – non-flat structuring element of kernel’s shape, subtracted from the neighbor values before the minimum. Default: None, a flat element.

  • origin (Optional[List[int]], optional) – [row, col] cell of kernel placed on the output pixel, as in dilation(). Default: None

  • border_type (str, optional) – border handling, as in dilation(). Default: "geodesic".

  • border_value (float, optional) – fill value for border_type="constant". Default: 0.0.

  • max_val (float, optional) – no effect, as in dilation(). Default: 1e4

  • engine (str, optional) – computation engine, as in dilation(). Default: "auto".

Return type:

Tensor

Returns:

Eroded image (B, C, H, W), in the dtype dilation() returns for the same inputs.

See also

  • dilation(): the maximum over the neighborhood, with the kernel reflected.

  • opening(): an erosion followed by a dilation, which removes bright details and keeps the rest.

  • gradient(): the dilation minus the erosion, an edge-strength map.

  • reconstruction(): with method="erosion", repeats an erosion bounded by a mask until the result stops changing.

Note

See a working example here.

Example

>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(5, 5)
>>> output = erosion(tensor, kernel)
kornia.morphology.opening(tensor, kernel, structuring_element=None, origin=None, border_type='geodesic', border_value=0.0, max_val=1e4, engine='auto')[source]#

Open an image: erode, then dilate, to remove the bright details the kernel does not fit in.

out = opening(tensor, kernel) is dilation(erosion(tensor, kernel), kernel) with the same arguments in both halves, and returns a (B, C, H, W) image.

_images/opening.png
Convention:

As only dilation() reflects the kernel, opening is a morphological opening (anti-extensive and idempotent) for an asymmetric kernel too, under geodesic or circular; a non-flat structuring_element or engine="convolution" holds both properties only to roundoff, and constant, reflect and replicate can break them.

Parameters:
  • tensor (Tensor) – floating-point image (B, C, H, W); another dtype raises TypeError, another rank ValueError.

  • kernel (Tensor) – (k_h, k_w) mask of the neighborhood, as in dilation().

  • structuring_element (Optional[Tensor], optional) – non-flat structuring element, as in dilation(). Default: None

  • origin (Optional[List[int]], optional) – [row, col] cell of kernel placed on the output pixel, as in dilation(). Default: None

  • border_type (str, optional) – border handling, as in dilation(). Default: "geodesic".

  • border_value (float, optional) – fill value for border_type="constant". Default: 0.0.

  • max_val (float, optional) – no effect, as in dilation(). Default: 1e4

  • engine (str, optional) – computation engine, as in dilation(). Default: "auto".

Return type:

Tensor

Returns:

Opened image (B, C, H, W), in the dtype dilation() returns for the same inputs.

See also

  • closing(): the dual, which fills the dark details instead.

  • top_hat(): the image minus its opening, the removed bright details alone.

  • erosion(): the first half alone, which also shrinks the shapes that are kept.

  • reconstruction(): opening by reconstruction, reconstruction(erosion(x, kernel), x); thin parts of a kept shape survive, unlike in opening.

Note

See a working example here.

Example

>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> opened_img = opening(tensor, kernel)
kornia.morphology.closing(tensor, kernel, structuring_element=None, origin=None, border_type='geodesic', border_value=0.0, max_val=1e4, engine='auto')[source]#

Close an image: dilate, then erode, to fill the dark details the kernel does not fit in.

out = closing(tensor, kernel) is erosion(dilation(tensor, kernel), kernel) with the same arguments in both halves, and returns a (B, C, H, W) image.

_images/closing.png
Convention:

As only dilation() reflects the kernel, closing is a morphological closing (extensive and idempotent) for an asymmetric kernel too, under geodesic or circular; a non-flat structuring_element or engine="convolution" holds both properties only to roundoff, and constant, reflect and replicate can break them.

Parameters:
  • tensor (Tensor) – floating-point image (B, C, H, W); another dtype raises TypeError, another rank ValueError.

  • kernel (Tensor) – (k_h, k_w) mask of the neighborhood, as in dilation().

  • structuring_element (Optional[Tensor], optional) – non-flat structuring element, as in dilation(). Default: None

  • origin (Optional[List[int]], optional) – [row, col] cell of kernel placed on the output pixel, as in dilation(). Default: None

  • border_type (str, optional) – border handling, as in dilation(). Default: "geodesic".

  • border_value (float, optional) – fill value for border_type="constant". Default: 0.0.

  • max_val (float, optional) – no effect, as in dilation(). Default: 1e4

  • engine (str, optional) – computation engine, as in dilation(). Default: "auto".

Return type:

Tensor

Returns:

Closed image (B, C, H, W), in the dtype dilation() returns for the same inputs.

See also

  • opening(): the dual, which removes the bright details instead.

  • bottom_hat(): the closing minus the image, the filled dark details alone.

  • dilation(): the first half alone, which also grows the shapes that are kept.

Note

See a working example here.

Example

>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> closed_img = closing(tensor, kernel)
kornia.morphology.gradient(tensor, kernel, structuring_element=None, origin=None, border_type='geodesic', border_value=0.0, max_val=1e4, engine='auto')[source]#

Compute the morphological gradient, the dilation minus the erosion, as an edge-strength map.

out = gradient(tensor, kernel) returns dilation(tensor, kernel) - erosion(tensor, kernel) with the same arguments, a (B, C, H, W) edge-strength map that is large where the image changes. Under a non-geodesic border, with inputs that keep the image dtype (see dilation()), it equals scipy.ndimage.morphological_gradient with the matching mode and cval=border_value. For a flat kernel (no structuring_element) symmetric about its origin it is the value range over each neighborhood.

_images/gradient.png
Parameters:
  • tensor (Tensor) – floating-point image (B, C, H, W); another dtype raises TypeError, another rank ValueError.

  • kernel (Tensor) – (k_h, k_w) mask of the neighborhood, as in dilation().

  • structuring_element (Optional[Tensor], optional) – non-flat structuring element, as in dilation(). Default: None

  • origin (Optional[List[int]], optional) – [row, col] cell of kernel placed on the output pixel, as in dilation(). Default: None

  • border_type (str, optional) – border handling, as in dilation(). Default: "geodesic".

  • border_value (float, optional) – fill value for border_type="constant". Default: 0.0.

  • max_val (float, optional) – no effect, as in dilation(). Default: 1e4

  • engine (str, optional) – computation engine, as in dilation(). Default: "auto".

Return type:

Tensor

Returns:

Gradient image (B, C, H, W), in the dtype dilation() returns for the same inputs.

See also

  • dilation(): the maximum over the neighborhood, the first term.

  • erosion(): the minimum over the neighborhood, the second term.

  • sobel(): the magnitude of the Sobel derivatives, from linear filters instead of a maximum and a minimum.

Note

See a working example here.

Example

>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> gradient_img = gradient(tensor, kernel)
kornia.morphology.top_hat(tensor, kernel, structuring_element=None, origin=None, border_type='geodesic', border_value=0.0, max_val=1e4, engine='auto')[source]#

Extract the bright details the kernel does not fit in: the image minus its opening.

out = top_hat(tensor, kernel) returns tensor - opening(tensor, kernel) with the same arguments, the (B, C, H, W) white top-hat: the bright details opening() removes, on a zero background.

_images/top_hat.png
Convention:

Under every border_type except geodesic, for inputs that keep the image dtype (see dilation()), with the mode mapped as in Conventions & Pitfalls and cval=border_value, it equals scipy.ndimage.white_tophat. OpenCV’s MORPH_TOPHAT, at its default border (kornia’s geodesic), BORDER_REPLICATE or BORDER_REFLECT_101, equals it only for a flat kernel (no structuring_element) symmetric about its origin: OpenCV takes no structuring element, and cv2.dilate does not reflect the kernel.

Parameters:
  • tensor (Tensor) – floating-point image (B, C, H, W); another dtype raises TypeError, another rank ValueError.

  • kernel (Tensor) – (k_h, k_w) mask of the neighborhood, as in dilation().

  • structuring_element (Optional[Tensor], optional) – non-flat structuring element, as in dilation(). Default: None

  • origin (Optional[List[int]], optional) – [row, col] cell of kernel placed on the output pixel, as in dilation(). Default: None

  • border_type (str, optional) – border handling, as in dilation(). Default: "geodesic".

  • border_value (float, optional) – fill value for border_type="constant". Default: 0.0.

  • max_val (float, optional) – no effect, as in dilation(). Default: 1e4

  • engine (str, optional) – computation engine, as in dilation(). Default: "auto".

Return type:

Tensor

Returns:

Top hat transformed image (B, C, H, W), in the dtype dilation() returns for the same inputs.

See also

  • bottom_hat(): the closing minus the image, the dark details.

  • opening(): the image with these details removed.

Note

See a working example here.

Example

>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> top_hat_img = top_hat(tensor, kernel)
kornia.morphology.bottom_hat(tensor, kernel, structuring_element=None, origin=None, border_type='geodesic', border_value=0.0, max_val=1e4, engine='auto')[source]#

Extract the dark details the kernel does not fit in: the closing of the image minus the image.

out = bottom_hat(tensor, kernel) returns closing(tensor, kernel) - tensor with the same arguments, the (B, C, H, W) black top-hat: the dark details closing() fills, as positive values on a zero background.

_images/bottom_hat.png
Convention:

Under every border_type except geodesic, for inputs that keep the image dtype (see dilation()), with the mode mapped as in Conventions & Pitfalls and cval=border_value, it equals scipy.ndimage.black_tophat. OpenCV’s MORPH_BLACKHAT, at its default border (kornia’s geodesic), BORDER_REPLICATE or BORDER_REFLECT_101, equals it only for a flat kernel (no structuring_element) symmetric about its origin: OpenCV takes no structuring element, and cv2.dilate does not reflect the kernel.

Parameters:
  • tensor (Tensor) – floating-point image (B, C, H, W); another dtype raises TypeError, another rank ValueError.

  • kernel (Tensor) – (k_h, k_w) mask of the neighborhood, as in dilation().

  • structuring_element (Optional[Tensor], optional) – non-flat structuring element, as in dilation(). Default: None

  • origin (Optional[List[int]], optional) – [row, col] cell of kernel placed on the output pixel, as in dilation(). Default: None

  • border_type (str, optional) – border handling, as in dilation(). Default: "geodesic".

  • border_value (float, optional) – fill value for border_type="constant". Default: 0.0.

  • max_val (float, optional) – no effect, as in dilation(). Default: 1e4

  • engine (str, optional) – computation engine, as in dilation(). Default: "auto".

Return type:

Tensor

Returns:

Bottom hat transformed image (B, C, H, W), in the dtype dilation() returns for the same inputs.

See also

  • top_hat(): the image minus its opening, the bright details.

  • closing(): the image with these details filled.

Note

See a working example here.

Example

>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> bottom_hat_img = bottom_hat(tensor, kernel)
kornia.morphology.reconstruction(seed, mask, kernel=None, method='dilation', num_iters=None, check_every=4, engine='auto')[source]#

Reconstruct an image from a seed: dilate it inside a mask until it stops changing.

out = reconstruction(seed, mask) takes two floating-point images (B, C, H, W) and returns the (B, C, H, W) image grown from \(\min(\text{seed}, \text{mask})\) by repeated geodesic dilations \(\min(\delta_B(x), \text{mask})\), until the result stops changing. method="erosion" is the dual, \(-\text{reconstruction}(-\text{seed}, -\text{mask})\), which lowers a seed toward the mask from above. reconstruction(erosion(x, kernel), x) is opening by reconstruction: it removes the shapes opening() removes and restores the whole of each shape that survives the erosion, thin parts included. The shapes are connected through reconstruction’s own kernel, a \(3 \times 3\) square by default; for an erosion kernel with gaps, such as [[1, 0, 1, 0, 1]], pass the same kernel to reconstruction.

Convention:
  • Matches skimage.morphology.reconstruction: the default kernel is a \(3 \times 3\) square, its center cell is always part of the neighborhood, and both methods spread a pixel’s value to the kernel’s offsets, as dilation() does. scikit-image’s dilation spreads the other way, but its reconstruction agrees. The image border is geodesic. Unlike scikit-image, a seed above mask (below it for "erosion") is clipped to mask instead of raising.

  • Under autograd every step keeps its intermediates, so memory grows with the number of steps.

  • Reference: L. Vincent, “Morphological grayscale reconstruction in image analysis: applications and efficient algorithms”, IEEE TIP 1993.

Parameters:
  • seed (Tensor) – floating-point starting image (B, C, H, W).

  • mask (Tensor) – floating-point image bounding the reconstruction, of the same shape as seed.

  • kernel (Optional[Tensor], optional) – offsets from the center that a pixel’s value spreads to in one step, (k_h, k_w) with odd sizes. Non-zero cells mark an offset; their magnitude and dtype are ignored. Default: None, which uses a \(3 \times 3\) square.

  • method (str, optional) – "dilation" (default) or "erosion". Default: "dilation"

  • num_iters (Optional[int], optional) – number of steps to run. Default: None, which runs until the result stops changing. That can take far more steps than \(\max(H, W)\) when mask has winding paths. A fixed count always runs that many steps, even past convergence; 0 returns \(\min(\text{seed}, \text{mask})\) for "dilation" and \(\max(\text{seed}, \text{mask})\) for "erosion". It has no data-dependent exit, so torch.compile captures it as one graph, but the loop is unrolled and compile time grows with the count.

  • check_every (int, optional) – number of steps between convergence checks when num_iters is None. Each check syncs the device with the host, and steps past convergence are wasted, so a larger value suits inputs that take many steps. For inputs without NaN, the output does not depend on it. Default: 4.

  • engine (str, optional) – "unfold", "shift" or "auto" (default), passed to dilation(). "convolution" is rejected: it is not exact on every backend, and an inexact step can keep the loop from converging. Default: "auto"

Return type:

Tensor

Returns:

Reconstructed image (B, C, H, W) in the promoted dtype of seed and mask.

Raises:
  • TypeCheckError – if seed, mask or kernel is not a tensor.

  • ShapeError – if seed is not 4-dimensional, mask has another shape, or kernel is not 2-dimensional.

  • ValueCheckError – if engine is "convolution", also with checks disabled.

  • BaseError – if seed or mask is not floating point, a kernel size is even, method or engine is not one of the values above, num_iters is negative, or check_every is not positive.

See also

  • dilation(): one step without the mask; reconstruction repeats it, clipped to mask.

  • erosion(): the seed of opening by reconstruction.

  • opening(): also removes the thin parts of the shapes it keeps.

Example

>>> mask = torch.rand(1, 3, 5, 5)
>>> seed = mask * 0.5
>>> output = reconstruction(seed, mask)