Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

:sparkler: Enable non/batched connected components (#1193)

Edgar Riba24e91de5add6
diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.py
index 4602d464c..9da31f042 100644
--- a/kornia/contrib/connected_components.py
+++ b/kornia/contrib/connected_components.py
@@ -2,7 +2,7 @@ import torch
import torch.nn.functional as F
-def connected_components(input: torch.Tensor, num_iterations: int = 100) -> torch.Tensor:
+def connected_components(image: 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
@@ -19,7 +19,7 @@ def connected_components(input: torch.Tensor, num_iterations: int = 100) -> torc
connected_components.html>`__.
Args:
- input: the binarized input image with shape :math:`(B, 1, H, W)`.
+ image: the binarized input image with shape :math:`(*, 1, H, W)`.
The image must be in floating point with range [0, 1].
num_iterations: the number of iterations to make the algorithm to converge.
@@ -30,24 +30,27 @@ def connected_components(input: torch.Tensor, num_iterations: int = 100) -> torc
>>> 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(image, torch.Tensor):
+ raise TypeError(f"Input imagetype is not a torch.Tensor. Got: {type(image)}")
if not isinstance(num_iterations, int) or num_iterations < 1:
raise TypeError("Input num_iterations must be a positive integer.")
- if len(input.shape) != 4 or input.shape[-3] != 1:
- raise ValueError(f"Input image shape must be Bx1xHxW. Got: {input.shape}")
+ if len(image.shape) < 3 or image.shape[-3] != 1:
+ raise ValueError(f"Input image shape must be (*,1,H,W). Got: {image.shape}")
- # precomput a mask with the valid values
- mask = input == 1
+ H, W = image.shape[-2:]
+ image_view = image.view(-1, 1, H, W)
+
+ # precompute a mask with the valid values
+ mask = image_view == 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))
+ B, _, _, _ = image_view.shape
+ out = torch.arange(B * H * W, device=image.device, dtype=image.dtype).view((-1, 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
+ return out.view_as(image)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 39f36c05f..572fad27c 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -72,6 +72,14 @@ class TestConnectedComponents:
out = kornia.contrib.connected_components(img, num_iterations=10)
assert out.shape == (1, 1, 3, 4)
+ @pytest.mark.parametrize("shape", [
+ (1, 3, 4), (2, 1, 3, 4)
+ ])
+ 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
+
def test_exception(self, device, dtype):
img = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
@@ -81,10 +89,6 @@ class TestConnectedComponents:
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)
@@ -127,12 +131,6 @@ class TestConnectedComponents:
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"
)
@@ -151,107 +149,107 @@ class TestConnectedComponents:
class TestExtractTensorPatches:
def test_smoke(self, device):
- input = torch.arange(16.0, device=device).view(1, 1, 4, 4)
+ img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(3)
- assert m(input).shape == (1, 4, 1, 3, 3)
+ assert m(img).shape == (1, 4, 1, 3, 3)
def test_b1_ch1_h4w4_ws3(self, device):
- input = torch.arange(16.0, device=device).view(1, 1, 4, 4)
+ img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(3)
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 4, 1, 3, 3)
- assert_close(input[0, :, :3, :3], patches[0, 0])
- assert_close(input[0, :, :3, 1:], patches[0, 1])
- assert_close(input[0, :, 1:, :3], patches[0, 2])
- assert_close(input[0, :, 1:, 1:], patches[0, 3])
+ assert_close(img[0, :, :3, :3], patches[0, 0])
+ assert_close(img[0, :, :3, 1:], patches[0, 1])
+ assert_close(img[0, :, 1:, :3], patches[0, 2])
+ assert_close(img[0, :, 1:, 1:], patches[0, 3])
def test_b1_ch2_h4w4_ws3(self, device):
- input = torch.arange(16.0, device=device).view(1, 1, 4, 4)
- input = input.expand(-1, 2, -1, -1) # copy all channels
+ img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
+ img = img.expand(-1, 2, -1, -1) # copy all channels
m = kornia.contrib.ExtractTensorPatches(3)
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 4, 2, 3, 3)
- assert_close(input[0, :, :3, :3], patches[0, 0])
- assert_close(input[0, :, :3, 1:], patches[0, 1])
- assert_close(input[0, :, 1:, :3], patches[0, 2])
- assert_close(input[0, :, 1:, 1:], patches[0, 3])
+ assert_close(img[0, :, :3, :3], patches[0, 0])
+ assert_close(img[0, :, :3, 1:], patches[0, 1])
+ assert_close(img[0, :, 1:, :3], patches[0, 2])
+ assert_close(img[0, :, 1:, 1:], patches[0, 3])
def test_b1_ch1_h4w4_ws2(self, device):
- input = torch.arange(16.0, device=device).view(1, 1, 4, 4)
+ img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(2)
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 9, 1, 2, 2)
- assert_close(input[0, :, 0:2, 1:3], patches[0, 1])
- assert_close(input[0, :, 0:2, 2:4], patches[0, 2])
- assert_close(input[0, :, 1:3, 1:3], patches[0, 4])
- assert_close(input[0, :, 2:4, 1:3], patches[0, 7])
+ assert_close(img[0, :, 0:2, 1:3], patches[0, 1])
+ assert_close(img[0, :, 0:2, 2:4], patches[0, 2])
+ assert_close(img[0, :, 1:3, 1:3], patches[0, 4])
+ assert_close(img[0, :, 2:4, 1:3], patches[0, 7])
def test_b1_ch1_h4w4_ws2_stride2(self, device):
- input = torch.arange(16.0, device=device).view(1, 1, 4, 4)
+ img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(2, stride=2)
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 4, 1, 2, 2)
- assert_close(input[0, :, 0:2, 0:2], patches[0, 0])
- assert_close(input[0, :, 0:2, 2:4], patches[0, 1])
- assert_close(input[0, :, 2:4, 0:2], patches[0, 2])
- assert_close(input[0, :, 2:4, 2:4], patches[0, 3])
+ assert_close(img[0, :, 0:2, 0:2], patches[0, 0])
+ assert_close(img[0, :, 0:2, 2:4], patches[0, 1])
+ assert_close(img[0, :, 2:4, 0:2], patches[0, 2])
+ assert_close(img[0, :, 2:4, 2:4], patches[0, 3])
def test_b1_ch1_h4w4_ws2_stride21(self, device):
- input = torch.arange(16.0, device=device).view(1, 1, 4, 4)
+ img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(2, stride=(2, 1))
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 6, 1, 2, 2)
- assert_close(input[0, :, 0:2, 1:3], patches[0, 1])
- assert_close(input[0, :, 0:2, 2:4], patches[0, 2])
- assert_close(input[0, :, 2:4, 0:2], patches[0, 3])
- assert_close(input[0, :, 2:4, 2:4], patches[0, 5])
+ assert_close(img[0, :, 0:2, 1:3], patches[0, 1])
+ assert_close(img[0, :, 0:2, 2:4], patches[0, 2])
+ assert_close(img[0, :, 2:4, 0:2], patches[0, 3])
+ assert_close(img[0, :, 2:4, 2:4], patches[0, 5])
def test_b1_ch1_h3w3_ws2_stride1_padding1(self, device):
- input = torch.arange(9.0).view(1, 1, 3, 3).to(device)
+ img = torch.arange(9.0).view(1, 1, 3, 3).to(device)
m = kornia.contrib.ExtractTensorPatches(2, stride=1, padding=1)
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 16, 1, 2, 2)
- assert_close(input[0, :, 0:2, 0:2], patches[0, 5])
- assert_close(input[0, :, 0:2, 1:3], patches[0, 6])
- assert_close(input[0, :, 1:3, 0:2], patches[0, 9])
- assert_close(input[0, :, 1:3, 1:3], patches[0, 10])
+ assert_close(img[0, :, 0:2, 0:2], patches[0, 5])
+ assert_close(img[0, :, 0:2, 1:3], patches[0, 6])
+ assert_close(img[0, :, 1:3, 0:2], patches[0, 9])
+ assert_close(img[0, :, 1:3, 1:3], patches[0, 10])
def test_b2_ch1_h3w3_ws2_stride1_padding1(self, device):
batch_size = 2
- input = torch.arange(9.0).view(1, 1, 3, 3).to(device)
- input = input.expand(batch_size, -1, -1, -1)
+ img = torch.arange(9.0).view(1, 1, 3, 3).to(device)
+ img = img.expand(batch_size, -1, -1, -1)
m = kornia.contrib.ExtractTensorPatches(2, stride=1, padding=1)
- patches = m(input)
+ patches = m(img)
assert patches.shape == (batch_size, 16, 1, 2, 2)
for i in range(batch_size):
- assert_close(input[i, :, 0:2, 0:2], patches[i, 5])
- assert_close(input[i, :, 0:2, 1:3], patches[i, 6])
- assert_close(input[i, :, 1:3, 0:2], patches[i, 9])
- assert_close(input[i, :, 1:3, 1:3], patches[i, 10])
+ assert_close(img[i, :, 0:2, 0:2], patches[i, 5])
+ assert_close(img[i, :, 0:2, 1:3], patches[i, 6])
+ assert_close(img[i, :, 1:3, 0:2], patches[i, 9])
+ assert_close(img[i, :, 1:3, 1:3], patches[i, 10])
def test_b1_ch1_h3w3_ws23(self, device):
- input = torch.arange(9.0).view(1, 1, 3, 3).to(device)
+ img = torch.arange(9.0).view(1, 1, 3, 3).to(device)
m = kornia.contrib.ExtractTensorPatches((2, 3))
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 2, 1, 2, 3)
- assert_close(input[0, :, 0:2, 0:3], patches[0, 0])
- assert_close(input[0, :, 1:3, 0:3], patches[0, 1])
+ assert_close(img[0, :, 0:2, 0:3], patches[0, 0])
+ assert_close(img[0, :, 1:3, 0:3], patches[0, 1])
def test_b1_ch1_h3w4_ws23(self, device):
- input = torch.arange(12.0).view(1, 1, 3, 4).to(device)
+ img = torch.arange(12.0).view(1, 1, 3, 4).to(device)
m = kornia.contrib.ExtractTensorPatches((2, 3))
- patches = m(input)
+ patches = m(img)
assert patches.shape == (1, 4, 1, 2, 3)
- assert_close(input[0, :, 0:2, 0:3], patches[0, 0])
- assert_close(input[0, :, 0:2, 1:4], patches[0, 1])
- assert_close(input[0, :, 1:3, 0:3], patches[0, 2])
- assert_close(input[0, :, 1:3, 1:4], patches[0, 3])
+ assert_close(img[0, :, 0:2, 0:3], patches[0, 0])
+ assert_close(img[0, :, 0:2, 1:4], patches[0, 1])
+ assert_close(img[0, :, 1:3, 0:3], patches[0, 2])
+ assert_close(img[0, :, 1:3, 1:4], patches[0, 3])
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
@torch.jit.script
- def op_script(input: torch.Tensor, height: int, width: int) -> torch.Tensor:
- return kornia.denormalize_pixel_coordinates(input, height, width)
+ def op_script(img: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ return kornia.denormalize_pixel_coordinates(img, height, width)
height, width = 3, 4
grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True).to(device)
@@ -262,19 +260,19 @@ class TestExtractTensorPatches:
assert_close(actual, expected)
def test_gradcheck(self, device):
- input = torch.rand(2, 3, 4, 4).to(device)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.contrib.extract_tensor_patches, (input, 3), raise_exception=True)
+ img = torch.rand(2, 3, 4, 4).to(device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.contrib.extract_tensor_patches, (img, 3), raise_exception=True)
class TestCombineTensorPatches:
def test_smoke(self, device, dtype):
- input = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
+ img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
m = kornia.contrib.CombineTensorPatches((2, 2))
patches = kornia.contrib.extract_tensor_patches(
- input, window_size=(2, 2), stride=(2, 2))
+ img, window_size=(2, 2), stride=(2, 2))
assert m(patches).shape == (1, 1, 4, 4)
- assert (input == m(patches)).all()
+ assert (img == m(patches)).all()
def test_error(self, device, dtype):
patches = kornia.contrib.extract_tensor_patches(
@@ -283,18 +281,18 @@ class TestCombineTensorPatches:
kornia.contrib.combine_tensor_patches(patches, window_size=(2, 2), stride=(3, 2))
def test_padding1(self, device, dtype):
- input = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
+ img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
patches = kornia.contrib.extract_tensor_patches(
- input, window_size=(2, 2), stride=(2, 2), padding=1)
+ img, window_size=(2, 2), stride=(2, 2), padding=1)
m = kornia.contrib.CombineTensorPatches((2, 2), unpadding=1)
assert m(patches).shape == (1, 1, 4, 4)
- assert (input == m(patches)).all()
+ assert (img == m(patches)).all()
def test_gradcheck(self, device, dtype):
patches = kornia.contrib.extract_tensor_patches(
torch.arange(16., device=device, dtype=dtype).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))
- input = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(kornia.contrib.combine_tensor_patches, (input, (2, 2), (2, 2)), raise_exception=True)
+ img = utils.tensor_to_gradcheck_var(patches) # to var
+ assert gradcheck(kornia.contrib.combine_tensor_patches, (img, (2, 2), (2, 2)), raise_exception=True)
class TestLambdaModule:
@@ -307,32 +305,32 @@ class TestLambdaModule:
def test_smoke(self, device, dtype):
B, C, H, W = 1, 3, 4, 5
- input = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
func = self.add_2_layer
if not callable(func):
raise TypeError(f"Argument lambd should be callable, got {repr(type(func).__name__)}")
- assert isinstance(kornia.contrib.Lambda(func)(input), torch.Tensor)
+ assert isinstance(kornia.contrib.Lambda(func)(img), torch.Tensor)
@pytest.mark.parametrize("x", [3, 2, 5])
def test_lambda_with_arguments(self, x, device, dtype):
B, C, H, W = 2, 3, 5, 7
- input = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
func = self.add_x_mul_y
lambda_module = kornia.contrib.Lambda(func)
- out = lambda_module(input, x)
+ out = lambda_module(img, x)
assert isinstance(out, torch.Tensor)
@pytest.mark.parametrize("shape", [(1, 3, 2, 3), (2, 3, 5, 7)])
def test_lambda(self, shape, device, dtype):
B, C, H, W = shape
- input = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
func = kornia.bgr_to_grayscale
lambda_module = kornia.contrib.Lambda(func)
- out = lambda_module(input)
+ out = lambda_module(img)
assert isinstance(out, torch.Tensor)
- def test_grad(self, device, dtype):
+ def test_gradcheck(self, device, dtype):
B, C, H, W = 1, 3, 4, 5
- input = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
+ img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
func = kornia.bgr_to_grayscale
- assert gradcheck(kornia.contrib.Lambda(func), (input,), raise_exception=True)
+ assert gradcheck(kornia.contrib.Lambda(func), (img,), raise_exception=True)