Skip to content

šŸ Geometric Computer Vision Library for Spatial AI

add auto-image docs in kornia.morphology (#1128)

Edgar Riba40e3cc9155c9
diff --git a/docs/generate_example_images.py b/docs/generate_example_images.py
index 592ec65ea..69d6c1633 100644
--- a/docs/generate_example_images.py
+++ b/docs/generate_example_images.py
@@ -19,28 +19,30 @@ def read_img_from_url(url: str, resize_to: Optional[Tuple[int, int]] = None) ->
nparr = np.frombuffer(response, np.uint8)
# convert to image array and resize
img: np.ndarray = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)[..., :3]
- if resize_to is None:
- img = cv2.resize(img, (186, int(img.shape[0] / img.shape[1] * 224)))
- else:
- img = cv2.resize(img, resize_to)
# convert the image to a tensor
img_t: torch.Tensor = K.utils.image_to_tensor(img, keepdim=False) # 1xCxHXW
img_t = img_t.float() / 255.0
+ if resize_to is None:
+ img_t = K.geometry.resize(img_t, 184)
+ else:
+ img_t = K.geometry.resize(img_t, resize_to)
return img_t
def main():
# load the images
- BASE_IMAGE_URL1: str = "https://raw.githubusercontent.com/kornia/data/main/panda.jpg"
- BASE_IMAGE_URL2: str = "https://raw.githubusercontent.com/kornia/data/main/simba.png"
- BASE_IMAGE_URL3: str = "https://raw.githubusercontent.com/kornia/data/main/girona.png"
+ BASE_IMAGE_URL1: str = "https://raw.githubusercontent.com/kornia/data/main/panda.jpg" # augmentation
+ BASE_IMAGE_URL2: str = "https://raw.githubusercontent.com/kornia/data/main/simba.png" # color
+ BASE_IMAGE_URL3: str = "https://raw.githubusercontent.com/kornia/data/main/girona.png" # enhance
+ BASE_IMAGE_URL4: str = "https://raw.githubusercontent.com/kornia/data/main/baby_giraffe.png" # morphology
OUTPUT_PATH = Path(__file__).absolute().parent / "source/_static/img"
os.makedirs(OUTPUT_PATH, exist_ok=True)
print(f"Pointing images to path {OUTPUT_PATH}.")
img1 = read_img_from_url(BASE_IMAGE_URL1)
- img2 = read_img_from_url(BASE_IMAGE_URL2, img1.shape[-2:][::-1])
- img3 = read_img_from_url(BASE_IMAGE_URL3, img1.shape[-2:][::-1])
+ img2 = read_img_from_url(BASE_IMAGE_URL2, img1.shape[-2:])
+ img3 = read_img_from_url(BASE_IMAGE_URL3, img1.shape[-2:])
+ img4 = read_img_from_url(BASE_IMAGE_URL4)
# TODO: make this more generic for modules out of kornia.augmentation
# Dictionary containing the transforms to generate the sample images:
@@ -177,6 +179,32 @@ def main():
else:
args_in = (img_in, *args)
# import function and apply
+ fn = getattr(mod, fn_name)
+ out = fn(*args_in)
+ # save the output image
+ out = torch.cat([img_in[0], *[out[i] for i in range(out.size(0))]], dim=-1)
+ out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
+ sig = f"{fn_name}({', '.join([str(a) for a in args])})"
+ print(f"Generated image example for {fn_name}. {sig}")
+
+ # korna.morphology module
+ mod = importlib.import_module("kornia.morphology")
+ kernel = torch.tensor([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
+ transforms: dict = {
+ "dilation": ((kernel,), 1),
+ "erosion": ((kernel,), 1),
+ "opening": ((kernel,), 1),
+ "closing": ((kernel,), 1),
+ "gradient": ((kernel,), 1),
+ "top_hat": ((kernel,), 1),
+ "bottom_hat": ((kernel,), 1),
+ }
+ # ITERATE OVER THE TRANSFORMS
+ for fn_name, (args, num_samples) in transforms.items():
+ img_in = img4.repeat(num_samples, 1, 1, 1)
+ args_in = (img_in, *args)
+ # import function and apply
# import pdb;pdb.set_trace()
fn = getattr(mod, fn_name)
out = fn(*args_in)
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 32a58e525..86697d6f7 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -4,7 +4,6 @@ import torch
import torch.nn.functional as F
-# Dilation
def dilation(
tensor: torch.Tensor,
kernel: torch.Tensor,
@@ -16,25 +15,27 @@ def dilation(
) -> torch.Tensor:
r"""Returns the dilated image applying the same kernel in each channel.
+ .. image:: _static/img/dilation.png
+
The kernel must have 2 dimensions.
Args:
- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
- kernel (torch.Tensor): Positions of non-infinite elements of a flat structuring element. Non-zero values give
+ tensor: Image with shape :math:`(B, C, H, W)`.
+ kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation. It may be a
- non-flat structuring element.
- origin (List[int], optional): Origin of the structuring element. Default is None and uses the center of
+ structuring_element: Structuring element used for the grayscale dilation. It may be a non-flat
+ structuring element.
+ origin: Origin of the structuring element. Default: ``None`` and uses the center of
the structuring element as origin (rounding towards zero).
- border_type (str, optional): It determines how the image borders are handled, where border_value is the value
- when border_type is equal to ā€˜constant’. Default is ā€˜geodesic’ which ignores the values that are outside the
- image when applying the operation.
- border_value (float, optional): Value to fill past edges of input if border_type is ā€˜constant’. Default is 0.0.
- max_val (float, optional): The value of the infinite elements in the kernel.
+ border_type: It determines how the image borders are handled, where ``border_value`` is the value
+ when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
+ outside the image when applying the operation.
+ border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
+ max_val: The value of the infinite elements in the kernel.
Returns:
- torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.
+ Dilated image with shape :math:`(B, C, H, W)`.
Example:
>>> tensor = torch.rand(1, 3, 5, 5)
@@ -81,7 +82,6 @@ def dilation(
return output
-# Erosion
def erosion(
tensor: torch.Tensor,
kernel: torch.Tensor,
@@ -93,25 +93,27 @@ def erosion(
) -> torch.Tensor:
r"""Returns the eroded image applying the same kernel in each channel.
+ .. image:: _static/img/erosion.png
+
The kernel must have 2 dimensions.
Args:
- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
- kernel (torch.Tensor): Positions of non-infinite elements of a flat structuring element. Non-zero values give
+ tensor: Image with shape :math:`(B, C, H, W)`.
+ kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation. It may be a
- non-flat structuring element.
- origin (List[int], optional): Origin of the structuring element. Default is None and uses the center of
+ structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation.
+ It may be a non-flat structuring element.
+ origin: Origin of the structuring element. Default: ``None`` and uses the center of
the structuring element as origin (rounding towards zero).
- border_type (str, optional): It determines how the image borders are handled, where border_value is the value
- when border_type is equal to ā€˜constant’. Default is ā€˜geodesic’ which ignores the values that are outside the
- image when applying the operation.
- border_value (float, optional): Value to fill past edges of input if border_type is ā€˜constant’. Default is 0.0.
- max_val (float, optional): The value of the infinite elements in the kernel.
+ border_type: It determines how the image borders are handled, where ``border_value`` is the value
+ when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
+ outside the image when applying the operation.
+ border_value: Value to fill past edges of input if border_type is ``constant``.
+ max_val: The value of the infinite elements in the kernel.
Returns:
- torch.Tensor: Eroded image with shape :math:`(B, C, H, W)`.
+ Eroded image with shape :math:`(B, C, H, W)`.
Example:
>>> tensor = torch.rand(1, 3, 5, 5)
@@ -158,7 +160,6 @@ def erosion(
return output
-# Opening
def opening(
tensor: torch.Tensor,
kernel: torch.Tensor,
@@ -170,22 +171,24 @@ def opening(
) -> torch.Tensor:
r"""Returns the opened image, (that means, dilation after an erosion) applying the same kernel in each channel.
+ .. image:: _static/img/opening.png
+
The kernel must have 2 dimensions.
Args:
- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
- kernel (torch.Tensor): Positions of non-infinite elements of a flat structuring element. Non-zero values give
+ tensor: Image with shape :math:`(B, C, H, W)`.
+ kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation. It may be a
+ structuring_element: Structuring element used for the grayscale dilation. It may be a
non-flat structuring element.
- origin (List[int], optional): Origin of the structuring element. Default is None and uses the center of
+ origin: Origin of the structuring element. Default: ``None`` and uses the center of
the structuring element as origin (rounding towards zero).
- border_type (str, optional): It determines how the image borders are handled, where border_value is the value
- when border_type is equal to ā€˜constant’. Default is ā€˜geodesic’ which ignores the values that are outside the
- image when applying the operation.
- border_value (float, optional): Value to fill past edges of input if border_type is ā€˜constant’. Default is 0.0.
- max_val (float, optional): The value of the infinite elements in the kernel.
+ border_type: It determines how the image borders are handled, where ``border_value`` is the value
+ when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
+ outside the image when applying the operation.
+ border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
+ max_val: The value of the infinite elements in the kernel.
Returns:
torch.Tensor: Opened image with shape :math:`(B, C, H, W)`.
@@ -227,7 +230,6 @@ def opening(
)
-# Closing
def closing(
tensor: torch.Tensor,
kernel: torch.Tensor,
@@ -239,25 +241,27 @@ def closing(
) -> torch.Tensor:
r"""Returns the closed image, (that means, erosion after a dilation) applying the same kernel in each channel.
+ .. image:: _static/img/closing.png
+
The kernel must have 2 dimensions.
Args:
- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
- kernel (torch.Tensor): Positions of non-infinite elements of a flat structuring element. Non-zero values give
+ tensor: Image with shape :math:`(B, C, H, W)`.
+ kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation. It may be a
+ structuring_element: Structuring element used for the grayscale dilation. It may be a
non-flat structuring element.
- origin (List[int], optional): Origin of the structuring element. Default is None and uses the center of
+ origin: Origin of the structuring element. Default is None and uses the center of
the structuring element as origin (rounding towards zero).
- border_type (str, optional): It determines how the image borders are handled, where border_value is the value
- when border_type is equal to ā€˜constant’. Default is ā€˜geodesic’ which ignores the values that are outside the
- image when applying the operation.
- border_value (float, optional): Value to fill past edges of input if border_type is ā€˜constant’. Default is 0.0.
- max_val (float, optional): The value of the infinite elements in the kernel.
+ border_type: It determines how the image borders are handled, where ``border_value`` is the value
+ when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
+ outside the image when applying the operation.
+ border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
+ max_val: The value of the infinite elements in the kernel.
Returns:
- torch.Tensor: Closed image with shape :math:`(B, C, H, W)`.
+ Closed image with shape :math:`(B, C, H, W)`.
Example:
>>> tensor = torch.rand(1, 3, 5, 5)
@@ -308,26 +312,28 @@ def gradient(
) -> torch.Tensor:
r"""Returns the morphological gradient of an image.
+ .. image:: _static/img/gradient.png
+
That means, (dilation - erosion) applying the same kernel in each channel.
The kernel must have 2 dimensions.
Args:
- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
- kernel (torch.Tensor): Positions of non-infinite elements of a flat structuring element. Non-zero values give
+ tensor: Image with shape :math:`(B, C, H, W)`.
+ kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation. It may be a
+ structuring_element: Structuring element used for the grayscale dilation. It may be a
non-flat structuring element.
- origin (List[int], optional): Origin of the structuring element. Default is None and uses the center of
+ origin: Origin of the structuring element. Default is None and uses the center of
the structuring element as origin (rounding towards zero).
- border_type (str, optional): It determines how the image borders are handled, where border_value is the value
- when border_type is equal to ā€˜constant’. Default is ā€˜geodesic’ which ignores the values that are outside the
- image when applying the operation.
- border_value (float, optional): Value to fill past edges of input if border_type is ā€˜constant’. Default is 0.0.
- max_val (float, optional): The value of the infinite elements in the kernel.
+ border_type: It determines how the image borders are handled, where ``border_value`` is the value
+ when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
+ outside the image when applying the operation.
+ border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
+ max_val: The value of the infinite elements in the kernel.
Returns:
- torch.Tensor: Gradient image with shape :math:`(B, C, H, W)`.
+ Gradient image with shape :math:`(B, C, H, W)`.
Example:
>>> tensor = torch.rand(1, 3, 5, 5)
@@ -354,7 +360,6 @@ def gradient(
)
-# Top Hat
def top_hat(
tensor: torch.Tensor,
kernel: torch.Tensor,
@@ -366,28 +371,30 @@ def top_hat(
) -> torch.Tensor:
r"""Returns the top hat tranformation of an image.
+ .. image:: _static/img/top_hat.png
+
That means, (image - opened_image) applying the same kernel in each channel.
The kernel must have 2 dimensions.
- See :opening for details.
+ See :func:`~kornia.morphology.opening` for details.
Args:
- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
- kernel (torch.Tensor): Positions of non-infinite elements of a flat structuring element. Non-zero values give
+ tensor: Image with shape :math:`(B, C, H, W)`.
+ kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation. It may be a
+ structuring_element: Structuring element used for the grayscale dilation. It may be a
non-flat structuring element.
- origin (List[int], optional): Origin of the structuring element. Default is None and uses the center of
+ origin: Origin of the structuring element. Default: ``None`` and uses the center of
the structuring element as origin (rounding towards zero).
- border_type (str, optional): It determines how the image borders are handled, where border_value is the value
- when border_type is equal to ā€˜constant’. Default is ā€˜geodesic’ which ignores the values that are outside the
- image when applying the operation.
- border_value (float, optional): Value to fill past edges of input if border_type is ā€˜constant’. Default is 0.0.
- max_val (float, optional): The value of the infinite elements in the kernel.
+ border_type: It determines how the image borders are handled, where ``border_value`` is the value
+ when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
+ outside the image when applying the operation.
+ border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
+ max_val: The value of the infinite elements in the kernel.
Returns:
- torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.
+ Top hat transformated image with shape :math:`(B, C, H, W)`.
Example:
>>> tensor = torch.rand(1, 3, 5, 5)
@@ -418,7 +425,6 @@ def top_hat(
)
-# Bottom Hat
def bottom_hat(
tensor: torch.Tensor,
kernel: torch.Tensor,
@@ -430,28 +436,30 @@ def bottom_hat(
) -> torch.Tensor:
r"""Returns the bottom hat tranformation of an image.
+ .. image:: _static/img/bottom_hat.png
+
That means, (closed_image - image) applying the same kernel in each channel.
The kernel must have 2 dimensions.
- See :closing for details.
+ See :func:`~kornia.morphology.closing` for details.
Args:
- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
- kernel (torch.Tensor): Positions of non-infinite elements of a flat structuring element. Non-zero values give
+ tensor: Image with shape :math:`(B, C, H, W)`.
+ kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation. It may be a
+ structuring_element: Structuring element used for the grayscale dilation. It may be a
non-flat structuring element.
- origin (List[int], optional): Origin of the structuring element. Default is None and uses the center of
+ origin: Origin of the structuring element. Default: ``None`` and uses the center of
the structuring element as origin (rounding towards zero).
- border_type (str, optional): It determines how the image borders are handled, where border_value is the value
- when border_type is equal to ā€˜constant’. Default is ā€˜geodesic’ which ignores the values that are outside the
- image when applying the operation.
- border_value (float, optional): Value to fill past edges of input if border_type is ā€˜constant’. Default is 0.0.
- max_val (float, optional): The value of the infinite elements in the kernel.
+ border_type: It determines how the image borders are handled, where ``border_value`` is the value
+ when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
+ outside the image when applying the operation.
+ border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
+ max_val: The value of the infinite elements in the kernel.
Returns:
- torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.
+ Top hat transformated image with shape :math:`(B, C, H, W)`.
Example:
>>> tensor = torch.rand(1, 3, 5, 5)