Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

:two_men_holding_hands: Unfold->conv for morphology backbone (#1107)

Dmytro Mishkin8521fbffe724
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index e7c9e7b0a..c39a7ab79 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -4,6 +4,12 @@ import torch
import torch.nn.functional as F
+def _neight2channels_like_kernel(kernel: torch.Tensor) -> torch.Tensor:
+ h, w = kernel.size()
+ kernel = torch.eye(h * w, dtype=kernel.dtype, device=kernel.device)
+ return kernel.view(h * w, 1, h, w)
+
+
def dilation(
tensor: torch.Tensor,
kernel: torch.Tensor,
@@ -12,6 +18,7 @@ def dilation(
border_type: str = 'geodesic',
border_value: float = 0.0,
max_val: float = 1e4,
+ engine: str = 'unfold',
) -> torch.Tensor:
r"""Return the dilated image applying the same kernel in each channel.
@@ -33,6 +40,7 @@ def dilation(
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.
+ engine: convolution is faster and less memory hungry, and unfold is more stable numerically
Returns:
Dilated image with shape :math:`(B, C, H, W)`.
@@ -79,11 +87,21 @@ def dilation(
neighborhood = structuring_element.clone()
neighborhood[kernel == 0] = -max_val
- output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
- output, _ = torch.max(output + neighborhood.flip((0, 1)), 4)
- output, _ = torch.max(output, 4)
-
- return output
+ if engine == 'unfold':
+ output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
+ output, _ = torch.max(output + neighborhood.flip((0, 1)), 4)
+ output, _ = torch.max(output, 4)
+ elif engine == 'convolution':
+ B, C, H, W = tensor.size()
+ h_pad, w_pad = output.shape[-2:]
+ reshape_kernel = _neight2channels_like_kernel(kernel)
+ output, _ = F.conv2d(
+ output.view(B * C, 1, h_pad, w_pad), reshape_kernel, padding=0, bias=neighborhood.view(-1).flip(0)
+ ).max(dim=1)
+ output = output.view(B, C, H, W)
+ else:
+ raise NotImplementedError(f"engine {engine} is unknown, use 'convolution' or 'unfold'")
+ return output.view_as(tensor)
def erosion(
@@ -94,6 +112,7 @@ def erosion(
border_type: str = 'geodesic',
border_value: float = 0.0,
max_val: float = 1e4,
+ engine: str = 'unfold',
) -> torch.Tensor:
r"""Return the eroded image applying the same kernel in each channel.
@@ -115,6 +134,7 @@ def erosion(
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.
+ engine: ``convolution`` is faster and less memory hungry, and ``unfold`` is more stable numerically
Returns:
Eroded image with shape :math:`(B, C, H, W)`.
@@ -161,9 +181,21 @@ def erosion(
neighborhood = structuring_element.clone()
neighborhood[kernel == 0] = -max_val
- output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
- output, _ = torch.min(output - neighborhood, 4)
- output, _ = torch.min(output, 4)
+ if engine == 'unfold':
+ output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
+ output, _ = torch.min(output - neighborhood, 4)
+ output, _ = torch.min(output, 4)
+ elif engine == 'convolution':
+ B, C, H, W = tensor.size()
+ Hpad, Wpad = output.shape[-2:]
+ reshape_kernel = _neight2channels_like_kernel(kernel)
+ output, _ = F.conv2d(output.view(B * C, 1, Hpad, Wpad),
+ reshape_kernel,
+ padding=0,
+ bias=-neighborhood.view(-1)).min(dim=1)
+ output = output.view(B, C, H, W)
+ else:
+ raise NotImplementedError(f"engine {engine} is unknown, use 'convolution' or 'unfold'")
return output
@@ -176,6 +208,7 @@ def opening(
border_type: str = 'geodesic',
border_value: float = 0.0,
max_val: float = 1e4,
+ engine: str = 'unfold',
) -> torch.Tensor:
r"""Return the opened image, (that means, dilation after an erosion) applying the same kernel in each channel.
@@ -197,6 +230,7 @@ def opening(
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.
+ engine: convolution is faster and less memory hungry, and unfold is more stable numerically
Returns:
torch.Tensor: Opened image with shape :math:`(B, C, H, W)`.
@@ -239,6 +273,7 @@ def opening(
border_type=border_type,
border_value=border_value,
max_val=max_val,
+ engine=engine,
)
@@ -250,6 +285,7 @@ def closing(
border_type: str = 'geodesic',
border_value: float = 0.0,
max_val: float = 1e4,
+ engine: str = 'unfold',
) -> torch.Tensor:
r"""Return the closed image, (that means, erosion after a dilation) applying the same kernel in each channel.
@@ -271,6 +307,7 @@ def closing(
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.
+ engine: convolution is faster and less memory hungry, and unfold is more stable numerically
Returns:
Closed image with shape :math:`(B, C, H, W)`.
@@ -313,6 +350,7 @@ def closing(
border_type=border_type,
border_value=border_value,
max_val=max_val,
+ engine=engine,
)
@@ -325,6 +363,7 @@ def gradient(
border_type: str = 'geodesic',
border_value: float = 0.0,
max_val: float = 1e4,
+ engine: str = 'unfold',
) -> torch.Tensor:
r"""Return the morphological gradient of an image.
@@ -347,6 +386,7 @@ def gradient(
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.
+ engine: convolution is faster and less memory hungry, and unfold is more stable numerically
Returns:
Gradient image with shape :math:`(B, C, H, W)`.
@@ -369,6 +409,7 @@ def gradient(
border_type=border_type,
border_value=border_value,
max_val=max_val,
+ engine=engine,
) - erosion(
tensor,
kernel=kernel,
@@ -377,6 +418,7 @@ def gradient(
border_type=border_type,
border_value=border_value,
max_val=max_val,
+ engine=engine,
)
@@ -388,6 +430,7 @@ def top_hat(
border_type: str = 'geodesic',
border_value: float = 0.0,
max_val: float = 1e4,
+ engine: str = 'unfold',
) -> torch.Tensor:
r"""Return the top hat transformation of an image.
@@ -412,6 +455,7 @@ def top_hat(
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.
+ engine: convolution is faster and less memory hungry, and unfold is more stable numerically
Returns:
Top hat transformed image with shape :math:`(B, C, H, W)`.
@@ -446,6 +490,7 @@ def top_hat(
border_type=border_type,
border_value=border_value,
max_val=max_val,
+ engine=engine,
)
@@ -457,6 +502,7 @@ def bottom_hat(
border_type: str = 'geodesic',
border_value: float = 0.0,
max_val: float = 1e4,
+ engine: str = 'unfold',
) -> torch.Tensor:
r"""Return the bottom hat transformation of an image.
@@ -481,6 +527,7 @@ def bottom_hat(
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.
+ engine: convolution is faster and less memory hungry, and unfold is more stable numerically
Returns:
Top hat transformed image with shape :math:`(B, C, H, W)`.
@@ -516,6 +563,7 @@ def bottom_hat(
border_type=border_type,
border_value=border_value,
max_val=max_val,
+ engine=engine,
)
- tensor
)
diff --git a/test/morphology/test_closing.py b/test/morphology/test_closing.py
index 68f2907cb..d6fd2253c 100644
--- a/test/morphology/test_closing.py
+++ b/test/morphology/test_closing.py
@@ -41,8 +41,8 @@ class TestClosing:
assert_close(
closing(tensor, torch.ones_like(structural_element), structuring_element=structural_element),
expected,
- atol=1e-4,
- rtol=1e-4,
+ atol=1e-3,
+ rtol=1e-3,
)
def test_exception(self, device, dtype):
diff --git a/test/morphology/test_dilation.py b/test/morphology/test_dilation.py
index ceaee8847..02ca327fa 100644
--- a/test/morphology/test_dilation.py
+++ b/test/morphology/test_dilation.py
@@ -26,7 +26,8 @@ class TestDilate:
expected = torch.tensor([[1.0, 1.0, 1.0], [0.7, 1.0, 0.8], [0.9, 0.9, 0.9]], device=device, dtype=dtype)[
None, None, :, :
]
- assert_close(dilation(tensor, kernel), expected, atol=1e-4, rtol=1e-4)
+ assert_close(dilation(tensor, kernel, engine='unfold'), expected, atol=1e-4, rtol=1e-4)
+ assert_close(dilation(tensor, kernel, engine='convolution'), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[
@@ -39,11 +40,33 @@ class TestDilate:
None, None, :, :
]
assert_close(
- dilation(tensor, torch.ones_like(structural_element), structuring_element=structural_element),
+ dilation(tensor,
+ torch.ones_like(structural_element),
+ structuring_element=structural_element,
+ engine='unfold'),
expected,
- atol=1e-4,
- rtol=1e-4,
+ atol=1e-3,
+ rtol=1e-3,
)
+ assert_close(
+ dilation(tensor,
+ torch.ones_like(structural_element),
+ structuring_element=structural_element,
+ engine='convolution'),
+ expected,
+ atol=1e-3,
+ rtol=1e-3,
+ )
+
+ def test_flip(self, device, dtype):
+ tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[
+ None, None, :, :
+ ]
+ kernel = torch.tensor([[0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.7, 1.0, 1.0], [0.7, 1.0, 1.0], [0.7, 0.9, 0.9]], device=device, dtype=dtype)[
+ None, None, :, :
+ ]
+ assert_close(dilation(tensor, kernel), expected, atol=1e-3, rtol=1e-3)
def test_exception(self, device, dtype):
tensor = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_erosion.py b/test/morphology/test_erosion.py
index 9ad88f2e4..82d6d407d 100644
--- a/test/morphology/test_erosion.py
+++ b/test/morphology/test_erosion.py
@@ -27,6 +27,7 @@ class TestErode:
None, None, :, :
]
assert_close(erosion(tensor, kernel), expected, atol=1e-4, rtol=1e-4)
+ assert_close(erosion(tensor, kernel, engine='convolution'), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[
@@ -44,6 +45,26 @@ class TestErode:
atol=1e-4,
rtol=1e-4,
)
+ assert_close(
+ erosion(tensor,
+ torch.ones_like(structural_element),
+ structuring_element=structural_element,
+ engine='convolution'),
+ expected,
+ atol=1e-3,
+ rtol=1e-3,
+ )
+
+ def test_flip(self, device, dtype):
+ tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[
+ None, None, :, :
+ ]
+ kernel = torch.tensor([[0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.3, 0.3, 0.3], [0.3, 0.2, 0.2], [0.3, 0.2, 0.2]], device=device, dtype=dtype)[
+ None, None, :, :
+ ]
+ assert_close(erosion(tensor, kernel, engine='unfold'), expected, atol=1e-4, rtol=1e-4)
+ assert_close(erosion(tensor, kernel, engine='convolution'), expected, atol=1e-3, rtol=1e-3)
def test_exception(self, device, dtype):
tensor = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_opening.py b/test/morphology/test_opening.py
index 5d934dab6..253812b0d 100644
--- a/test/morphology/test_opening.py
+++ b/test/morphology/test_opening.py
@@ -41,8 +41,8 @@ class TestOpening:
assert_close(
opening(tensor, torch.ones_like(structural_element), structuring_element=structural_element),
expected,
- atol=1e-4,
- rtol=1e-4,
+ atol=1e-3,
+ rtol=1e-3,
)
def test_exception(self, device, dtype):