Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(contrib): add 3D volume support to distance_transform (#3470)

Rishabh Shrivastavae816450817df
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 888f8d1cd..2104e8191 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -15,82 +15,131 @@
# limitations under the License.
#
+from __future__ import annotations
+
import math
import torch
from torch import nn
-from kornia.filters import filter2d
-from kornia.geometry.grid import create_meshgrid
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
+from kornia.filters import filter2d, filter3d
+from kornia.geometry.grid import create_meshgrid, create_meshgrid3d
-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.
+def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float) -> torch.Tensor:
+ device = image.device
+ dtype = image.dtype
+ k_half = kernel_size // 2
- 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.
+ n_iters = math.ceil(max(image.shape[2], image.shape[3]) / k_half)
+ grid = create_meshgrid(kernel_size, kernel_size, False, device, dtype)
+ grid = grid - k_half
- 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.
+ dist = torch.hypot(grid[0, ..., 0], grid[0, ..., 1])
+ kernel = torch.exp(-dist / h).unsqueeze(0)
- Returns:
- tensor with shape :math:`(B,C,H,W)`.
+ out = torch.zeros_like(image)
+ boundary = image.clone()
+ signal_ones = torch.ones_like(boundary)
- Example:
- >>> tensor = torch.zeros(1, 1, 5, 5)
- >>> tensor[:,:, 1, 2] = 1
- >>> dt = kornia.contrib.distance_transform(tensor)
+ for i in range(n_iters):
+ cdt = filter2d(boundary, kernel, border_type="replicate")
+ cdt = -h * torch.log(cdt)
+ cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)
- """
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"image type is not a torch.Tensor. Got {type(image)}")
+ mask = cdt > 0
+ if not mask.any():
+ break
- if not len(image.shape) == 4:
- raise ValueError(f"Invalid image shape, we expect BxCxHxW. Got: {image.shape}")
+ offset: int = i * k_half
+ out = out + (offset + cdt) * mask.to(dtype=out.dtype)
+ boundary = torch.where(mask, signal_ones, boundary)
- if kernel_size % 2 == 0:
- raise ValueError("Kernel size must be an odd number.")
+ return out
- # 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)
+def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float) -> torch.Tensor:
+ device = image.device
+ dtype = image.dtype
+ k_half = kernel_size // 2
- out = torch.zeros_like(image)
+ n_iters = math.ceil(max(image.shape[2:]) / k_half)
+ grid = create_meshgrid3d(kernel_size, kernel_size, kernel_size, False, device, dtype)
+ grid = grid - k_half
+ dist = torch.norm(grid[0], p=2, dim=-1)
+ kernel = torch.exp(-dist / h).unsqueeze(0)
- # It is possible to avoid cloning the image if boundary = image, but this would require modifying the image tensor.
+ out = torch.zeros_like(image)
boundary = image.clone()
signal_ones = torch.ones_like(boundary)
for i in range(n_iters):
- cdt = filter2d(boundary, kernel, border_type="replicate")
+ cdt = filter3d(boundary, kernel, border_type="replicate")
cdt = -h * torch.log(cdt)
+ cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)
- # 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:
+ mask = cdt > 0
+ if not mask.any():
break
- offset: int = i * (kernel_size // 2)
- out += (offset + cdt) * mask
- boundary = torch.where(mask == 1, signal_ones, boundary)
+ offset: int = i * k_half
+ out = out + (offset + cdt) * mask.to(dtype=out.dtype)
+ boundary = torch.where(mask, signal_ones, boundary)
return out
+def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:
+ r"""Approximates the Euclidean distance transform of images/volumes using cascaded convolution operations.
+
+ The value at each pixel/voxel represents the distance to the nearest non-zero element.
+ It uses the method described in :cite:`pham2021dtlayer`.
+ The transformation is applied independently across the channel dimension.
+
+ Args:
+ image: Image or volume with shape :math:`(B,C,H,W)` or :math:`(B,C,D,H,W)`.
+ kernel_size: size of the convolution kernel. Must be an odd number.
+ h: value that influence the approximation of the min function.
+
+ Returns:
+ tensor with the same shape as input.
+
+ Example:
+ >>> # 2D example:
+ >>> tensor = torch.zeros(1, 1, 5, 5)
+ >>> tensor[:,:, 1, 2] = 1
+ >>> dt = distance_transform(tensor)
+ >>> # 3D example:
+ >>> volume = torch.zeros(1, 1, 5, 5, 5)
+ >>> volume[:, :, 2, 2, 2] = 1
+ >>> dt = distance_transform(volume)
+
+ """
+ # Validation using KORNIA_CHECK API
+ KORNIA_CHECK_IS_TENSOR(image)
+ KORNIA_CHECK(image.is_floating_point(), "image must be a floating point tensor")
+
+ KORNIA_CHECK(image.ndim in (4, 5), f"Invalid image shape, we expect BxCxHxW or BxCxDxHxW. Got: {image.shape}")
+
+ if image.ndim == 4:
+ KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])
+ else:
+ KORNIA_CHECK_SHAPE(image, ["B", "C", "D", "H", "W"])
+
+ # dtype / param checks
+ KORNIA_CHECK_TYPE(kernel_size, int, "kernel_size must be an int")
+ KORNIA_CHECK(kernel_size % 2 != 0 and kernel_size >= 3, "kernel_size must be an odd integer >= 3")
+ KORNIA_CHECK(h > 0, f"h must be a positive float, got {h}")
+
+ if image.ndim == 4:
+ return _distance_transform_2d_impl(image, kernel_size, h)
+
+ return _distance_transform_3d_impl(image, kernel_size, h)
+
+
class DistanceTransform(nn.Module):
- r"""Module that approximates the Manhattan (city block) distance transform of images using convolutions.
+ r"""Module that approximates the Euclidean distance transform of images/volumes using convolutions.
Args:
kernel_size: size of the convolution kernel.
@@ -104,9 +153,12 @@ class DistanceTransform(nn.Module):
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.
+ # Reshape multi-channel inputs to batch dimension to ensure independent processing
if image.shape[1] > 1:
- image_in = image.view(-1, 1, image.shape[-2], image.shape[-1])
+ # Dynamically determine spatial dimensions (works for H,W or D,H,W)
+ spatial_dims = image.shape[2:]
+ # Use reshape to handle non-contiguous tensors safely
+ image_in = image.reshape(-1, 1, *spatial_dims)
else:
image_in = image
diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.py
index c83844be7..12bd14cff 100755
--- a/tests/contrib/test_conv_distance_transformer.py
+++ b/tests/contrib/test_conv_distance_transformer.py
@@ -19,55 +19,112 @@ import pytest
import torch
import kornia
+from kornia.core.exceptions import BaseError, TypeCheckError
+from kornia.geometry.grid import create_meshgrid, create_meshgrid3d
from testing.base import BaseTester
class TestConvDistanceTransform(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, 5, 7])
- def test_smoke(self, kernel_size, device, dtype):
- sample1 = torch.rand(1, 3, 100, 100, device=device, dtype=dtype)
- sample2 = torch.rand(1, 1, 100, 100, device=device, dtype=dtype)
+ @pytest.mark.parametrize("shape", [(1, 3, 100, 100), (2, 2, 10, 10, 10)])
+ def test_smoke(self, kernel_size, shape, device, dtype):
+ sample = torch.rand(*shape, device=device, dtype=dtype)
distance_transformer = kornia.contrib.DistanceTransform(kernel_size)
- output1 = distance_transformer(sample1)
- output2 = kornia.contrib.distance_transform(sample2, kernel_size)
+ output1 = distance_transformer(sample)
+ output2 = kornia.contrib.distance_transform(sample, kernel_size)
assert isinstance(output1, torch.Tensor)
assert isinstance(output2, torch.Tensor)
- assert output1.shape == sample1.shape
+ assert output1.shape == sample.shape
+ self.assert_close(output1, output2)
def test_module(self, device, dtype):
B, C, H, W = 1, 1, 99, 100
- sample1 = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ sample2d = torch.rand(B, C, H, W, device=device, dtype=dtype)
distance_transformer = kornia.contrib.DistanceTransform().to(device, dtype)
- output1 = distance_transformer(sample1)
- output2 = kornia.contrib.distance_transform(sample1)
+ output1 = distance_transformer(sample2d)
+ output2 = kornia.contrib.distance_transform(sample2d)
self.assert_close(output1, output2)
+ B, C, D, H, W = 1, 1, 10, 10, 10
+ sample3d = torch.rand(B, C, D, H, W, device=device, dtype=dtype)
+ output3 = distance_transformer(sample3d)
+ output4 = kornia.contrib.distance_transform(sample3d)
+ self.assert_close(output3, output4)
+
def test_exception(self, device, dtype):
- B, C, H, W = 1, 1, 224, 224
- sample1 = torch.rand(B, C, H, W, device=device, dtype=dtype)
- sample2 = torch.rand(C, H, W, device=device, dtype=dtype)
+ B, C, H, W = 1, 1, 32, 32
+ sample2d = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ sample_wrong_dims = torch.rand(C, H, W, device=device, dtype=dtype)
- # Non-odd kernel size
- with pytest.raises(ValueError):
+ # Non-odd kernel size -> BaseError from KORNIA_CHECK
+ with pytest.raises(BaseError) as excinfo:
ConvDT = kornia.contrib.DistanceTransform(6)
- ConvDT.forward(sample1)
+ ConvDT.forward(sample2d)
+ assert "kernel_size must be an odd integer >= 3" in str(excinfo.value)
+
+ with pytest.raises(BaseError):
+ kornia.contrib.distance_transform(sample2d, 4)
- with pytest.raises(ValueError):
- kornia.contrib.distance_transform(sample1, 4)
+ # Kernel size too small
+ with pytest.raises(BaseError):
+ kornia.contrib.distance_transform(sample2d, 1)
- # Invalid input dimensions
- with pytest.raises(ValueError):
- kornia.contrib.distance_transform(sample2)
+ # Invalid input dimensions (3D tensor instead of 4D or 5D)
+ with pytest.raises(BaseError) as excinfo:
+ kornia.contrib.distance_transform(sample_wrong_dims)
+ assert "Invalid image shape" in str(excinfo.value)
- # Invalid input type
- with pytest.raises(TypeError):
+ # Invalid input type (None)
+ with pytest.raises(TypeCheckError):
kornia.contrib.distance_transform(None)
- def test_value(self, device, dtype):
+ # Integer input not supported (dtype check)
+ sample_int = torch.randint(0, 2, (B, C, H, W), device=device)
+ with pytest.raises(BaseError):
+ kornia.contrib.distance_transform(sample_int)
+
+ # invalid h
+ with pytest.raises(BaseError):
+ kornia.contrib.distance_transform(sample2d, kernel_size=3, h=0.0)
+
+ def test_kernel_geometry(self, device, dtype):
+ kernel_size = 5
+ k_half = kernel_size // 2
+ h = 0.35
+
+ # 2D Kernel Check
+ grid2d = create_meshgrid(kernel_size, kernel_size, False, device, dtype)
+ grid2d = grid2d - k_half
+ dist2d = torch.norm(grid2d[0], p=2, dim=-1)
+ kernel2d = torch.exp(-dist2d / h)
+
+ self.assert_close(kernel2d[k_half, k_half], torch.tensor(1.0, device=device, dtype=dtype))
+
+ self.assert_close(kernel2d[0, 0], kernel2d[-1, -1])
+
+ # 3D Kernel Check
+ grid3d = create_meshgrid3d(kernel_size, kernel_size, kernel_size, False, device, dtype)
+ grid3d = grid3d - k_half
+ dist3d = torch.norm(grid3d[0], p=2, dim=-1)
+ kernel3d = torch.exp(-dist3d / h)
+
+ # Center must be exactly 1.0
+ self.assert_close(kernel3d[k_half, k_half, k_half], torch.tensor(1.0, device=device, dtype=dtype))
+ self.assert_close(kernel3d[0, 0, 0], kernel3d[-1, -1, -1])
+
+ def test_noncontiguous_multi_channel(self, device, dtype):
+ B, C, H, W = 1, 2, 4, 4
+ sample = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ sample = sample.transpose(2, 3)
+ op = kornia.contrib.DistanceTransform()
+ out = op(sample)
+ assert out.shape == sample.shape
+
+ def test_value_2d(self, device, dtype):
B, C, H, W = 1, 1, 4, 4
kernel_size = 7
h = 0.35
@@ -90,21 +147,50 @@ class TestConvDistanceTransform(BaseTester):
output1 = kornia.contrib.distance_transform(sample1, kernel_size, h)
self.assert_close(expected_output1, output1)
+ def test_value_3d(self, device, dtype):
+ B, C, D, H, W = 1, 1, 3, 3, 3
+ kernel_size = 3
+ h = 0.35
+ sample1 = torch.zeros(B, C, D, H, W, device=device, dtype=dtype)
+
+ sample1[:, :, 1, 1, 1] = 1.0
+
+ output1 = kornia.contrib.distance_transform(sample1, kernel_size, h)
+
+ self.assert_close(output1[0, 0, 1, 1, 1], torch.tensor(0.0, device=device, dtype=dtype))
+
+ self.assert_close(output1[0, 0, 0, 1, 1], torch.tensor(1.0, device=device, dtype=dtype))
+
+ expected_corner = torch.tensor(1.7320508, device=device, dtype=dtype)
+ self.assert_close(output1[0, 0, 0, 0, 0], expected_corner)
+
def test_gradcheck(self, device):
B, C, H, W = 1, 1, 32, 32
- sample1 = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- self.gradcheck(kornia.contrib.distance_transform, (sample1))
+ sample2d = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
+ self.gradcheck(kornia.contrib.distance_transform, (sample2d,))
+
+ B, C, D, H, W = 1, 1, 5, 5, 5
+ sample3d = torch.ones(B, C, D, H, W, device=device, dtype=torch.float64, requires_grad=True)
+ self.gradcheck(kornia.contrib.distance_transform, (sample3d,))
def test_loss_grad(self, device, dtype):
B, C, H, W = 1, 1, 32, 32
sample1 = torch.rand(B, C, H, W, device=device, dtype=dtype, requires_grad=True)
sample2 = torch.rand(B, C, H, W, device=device, dtype=dtype, requires_grad=True)
tiny_module = torch.nn.Conv2d(1, 1, (3, 3), (1, 1), (1, 1)).to(device=device, dtype=dtype)
- sample1 = kornia.contrib.distance_transform(tiny_module(sample1))
- sample2 = kornia.contrib.distance_transform(sample2)
- loss = torch.nn.functional.mse_loss(sample1, sample2)
+ out1 = kornia.contrib.distance_transform(tiny_module(sample1))
+ out2 = kornia.contrib.distance_transform(sample2)
+ loss = torch.nn.functional.mse_loss(out1, out2)
loss.backward()
+ B, C, D, H, W = 1, 1, 10, 10, 10
+ sample3d_1 = torch.rand(B, C, D, H, W, device=device, dtype=dtype, requires_grad=True)
+ sample3d_2 = torch.rand(B, C, D, H, W, device=device, dtype=dtype, requires_grad=True)
+ out3 = kornia.contrib.distance_transform(sample3d_1)
+ out4 = kornia.contrib.distance_transform(sample3d_2)
+ loss_3d = torch.nn.functional.mse_loss(out3, out4)
+ loss_3d.backward()
+
def test_offset_parenthesis_fix(self, device, dtype):
img = torch.zeros(1, 1, 8, 4, device=device, dtype=dtype)
img[0, 0, 1, :] = 1.0
@@ -125,3 +211,12 @@ class TestConvDistanceTransform(BaseTester):
)
self.assert_close(out[0, 0], expected, rtol=1e-3, atol=1e-3)
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ input2d = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)
+ op = kornia.contrib.distance_transform
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(input2d), op_optimized(input2d))
+
+ input3d = torch.rand(1, 1, 8, 8, 8, device=device, dtype=dtype)
+ self.assert_close(op(input3d), op_optimized(input3d))