Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

morphology (#831)

Jucliquee5bb5844715a
diff --git a/docs/.gitignore b/docs/.gitignore
index 16088c9cb..88f21e651 100644
--- a/docs/.gitignore
+++ b/docs/.gitignore
@@ -1,5 +1,4 @@
build/doctest
-build/doctrees
build/html/.buildinfo
build/html/objects.inv
-source/tutorials/*
+source/tutorials/*
\ No newline at end of file
diff --git a/docs/source/index.rst b/docs/source/index.rst
index de68af325..94a12a98e 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -24,6 +24,7 @@ Kornia Documentation
geometry
losses
utils
+ morphology
.. toctree::
:maxdepth: 2
diff --git a/docs/source/morphology.rst b/docs/source/morphology.rst
new file mode 100644
index 000000000..c9c9b5a98
--- /dev/null
+++ b/docs/source/morphology.rst
@@ -0,0 +1,12 @@
+kornia.morphology
+======================
+
+.. currentmodule:: kornia.morphology
+
+.. autofunction:: dilation
+.. autofunction:: erosion
+.. autofunction:: open
+.. autofunction:: close
+.. autofunction:: gradient
+.. autofunction:: top_hat
+.. autofunction:: black_hat
\ No newline at end of file
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 4e3e4097b..e0ede2062 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -19,6 +19,7 @@ from kornia import geometry
from kornia import jit
from kornia import losses
from kornia import utils
+from kornia import morphology
# Exposes package functional to top level
diff --git a/kornia/morphology/__init__.py b/kornia/morphology/__init__.py
new file mode 100644
index 000000000..7f5cd6aac
--- /dev/null
+++ b/kornia/morphology/__init__.py
@@ -0,0 +1,3 @@
+from .basic_operators import *
+from .open_close import *
+from .morphology import *
diff --git a/kornia/morphology/basic_operators.py b/kornia/morphology/basic_operators.py
new file mode 100644
index 000000000..7704ed704
--- /dev/null
+++ b/kornia/morphology/basic_operators.py
@@ -0,0 +1,129 @@
+# Libraries
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from typing import Tuple, Union
+
+
+# _se_to_mask
+def _se_to_mask(se: torch.Tensor) -> torch.Tensor:
+ se_h, se_w = se.size()
+ se_flat = se.view(-1)
+ num_feats = se_h * se_w
+ out = torch.zeros(num_feats, 1, se_h, se_w, dtype=se.dtype, device=se.device)
+ for i in range(num_feats):
+ y = i % se_h
+ x = i // se_h
+ out[i, 0, x, y] = (se_flat[i] >= 0).float()
+ return out
+
+
+def dilation(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+
+ r"""
+
+ Returns the dilated image applying the same kernel in each channel.
+ The kernel must have 2 dimensions, each one defined by an odd number.
+
+ Args
+
+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.
+
+ Returns:
+
+ torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.
+
+ Example:
+
+ >>> tensor = torch.rand(1, 3, 5, 5)
+ >>> kernel = torch.ones(3, 3)
+ >>> dilated_img = dilation(tensor, kernel)
+
+ """
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) != 4:
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(
+ tensor.dim()))
+
+ if not isinstance(kernel, torch.Tensor):
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
+ type(kernel)))
+
+ if len(kernel.shape) != 2:
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
+ kernel.dim()))
+
+ # prepare kernel
+ se_d = kernel - 1
+ kernel_d = _se_to_mask(se_d)
+
+ # pad
+ se_h, se_w = kernel.shape
+ pad_d = (se_h // 2, se_w // 2)
+
+ output = tensor.view(tensor.shape[0] * tensor.shape[1], 1, tensor.shape[2], tensor.shape[3])
+ output = (F.conv2d(output, kernel_d, padding=pad_d) + se_d.view(1, -1, 1, 1)).max(dim=1)[0]
+ shape = tensor.shape
+
+ return output.view(shape)
+
+
+# erosion
+def erosion(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+
+ r"""
+
+ Returns the eroded image applying the same kernel in each channel.
+ The kernel must have 2 dimensions, each one defined by an odd number.
+
+ Args
+
+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.
+
+ Returns:
+
+ torch.Tensor: Eroded image with shape :math:`(B, C, H, W)`.
+
+ Example:
+
+ >>> tensor = torch.rand(1, 3, 5, 5)
+ >>> kernel = torch.ones(5, 5)
+ >>> output = erosion(tensor, kernel)
+
+ """
+
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) != 4:
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(
+ tensor.dim()))
+
+ if not isinstance(kernel, torch.Tensor):
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
+ type(kernel)))
+
+ if len(kernel.shape) != 2:
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
+ kernel.dim()))
+
+ # prepare kernel
+ se_e = kernel - 1
+ kernel_e = _se_to_mask(se_e)
+
+ # pad
+ se_h, se_w = kernel.shape
+ pad_e = (se_h // 2, se_w // 2, se_h // 2, se_w // 2)
+
+ output = tensor.view(tensor.shape[0] * tensor.shape[1], 1, tensor.shape[2], tensor.shape[3])
+ output = F.pad(output, pad_e, mode='constant', value=1.)
+ output = (F.conv2d(output, kernel_e) - se_e.view(1, -1, 1, 1)).min(dim=1)[0]
+ shape = tensor.shape
+
+ return output.view(shape)
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
new file mode 100644
index 000000000..a126b77cf
--- /dev/null
+++ b/kornia/morphology/morphology.py
@@ -0,0 +1,147 @@
+# Libraries
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from kornia.morphology.basic_operators import dilation, erosion
+from kornia.morphology.open_close import open, close
+
+
+# morphological gradient
+def gradient(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+
+ r"""
+
+ Returns the morphological gradient of an image,
+ (that means, dilation - erosion) applying the same kernel in each channel.
+ The kernel must have 2 dimensions, each one defined by an odd number.
+
+ Args
+
+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.
+
+ Returns:
+
+ torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.
+
+ Example:
+
+ >>> tensor = torch.rand(1, 3, 5, 5)
+ >>> kernel = torch.ones(3, 3)
+ >>> gradient_img = gradient(tensor, kernel)
+
+ """
+
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) != 4:
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(
+ tensor.dim()))
+
+ if not isinstance(kernel, torch.Tensor):
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
+ type(kernel)))
+
+ if len(kernel.shape) != 2:
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
+ kernel.dim()))
+
+ return dilation(tensor, kernel) - erosion(tensor, kernel)
+
+
+# top_hat
+def top_hat(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+
+ r"""
+
+ Returns the top hat tranformation of an image,
+ (that means, image - opened_image) applying the same kernel in each channel.
+
+ The kernel must have 2 dimensions, each one defined by an odd number.
+
+ See :class:`~kornia.morphology.open` for details.
+
+ Args
+
+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.
+
+ Returns:
+
+ torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.
+
+ Example:
+
+ >>> tensor = torch.rand(1, 3, 5, 5)
+ >>> kernel = torch.ones(3, 3)
+ >>> top_hat_img = top_hat(tensor, kernel)
+
+ """
+
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) != 4:
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(
+ tensor.dim()))
+
+ if not isinstance(kernel, torch.Tensor):
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
+ type(kernel)))
+
+ if len(kernel.shape) != 2:
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
+ kernel.dim()))
+
+ return tensor - open(tensor, kernel)
+
+
+# black_hat
+def black_hat(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+
+ r"""
+
+ Returns the black hat tranformation of an image,
+ (that means, closed_image - image) applying the same kernel in each channel.
+
+ The kernel must have 2 dimensions, each one defined by an odd number.
+
+ See :class:`~kornia.morphology.close` for details.
+
+ Args
+
+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.
+
+ Returns:
+
+ torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.
+
+ Example:
+
+ >>> tensor = torch.rand(1, 3, 5, 5)
+ >>> kernel = torch.ones(3, 3)
+ >>> black_hat_img = black_hat(tensor, kernel)
+
+ """
+
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) != 4:
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(
+ tensor.dim()))
+
+ if not isinstance(kernel, torch.Tensor):
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
+ type(kernel)))
+
+ if len(kernel.shape) != 2:
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
+ kernel.dim()))
+
+ return close(tensor, kernel) - tensor
diff --git a/kornia/morphology/open_close.py b/kornia/morphology/open_close.py
new file mode 100644
index 000000000..d318be88a
--- /dev/null
+++ b/kornia/morphology/open_close.py
@@ -0,0 +1,93 @@
+# Libraries
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from kornia.morphology.basic_operators import dilation, erosion
+
+
+# open
+def open(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+
+ r"""
+
+ Returns the opened image, (that means, erosion after a dilation) applying the same kernel in each channel.
+ The kernel must have 2 dimensions, each one defined by an odd number.
+
+ Args
+
+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.
+
+ Returns:
+
+ torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.
+
+ Example:
+
+ >>> tensor = torch.rand(1, 3, 5, 5)
+ >>> kernel = torch.ones(3, 3)
+ >>> opened_img = open(tensor, kernel)
+
+ """
+
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) != 4:
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(
+ tensor.dim()))
+
+ if not isinstance(kernel, torch.Tensor):
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
+ type(kernel)))
+
+ if len(kernel.shape) != 2:
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
+ kernel.dim()))
+
+ return dilation(erosion(tensor, kernel), kernel)
+
+
+# close
+def close(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+
+ r"""
+
+ Returns the closed image, (that means, dilation after an erosion) applying the same kernel in each channel.
+ The kernel must have 2 dimensions, each one defined by an odd number.
+
+ Args
+
+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.
+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.
+
+ Returns:
+
+ torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.
+
+ Example:
+
+ >>> tensor = torch.rand(1, 3, 5, 5)
+ >>> kernel = torch.ones(3, 3)
+ >>> closed_img = close(tensor, kernel)
+
+ """
+
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) != 4:
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(
+ tensor.dim()))
+
+ if not isinstance(kernel, torch.Tensor):
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
+ type(kernel)))
+
+ if len(kernel.shape) != 2:
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
+ kernel.dim()))
+
+ return erosion(dilation(tensor, kernel), kernel)
diff --git a/test/morphology/test_black_hat.py b/test/morphology/test_black_hat.py
new file mode 100644
index 000000000..5b0ec0cda
--- /dev/null
+++ b/test/morphology/test_black_hat.py
@@ -0,0 +1,68 @@
+import pytest
+import torch
+from kornia.morphology.basic_operators import _se_to_mask
+from kornia.morphology.morphology import black_hat
+import kornia.testing as utils # test utils
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestBlackHat():
+
+ def test_smoke(self, device, dtype):
+ kernel = torch.rand(3, 3, device=device, dtype=dtype)
+ assert _se_to_mask(kernel) is not None
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize(
+ "kernel", [(3, 3), (5, 5)])
+ def test_cardinality(self, device, dtype, shape, kernel):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ krnl = torch.ones(kernel, device=device, dtype=dtype)
+ assert black_hat(img, krnl).shape == shape
+
+ def test_value(self, device, dtype):
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.2, 0., 0.5], [0., 0.4, 0.], [0.3, 0., 0.6]],
+ device=device, dtype=dtype)[None, None, :, :]
+ assert_allclose(black_hat(input, kernel), expected)
+
+ def test_exception(self, device, dtype):
+ input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert black_hat([0.], kernel)
+
+ with pytest.raises(TypeError):
+ assert black_hat(input, [0.])
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert black_hat(test, kernel)
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert black_hat(input, test)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64)
+ kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64)
+ assert gradcheck(black_hat, (input, kernel), raise_exception=True)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = black_hat
+ op_script = torch.jit.script(op)
+
+ input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ actual = op_script(input, kernel)
+ expected = op(input, kernel)
+
+ assert_allclose(actual, expected)
diff --git a/test/morphology/test_close.py b/test/morphology/test_close.py
new file mode 100644
index 000000000..24557cf08
--- /dev/null
+++ b/test/morphology/test_close.py
@@ -0,0 +1,68 @@
+import pytest
+import torch
+from kornia.morphology.basic_operators import _se_to_mask
+from kornia.morphology.open_close import close
+import kornia.testing as utils # test utils
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestClose():
+
+ def test_smoke(self, device, dtype):
+ kernel = torch.rand(3, 3, device=device, dtype=dtype)
+ assert _se_to_mask(kernel) is not None
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize(
+ "kernel", [(3, 3), (5, 5)])
+ def test_cardinality(self, device, dtype, shape, kernel):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ krnl = torch.ones(kernel, device=device, dtype=dtype)
+ assert close(img, krnl).shape == shape
+
+ def test_value(self, device, dtype):
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.7, 1., 0.8], [0.7, 0.7, 0.8], [0.7, 0.9, 0.8]],
+ device=device, dtype=dtype)[None, None, :, :]
+ assert_allclose(close(input, kernel), expected)
+
+ def test_exception(self, device, dtype):
+ input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert close([0.], kernel)
+
+ with pytest.raises(TypeError):
+ assert close(input, [0.])
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert close(test, kernel)
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert close(input, test)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64)
+ kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64)
+ assert gradcheck(close, (input, kernel), raise_exception=True)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = close
+ op_script = torch.jit.script(op)
+
+ input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ actual = op_script(input, kernel)
+ expected = op(input, kernel)
+
+ assert_allclose(actual, expected)
diff --git a/test/morphology/test_dilation.py b/test/morphology/test_dilation.py
new file mode 100644
index 000000000..67cf8afd2
--- /dev/null
+++ b/test/morphology/test_dilation.py
@@ -0,0 +1,67 @@
+import pytest
+import torch
+from kornia.morphology.basic_operators import _se_to_mask, dilation
+import kornia.testing as utils # test utils
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestDilate():
+
+ def test_smoke(self, device, dtype):
+ kernel = torch.rand(3, 3, device=device, dtype=dtype)
+ assert _se_to_mask(kernel) is not None
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize(
+ "kernel", [(3, 3), (5, 5)])
+ def test_cardinality(self, device, dtype, shape, kernel):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ krnl = torch.ones(kernel, device=device, dtype=dtype)
+ assert dilation(img, krnl).shape == shape
+
+ def test_value(self, device, dtype):
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=device, dtype=dtype)
+ expected = torch.tensor([[1., 1., 1.], [0.7, 1., 0.8], [0.9, 0.9, 0.9]],
+ device=device, dtype=dtype)[None, None, :, :]
+ assert_allclose(dilation(input, kernel), expected)
+
+ def test_exception(self, device, dtype):
+ input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert dilation([0.], kernel)
+
+ with pytest.raises(TypeError):
+ assert dilation(input, [0.])
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert dilation(test, kernel)
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert dilation(input, test)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64)
+ kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64)
+ assert gradcheck(dilation, (input, kernel), raise_exception=True)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = dilation
+ op_script = torch.jit.script(op)
+
+ input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ actual = op_script(input, kernel)
+ expected = op(input, kernel)
+
+ assert_allclose(actual, expected)
diff --git a/test/morphology/test_erosion.py b/test/morphology/test_erosion.py
new file mode 100644
index 000000000..3c51a5e47
--- /dev/null
+++ b/test/morphology/test_erosion.py
@@ -0,0 +1,67 @@
+import pytest
+import torch
+from kornia.morphology.basic_operators import _se_to_mask, erosion
+import kornia.testing as utils # test utils
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestErode():
+
+ def test_smoke(self, device, dtype):
+ kernel = torch.rand(3, 3, device=device, dtype=dtype)
+ assert _se_to_mask(kernel) is not None
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize(
+ "kernel", [(3, 3), (5, 5)])
+ def test_cardinality(self, device, dtype, shape, kernel):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ krnl = torch.ones(kernel, device=device, dtype=dtype)
+ assert erosion(img, krnl).shape == shape
+
+ def test_value(self, device, dtype):
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.5, 0.3, 0.3], [0.3, 0.3, 0.2], [0.4, 0.2, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ assert_allclose(erosion(input, kernel), expected)
+
+ def test_exception(self, device, dtype):
+ input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert erosion([0.], kernel)
+
+ with pytest.raises(TypeError):
+ assert erosion(input, [0.])
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert erosion(test, kernel)
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert erosion(input, test)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64)
+ kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64)
+ assert gradcheck(erosion, (input, kernel), raise_exception=True)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = erosion
+ op_script = torch.jit.script(op)
+
+ input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ actual = op_script(input, kernel)
+ expected = op(input, kernel)
+
+ assert_allclose(actual, expected)
diff --git a/test/morphology/test_gradient.py b/test/morphology/test_gradient.py
new file mode 100644
index 000000000..03ff39db1
--- /dev/null
+++ b/test/morphology/test_gradient.py
@@ -0,0 +1,68 @@
+import pytest
+import torch
+from kornia.morphology.basic_operators import _se_to_mask
+from kornia.morphology.morphology import gradient
+import kornia.testing as utils # test utils
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestGradient():
+
+ def test_smoke(self, device, dtype):
+ kernel = torch.rand(3, 3, device=device, dtype=dtype)
+ assert _se_to_mask(kernel) is not None
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize(
+ "kernel", [(3, 3), (5, 5)])
+ def test_cardinality(self, device, dtype, shape, kernel):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ krnl = torch.ones(kernel, device=device, dtype=dtype)
+ assert gradient(img, krnl).shape == shape
+
+ def test_value(self, device, dtype):
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.5, 0.7, 0.7], [0.4, 0.7, 0.6], [0.5, 0.7, 0.7]],
+ device=device, dtype=dtype)[None, None, :, :]
+ assert_allclose(gradient(input, kernel), expected)
+
+ def test_exception(self, device, dtype):
+ input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert gradient([0.], kernel)
+
+ with pytest.raises(TypeError):
+ assert gradient(input, [0.])
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert gradient(test, kernel)
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert gradient(input, test)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64)
+ kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64)
+ assert gradcheck(gradient, (input, kernel), raise_exception=True)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = gradient
+ op_script = torch.jit.script(op)
+
+ input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ actual = op_script(input, kernel)
+ expected = op(input, kernel)
+
+ assert_allclose(actual, expected)
diff --git a/test/morphology/test_open.py b/test/morphology/test_open.py
new file mode 100644
index 000000000..c0ae81470
--- /dev/null
+++ b/test/morphology/test_open.py
@@ -0,0 +1,68 @@
+import pytest
+import torch
+from kornia.morphology.basic_operators import _se_to_mask
+from kornia.morphology.open_close import open
+import kornia.testing as utils # test utils
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestOpen():
+
+ def test_smoke(self, device, dtype):
+ kernel = torch.rand(3, 3, device=device, dtype=dtype)
+ assert _se_to_mask(kernel) is not None
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize(
+ "kernel", [(3, 3), (5, 5)])
+ def test_cardinality(self, device, dtype, shape, kernel):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ krnl = torch.ones(kernel, device=device, dtype=dtype)
+ assert open(img, krnl).shape == shape
+
+ def test_value(self, device, dtype):
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.5, 0.5, 0.3], [0.5, 0.3, 0.3], [0.4, 0.4, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ assert_allclose(open(input, kernel), expected)
+
+ def test_exception(self, device, dtype):
+ input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert open([0.], kernel)
+
+ with pytest.raises(TypeError):
+ assert open(input, [0.])
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert open(test, kernel)
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert open(input, test)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64)
+ kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64)
+ assert gradcheck(open, (input, kernel), raise_exception=True)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = open
+ op_script = torch.jit.script(op)
+
+ input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ actual = op_script(input, kernel)
+ expected = op(input, kernel)
+
+ assert_allclose(actual, expected)
diff --git a/test/morphology/test_top_hat.py b/test/morphology/test_top_hat.py
new file mode 100644
index 000000000..4baadc74b
--- /dev/null
+++ b/test/morphology/test_top_hat.py
@@ -0,0 +1,68 @@
+import pytest
+import torch
+from kornia.morphology.basic_operators import _se_to_mask
+from kornia.morphology.morphology import top_hat
+import kornia.testing as utils # test utils
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestTopHat():
+
+ def test_smoke(self, device, dtype):
+ kernel = torch.rand(3, 3, device=device, dtype=dtype)
+ assert _se_to_mask(kernel) is not None
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize(
+ "kernel", [(3, 3), (5, 5)])
+ def test_cardinality(self, device, dtype, shape, kernel):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ krnl = torch.ones(kernel, device=device, dtype=dtype)
+ assert top_hat(img, krnl).shape == shape
+
+ def test_value(self, device, dtype):
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
+ device=device, dtype=dtype)[None, None, :, :]
+ kernel = torch.tensor([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], device=device, dtype=dtype)
+ expected = torch.tensor([[0., 0.5, 0.], [0.2, 0., 0.5], [0., 0.5, 0.]],
+ device=device, dtype=dtype)[None, None, :, :]
+ assert_allclose(top_hat(input, kernel), expected)
+
+ def test_exception(self, device, dtype):
+ input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert top_hat([0.], kernel)
+
+ with pytest.raises(TypeError):
+ assert top_hat(input, [0.])
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert top_hat(test, kernel)
+
+ with pytest.raises(ValueError):
+ test = torch.ones(2, 3, 4, device=device, dtype=dtype)
+ assert top_hat(input, test)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64)
+ kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64)
+ assert gradcheck(top_hat, (input, kernel), raise_exception=True)
+
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = top_hat
+ op_script = torch.jit.script(op)
+
+ input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ actual = op_script(input, kernel)
+ expected = op(input, kernel)
+
+ assert_allclose(actual, expected)