Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add distance transform implementation (#1490)

aaroswings6ea53d182f6e
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 61f5643f5..0b10d432f 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -46,3 +46,10 @@ Lambda
------
.. autoclass:: Lambda
+
+Distance Transform
+------
+
+.. autofunction:: distance_transform
+
+.. autoclass:: DistanceTransform
diff --git a/docs/source/references.bib b/docs/source/references.bib
index 55f7d23d5..ebbef6f0f 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -151,3 +151,24 @@
journal={IEEE Transactions on Biometrics, Behavior, and Identity Science},
year={2021}
}
+
+@article{karam2019convdt,
+ author={Karam, Christina and Sugimoto, Kenjiro and Hirakawa, Keigo},
+ journal={IEEE Signal Processing Letters},
+ title={Fast Convolutional Distance Transform},
+ year={2019},
+ volume={26},
+ number={6},
+ pages={853-857},
+ doi={10.1109/LSP.2019.2910466}
+}
+
+@inbook{pham2021dtlayer,
+ author = {Pham, Duc and Dovletov, Gurbandurdy and Pauli, Josef},
+ year = {2021},
+ month = {03},
+ pages = {432-444},
+ title = {A Differentiable Convolutional Distance Transform Layer for Improved Image Segmentation},
+ isbn = {978-3-030-71277-8},
+ doi = {10.1007/978-3-030-71278-5_31}
+}
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index cc4e701c9..84749f9f6 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,5 +1,6 @@
from .classification import ClassificationHead
from .connected_components import connected_components
+from .distance_transform import DistanceTransform, distance_transform
from .extract_patches import CombineTensorPatches, ExtractTensorPatches, combine_tensor_patches, extract_tensor_patches
from .face_detection import *
from .histogram_matching import histogram_matching, interp
@@ -21,4 +22,6 @@ __all__ = [
"ClassificationHead",
"Lambda",
"ImageStitcher",
+ "distance_transform",
+ "DistanceTransform",
]
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
new file mode 100644
index 000000000..2d5ac689c
--- /dev/null
+++ b/kornia/contrib/distance_transform.py
@@ -0,0 +1,100 @@
+import math
+
+import torch
+import torch.nn as nn
+
+from kornia.filters import filter2d
+from kornia.utils import create_meshgrid
+
+
+def distance_transform(
+ image: torch.Tensor,
+ kernel_size: int = 3,
+ h: float = 0.35
+) -> torch.Tensor:
+ r"""Approximates the Manhattan distance transform of images using cascaded convolution operations.
+
+ The value at each pixel in the output represents the distance to the nearest non-zero pixel in the image image.
+ It uses the method described in :cite:`pham2021dtlayer`.
+ The transformation is applied independently across the channel dimension of the images.
+
+ Args:
+ image: Image with shape :math:`(B,C,H,W)`.
+ kernel_size: size of the convolution kernel.
+ h: value that influence the approximation of the min function.
+
+ Returns:
+ tensor with shape :math:`(B,C,H,W)`.
+
+ Example:
+ >>> tensor = torch.zeros(1, 1, 5, 5)
+ >>> tensor[:,:, 1, 2] = 1
+ >>> dt = kornia.contrib.distance_transform(tensor)
+ """
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"image type is not a torch.Tensor. Got {type(image)}")
+
+ if not len(image.shape) == 4:
+ raise ValueError(f"Invalid image shape, we expect BxCxHxW. Got: {image.shape}")
+
+ if kernel_size % 2 == 0:
+ raise ValueError("Kernel size must be an odd number.")
+
+ # n_iters is set such that the DT will be able to propagate from any corner of the image to its far,
+ # diagonally opposite corner
+ n_iters: int = math.ceil(max(image.shape[2], image.shape[3]) / math.floor(kernel_size / 2))
+ grid = create_meshgrid(kernel_size, kernel_size, normalized_coordinates=False,
+ device=image.device, dtype=image.dtype)
+
+ grid -= math.floor(kernel_size / 2)
+ kernel = torch.hypot(grid[0, :, :, 0], grid[0, :, :, 1])
+ kernel = torch.exp(kernel / -h).unsqueeze(0)
+
+ out = torch.zeros_like(image)
+
+ # It is possible to avoid cloning the image if boundary = image, but this would require modifying the image tensor.
+ boundary = image.clone()
+
+ for i in range(n_iters):
+ cdt = filter2d(boundary, kernel, border_type='replicate')
+ cdt = -h * torch.log(cdt)
+
+ # We are calculating log(0) above.
+ cdt = torch.nan_to_num(cdt, posinf=0.0)
+
+ mask = torch.where(cdt > 0, 1.0, 0.0)
+ if mask.sum() == 0:
+ break
+
+ offset: int = i * kernel_size // 2
+ out += (offset + cdt) * mask
+ boundary[mask == 1] = 1
+
+ return out
+
+
+class DistanceTransform(nn.Module):
+ r"""Module that approximates the Manhattan (city block) distance transform of images using convolutions.
+
+ Args:
+ kernel_size: size of the convolution kernel.
+ h: value that influence the approximation of the min function.
+
+ """
+ def __init__(
+ self,
+ kernel_size: int = 3,
+ h: float = 0.35
+ ):
+ super().__init__()
+ self.kernel_size = kernel_size
+ self.h = h
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
+ # If images have multiple channels, view the channels in the batch dimension to match kernel shape.
+ if image.shape[1] > 1:
+ image_in = image.view(-1, 1, image.shape[-2], image.shape[-1])
+ else:
+ image_in = image
+
+ return distance_transform(image_in, self.kernel_size, self.h).view_as(image)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 4716ef1b2..dbc9f5aa8 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -371,8 +371,73 @@ class TestImageStitcher:
stitcher(input1, input2)
-class TestHistMatch:
+class TestConvDistanceTransform:
+ @pytest.mark.parametrize("kernel_size", [3, 5, 7])
+ def test_smoke(self, kernel_size, device, dtype):
+ input1 = torch.rand(1, 3, 100, 100, device=device, dtype=dtype)
+ input2 = torch.rand(1, 1, 100, 100, device=device, dtype=dtype)
+ distance_transformer = kornia.contrib.DistanceTransform(kernel_size)
+
+ output1 = distance_transformer(input1)
+ output2 = kornia.contrib.distance_transform(input2, kernel_size)
+
+ assert isinstance(output1, torch.Tensor)
+ assert isinstance(output2, torch.Tensor)
+ assert output1.shape == input1.shape
+
+ def test_module(self, device, dtype):
+ B, C, H, W = 1, 1, 99, 100
+ input1 = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ distance_transformer = kornia.contrib.DistanceTransform().to(device, dtype)
+
+ output1 = distance_transformer(input1)
+ output2 = kornia.contrib.distance_transform(input1)
+ tol_val: float = utils._get_precision(device, dtype)
+ assert_close(output1, output2, rtol=tol_val, atol=tol_val)
+
+ def test_exception(self, device, dtype):
+ B, C, H, W = 1, 1, 224, 224
+ input1 = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ input2 = torch.rand(C, H, W, device=device, dtype=dtype)
+
+ # Non-odd kernel size
+ with pytest.raises(ValueError):
+ ConvDT = kornia.contrib.DistanceTransform(6)
+ ConvDT.forward(input1)
+
+ with pytest.raises(ValueError):
+ kornia.contrib.distance_transform(input1, 4)
+ # Invalid input dimensions
+ with pytest.raises(ValueError):
+ kornia.contrib.distance_transform(input2)
+
+ # Invalid input type
+ with pytest.raises(TypeError):
+ kornia.contrib.distance_transform(None)
+
+ def test_value(self, device, dtype):
+ B, C, H, W = 1, 1, 4, 4
+ kernel_size = 7
+ h = 0.35
+ input1 = torch.zeros(B, C, H, W, device=device, dtype=dtype)
+ input1[:, :, 1, 1] = 1.0
+ expected_output1 = torch.tensor([[[
+ [1.4142135382, 1.0000000000, 1.4142135382, 2.2360680103],
+ [1.0000000000, 0.0000000000, 1.0000000000, 2.0000000000],
+ [1.4142135382, 1.0000000000, 1.4142135382, 2.2360680103],
+ [2.2360680103, 2.0000000000, 2.2360680103, 2.8284270763]
+ ]]], device=device, dtype=dtype)
+ output1 = kornia.contrib.distance_transform(input1, kernel_size, h)
+ assert_close(expected_output1, output1)
+
+ def test_gradcheck(self, device, dtype):
+ B, C, H, W = 1, 1, 32, 32
+ input1 = torch.ones(B, C, H, W, device=device, dtype=dtype, requires_grad=True)
+ assert gradcheck(kornia.contrib.distance_transform, (input1), raise_exception=True)
+
+
+class TestHistMatch:
def test_interp(self, device, dtype):
xp = torch.tensor([1, 2, 3], device=device, dtype=dtype)
fp = torch.tensor([4, 2, 0], device=device, dtype=dtype)