Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add the connected components labeling algorithm (#1184)

Edgar Ribaa968e35a936b
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 52004ac4e..b63c9975d 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -3,6 +3,7 @@ kornia.contrib
.. currentmodule:: kornia.contrib
+.. autofunction:: connected_components
.. autofunction:: extract_tensor_patches
Module
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 0fbfce291..8f5bba2ff 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,4 +1,5 @@
-from .extract_patches import extract_tensor_patches, ExtractTensorPatches
-from .max_blur_pool import max_blur_pool2d, MaxBlurPool2d
+from kornia.contrib.connected_components import connected_components
+from kornia.contrib.extract_patches import extract_tensor_patches, ExtractTensorPatches
+from kornia.contrib.max_blur_pool import max_blur_pool2d, MaxBlurPool2d
-__all__ = ["extract_tensor_patches", "max_blur_pool2d", "ExtractTensorPatches", "MaxBlurPool2d"]
+__all__ = ["connected_components", "extract_tensor_patches", "max_blur_pool2d", "ExtractTensorPatches", "MaxBlurPool2d"]
diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.py
new file mode 100644
index 000000000..dd6fd9869
--- /dev/null
+++ b/kornia/contrib/connected_components.py
@@ -0,0 +1,49 @@
+import torch
+import torch.nn.functional as F
+
+
+def connected_components(input: torch.Tensor, num_iterations: int = 100) -> torch.Tensor:
+ r"""Computes the Connected-component labelling (CCL) algorithm.
+
+ .. image:: https://github.com/kornia/data/raw/main/cells_segmented.png
+
+ The implementation is an adaptation of the following repository:
+
+ https://gist.github.com/efirdc/5d8bd66859e574c683a504a4690ae8bc
+
+ .. note::
+ This is an experimental API subject to changes and optimization improvements.
+
+ Args:
+ input: the binarized input image with shape :math:`(B, 1, H, W)`.
+ The image must be in floating point with range [0, 1].
+ num_iterations: the number of iterations to make the algorith to converge.
+
+ Return:
+ The labels image with the same shape of the input image.
+
+ Example:
+ >>> img = torch.rand(2, 1, 4, 5)
+ >>> img_labels = connected_components(img, num_iterations=100)
+ """
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input input type is not a torch.Tensor. Got: {type(input)}")
+
+ if not isinstance(num_iterations, int) or num_iterations < 1:
+ raise TypeError("Input num_iterations must be a postive integer.")
+
+ if len(input.shape) != 4 or input.shape[-3] != 1:
+ raise ValueError(f"Input image shape must be Bx1xHxW. Got: {input.shape}")
+
+ # precomput a mask with the valid values
+ mask = input == 1
+
+ # allocate the output tensors for labels
+ B, _, H, W = input.shape
+ out = torch.arange(B * W * H, device=input.device, dtype=input.dtype).reshape((B, 1, H, W))
+ out[~mask] = 0
+
+ for _ in range(num_iterations):
+ out[mask] = F.max_pool2d(out, kernel_size=3, stride=1, padding=1)[mask]
+
+ return out
diff --git a/test/test_contrib.py b/test/test_contrib.py
index c276e6160..ba8c3e9c0 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -5,6 +5,90 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
from kornia.testing import assert_close
+from packaging import version
+
+
+class TestConnectedComponents:
+ def test_smoke(self, device, dtype):
+ img = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
+ out = kornia.contrib.connected_components(img, num_iterations=10)
+ assert out.shape == (1, 1, 3, 4)
+
+ def test_exception(self, device, dtype):
+ img = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert kornia.contrib.connected_components(img, 1.0)
+
+ with pytest.raises(TypeError):
+ assert kornia.contrib.connected_components(img, 0)
+
+ with pytest.raises(ValueError):
+ img = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ assert kornia.contrib.connected_components(img, 1)
+
+ with pytest.raises(ValueError):
+ img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ assert kornia.contrib.connected_components(img, 2)
+
+ def test_value(self, device, dtype):
+ img = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 0.0, 0.0, 1.0],
+ [0.0, 1.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0, 1.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 14.0, 14.0, 0.0, 0.0, 11.0],
+ [0.0, 14.0, 14.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 34.0, 34.0, 0.0],
+ [0.0, 0.0, 0.0, 34.0, 34.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ out = kornia.contrib.connected_components(img, num_iterations=10)
+ assert_close(out, expected)
+
+ @pytest.mark.parametrize("shape", [(1, 1, 2, 3), (2, 1, 4, 7)])
+ def test_cardinality(self, device, dtype, shape):
+ img = torch.rand(shape, device=device, dtype=dtype)
+ out = kornia.contrib.connected_components(img, num_iterations=10)
+ assert out.shape == shape
+
+ @pytest.mark.skipif(
+ version.parse(torch.__version__) < version.parse("1.9"), reason="Tuple cannot be used with PyTorch < v1.9"
+ )
+ def test_gradcheck(self, device, dtype):
+ B, C, H, W = 2, 1, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.contrib.connected_components, (img,), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ B, C, H, W = 2, 1, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ op = kornia.contrib.connected_components
+ op_jit = torch.jit.script(op)
+ assert_close(op(img), op_jit(img))
class TestMaxBlurPool2d: