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.
Grow bright regions with
dilation()and shrink them witherosion().Remove the bright details the kernel does not fit in with
opening(), and fill the dark ones withclosing();top_hat()andbottom_hat()return those details alone.Measure edge strength, the dilation minus the erosion, with
gradient().Grow a seed image inside a mask until it stops changing with
reconstruction().
- 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 oftensorover the neighborhood placed at it.
- Convention:
dilationreflects the kernel: it is the Minkowski dilation \(\delta_B f(x) = \max_{b \in B} f(x - b)\), as inscipy.ndimage;erosion()does not reflect. Conventions & Pitfalls maps the kernels and the border modes onto scipy, scikit-image and OpenCV.Under
geodesica window with no kernel cell inside the image is empty and returns the reduction identity,-infhere and+infinerosion(), 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 raisesTypeError, another rankValueError.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 passtorch.ones(k_h, k_w). Another rank raisesValueError.structuring_element (
Optional[Tensor], optional) – non-flat structuring element ofkernel’s shape, added to the neighbor values before the maximum. Another shape raisesValueError. Default:None, a flat element.origin (
Optional[List[int]], optional) –[row, col]cell ofkernelplaced 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 withtorch.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 raiseRuntimeErrorotherwise. Any other value raisesValueError. Default:"geodesic"border_value (
float, optional) – fill value forborder_type="constant"; the other modes ignore it. Default:0.0.max_val (
float, optional) – no effect; excluded kernel cells andgeodesicpadding use the reduction identity \(\mp\infty\). Retained for backward compatibility. Default:1e4engine (
str, optional) –"auto"(default),"unfold","shift"or"convolution"; another value raisesNotImplementedError."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’sconv2dand inherits its precision: aconv2dthat computes float32 in reduced precision, as on macOS CPU, rounds the output. Forward-only,"shift"needs nok_h k_w-sized intermediate. Under autograd it saves2 (k_h k_w - 1)output-sized tensors for backward, more memory than"unfold". Default:"auto"
- Return type:
- Returns:
Dilated image
(B, C, H, W). Its dtype is the image dtype promoted with that ofstructuring_element, or, without one, with that of a floating-pointkernel: a float16 image with the float32torch.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 ofdilation()and returns the(B, C, H, W)image whose every pixel is the minimum oftensorover the neighborhood placed at it.
- Convention:
As
dilation(), except thaterosiondoes not reflect the kernel: it is the Minkowski erosion \(\varepsilon_B f(x) = \min_{b \in B} f(x + b)\), as inscipy.ndimageand OpenCV.
- Parameters:
tensor (
Tensor) – floating-point image(B, C, H, W); another dtype raisesTypeError, another rankValueError.kernel (
Tensor) –(k_h, k_w)mask of the neighborhood, as indilation().structuring_element (
Optional[Tensor], optional) – non-flat structuring element ofkernel’s shape, subtracted from the neighbor values before the minimum. Default:None, a flat element.origin (
Optional[List[int]], optional) –[row, col]cell ofkernelplaced on the output pixel, as indilation(). Default:Noneborder_type (
str, optional) – border handling, as indilation(). Default:"geodesic".border_value (
float, optional) – fill value forborder_type="constant". Default:0.0.max_val (
float, optional) – no effect, as indilation(). Default:1e4engine (
str, optional) – computation engine, as indilation(). Default:"auto".
- Return type:
- Returns:
Eroded image
(B, C, H, W), in the dtypedilation()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(): withmethod="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)isdilation(erosion(tensor, kernel), kernel)with the same arguments in both halves, and returns a(B, C, H, W)image.
- Convention:
As only
dilation()reflects the kernel,openingis a morphological opening (anti-extensive and idempotent) for an asymmetric kernel too, undergeodesicorcircular; a non-flatstructuring_elementorengine="convolution"holds both properties only to roundoff, andconstant,reflectandreplicatecan break them.
- Parameters:
tensor (
Tensor) – floating-point image(B, C, H, W); another dtype raisesTypeError, another rankValueError.kernel (
Tensor) –(k_h, k_w)mask of the neighborhood, as indilation().structuring_element (
Optional[Tensor], optional) – non-flat structuring element, as indilation(). Default:Noneorigin (
Optional[List[int]], optional) –[row, col]cell ofkernelplaced on the output pixel, as indilation(). Default:Noneborder_type (
str, optional) – border handling, as indilation(). Default:"geodesic".border_value (
float, optional) – fill value forborder_type="constant". Default:0.0.max_val (
float, optional) – no effect, as indilation(). Default:1e4engine (
str, optional) – computation engine, as indilation(). Default:"auto".
- Return type:
- Returns:
Opened image
(B, C, H, W), in the dtypedilation()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)iserosion(dilation(tensor, kernel), kernel)with the same arguments in both halves, and returns a(B, C, H, W)image.
- Convention:
As only
dilation()reflects the kernel,closingis a morphological closing (extensive and idempotent) for an asymmetric kernel too, undergeodesicorcircular; a non-flatstructuring_elementorengine="convolution"holds both properties only to roundoff, andconstant,reflectandreplicatecan break them.
- Parameters:
tensor (
Tensor) – floating-point image(B, C, H, W); another dtype raisesTypeError, another rankValueError.kernel (
Tensor) –(k_h, k_w)mask of the neighborhood, as indilation().structuring_element (
Optional[Tensor], optional) – non-flat structuring element, as indilation(). Default:Noneorigin (
Optional[List[int]], optional) –[row, col]cell ofkernelplaced on the output pixel, as indilation(). Default:Noneborder_type (
str, optional) – border handling, as indilation(). Default:"geodesic".border_value (
float, optional) – fill value forborder_type="constant". Default:0.0.max_val (
float, optional) – no effect, as indilation(). Default:1e4engine (
str, optional) – computation engine, as indilation(). Default:"auto".
- Return type:
- Returns:
Closed image
(B, C, H, W), in the dtypedilation()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)returnsdilation(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-geodesicborder, with inputs that keep the image dtype (seedilation()), it equalsscipy.ndimage.morphological_gradientwith the matching mode andcval=border_value. For a flat kernel (nostructuring_element) symmetric about its origin it is the value range over each neighborhood.
- Parameters:
tensor (
Tensor) – floating-point image(B, C, H, W); another dtype raisesTypeError, another rankValueError.kernel (
Tensor) –(k_h, k_w)mask of the neighborhood, as indilation().structuring_element (
Optional[Tensor], optional) – non-flat structuring element, as indilation(). Default:Noneorigin (
Optional[List[int]], optional) –[row, col]cell ofkernelplaced on the output pixel, as indilation(). Default:Noneborder_type (
str, optional) – border handling, as indilation(). Default:"geodesic".border_value (
float, optional) – fill value forborder_type="constant". Default:0.0.max_val (
float, optional) – no effect, as indilation(). Default:1e4engine (
str, optional) – computation engine, as indilation(). Default:"auto".
- Return type:
- Returns:
Gradient image
(B, C, H, W), in the dtypedilation()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)returnstensor - opening(tensor, kernel)with the same arguments, the(B, C, H, W)white top-hat: the bright detailsopening()removes, on a zero background.
- Convention:
Under every
border_typeexceptgeodesic, for inputs that keep the image dtype (seedilation()), with the mode mapped as in Conventions & Pitfalls andcval=border_value, it equalsscipy.ndimage.white_tophat. OpenCV’sMORPH_TOPHAT, at its default border (kornia’sgeodesic),BORDER_REPLICATEorBORDER_REFLECT_101, equals it only for a flat kernel (nostructuring_element) symmetric about its origin: OpenCV takes no structuring element, andcv2.dilatedoes not reflect the kernel.
- Parameters:
tensor (
Tensor) – floating-point image(B, C, H, W); another dtype raisesTypeError, another rankValueError.kernel (
Tensor) –(k_h, k_w)mask of the neighborhood, as indilation().structuring_element (
Optional[Tensor], optional) – non-flat structuring element, as indilation(). Default:Noneorigin (
Optional[List[int]], optional) –[row, col]cell ofkernelplaced on the output pixel, as indilation(). Default:Noneborder_type (
str, optional) – border handling, as indilation(). Default:"geodesic".border_value (
float, optional) – fill value forborder_type="constant". Default:0.0.max_val (
float, optional) – no effect, as indilation(). Default:1e4engine (
str, optional) – computation engine, as indilation(). Default:"auto".
- Return type:
- Returns:
Top hat transformed image
(B, C, H, W), in the dtypedilation()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)returnsclosing(tensor, kernel) - tensorwith the same arguments, the(B, C, H, W)black top-hat: the dark detailsclosing()fills, as positive values on a zero background.
- Convention:
Under every
border_typeexceptgeodesic, for inputs that keep the image dtype (seedilation()), with the mode mapped as in Conventions & Pitfalls andcval=border_value, it equalsscipy.ndimage.black_tophat. OpenCV’sMORPH_BLACKHAT, at its default border (kornia’sgeodesic),BORDER_REPLICATEorBORDER_REFLECT_101, equals it only for a flat kernel (nostructuring_element) symmetric about its origin: OpenCV takes no structuring element, andcv2.dilatedoes not reflect the kernel.
- Parameters:
tensor (
Tensor) – floating-point image(B, C, H, W); another dtype raisesTypeError, another rankValueError.kernel (
Tensor) –(k_h, k_w)mask of the neighborhood, as indilation().structuring_element (
Optional[Tensor], optional) – non-flat structuring element, as indilation(). Default:Noneorigin (
Optional[List[int]], optional) –[row, col]cell ofkernelplaced on the output pixel, as indilation(). Default:Noneborder_type (
str, optional) – border handling, as indilation(). Default:"geodesic".border_value (
float, optional) – fill value forborder_type="constant". Default:0.0.max_val (
float, optional) – no effect, as indilation(). Default:1e4engine (
str, optional) – computation engine, as indilation(). Default:"auto".
- Return type:
- Returns:
Bottom hat transformed image
(B, C, H, W), in the dtypedilation()returns for the same inputs.
See also
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 shapesopening()removes and restores the whole of each shape that survives the erosion, thin parts included. The shapes are connected throughreconstruction’s ownkernel, a \(3 \times 3\) square by default; for an erosionkernelwith gaps, such as[[1, 0, 1, 0, 1]], pass the samekerneltoreconstruction.- Convention:
Matches
skimage.morphology.reconstruction: the defaultkernelis 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, asdilation()does. scikit-image’sdilationspreads the other way, but itsreconstructionagrees. The image border isgeodesic. Unlike scikit-image, aseedabovemask(below it for"erosion") is clipped tomaskinstead 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 asseed.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)\) whenmaskhas winding paths. A fixed count always runs that many steps, even past convergence;0returns \(\min(\text{seed}, \text{mask})\) for"dilation"and \(\max(\text{seed}, \text{mask})\) for"erosion". It has no data-dependent exit, sotorch.compilecaptures 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 whennum_itersisNone. 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 todilation()."convolution"is rejected: it is not exact on every backend, and an inexact step can keep the loop from converging. Default:"auto"
- Return type:
- Returns:
Reconstructed image
(B, C, H, W)in the promoted dtype ofseedandmask.- Raises:
TypeCheckError – if
seed,maskorkernelis not a tensor.ShapeError – if
seedis not 4-dimensional,maskhas another shape, orkernelis not 2-dimensional.ValueCheckError – if
engineis"convolution", also with checks disabled.BaseError – if
seedormaskis not floating point, akernelsize is even,methodorengineis not one of the values above,num_itersis negative, orcheck_everyis not positive.
See also
dilation(): one step without the mask;reconstructionrepeats it, clipped tomask.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)