Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Allow CombineTensorPatches to work with overlapping patches (#2650)

Ashwin Nairc8d9f0bd0642
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index ec4c5b094..b16eaf05a 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -1,16 +1,16 @@
+import math
from typing import Optional, Tuple, Union, cast
import torch
+import torch.nn.functional as F
from torch.nn.modules.utils import _pair
-from kornia.core import Module, Tensor, concatenate, pad
-
-PadType = Union[Tuple[int, int], Tuple[int, int, int, int]]
+from kornia.core import Module, Tensor, pad
def compute_padding(
original_size: Union[int, Tuple[int, int]], window_size: Union[int, Tuple[int, int]]
-) -> Tuple[int, int, int, int]:
+) -> Tuple[int, int]:
r"""Compute required padding to ensure chaining of :func:`extract_tensor_patches` and
:func:`combine_tensor_patches` produces expected result.
@@ -19,7 +19,7 @@ def compute_padding(
window_size: the size of the sliding window used while extracting patches.
Return:
- The required padding for `(top, bottom, left, right)` as a tuple of 4 ints.
+ The required padding for `(vertical, horizontal)` as a tuple of 2 ints.
Example:
>>> image = torch.arange(12).view(1, 1, 4, 3)
@@ -38,23 +38,16 @@ def compute_padding(
original_size = cast(Tuple[int, int], _pair(original_size))
window_size = cast(Tuple[int, int], _pair(window_size))
- def paddim(dim1: int, dim2: int) -> Tuple[int, int]:
- if dim1 % dim2 == 0:
- p1 = 0
- p2 = 0
- else:
- tmp = dim2 - (dim1 % dim2)
- if tmp % 2 == 0:
- p1 = p2 = tmp // 2
- else:
- p1 = tmp
- p2 = 0
- return p1, p2
-
- padt, padb = paddim(original_size[0], window_size[0])
- padl, padr = paddim(original_size[1], window_size[1])
+ if original_size[0] % window_size[0] != 0:
+ padh = math.ceil((window_size[0] - original_size[0] % window_size[0]) / 2)
+ else:
+ padh = 0
+ if original_size[1] % window_size[1] != 0:
+ padw = math.ceil((window_size[1] - original_size[1] % window_size[1]) / 2)
+ else:
+ padw = 0
- return (padt, padb, padl, padr)
+ return (padh, padw)
class ExtractTensorPatches(Module):
@@ -119,12 +112,12 @@ class ExtractTensorPatches(Module):
self,
window_size: Union[int, Tuple[int, int]],
stride: Optional[Union[int, Tuple[int, int]]] = 1,
- padding: Optional[Union[int, PadType]] = 0,
+ padding: Optional[Union[int, Tuple[int, int]]] = 0,
) -> None:
super().__init__()
self.window_size: Tuple[int, int] = _pair(window_size)
self.stride: Tuple[int, int] = _pair(stride)
- self.padding: PadType = _pair(padding)
+ self.padding: Tuple[int, int] = _pair(padding)
def forward(self, input: Tensor) -> Tensor:
return extract_tensor_patches(input, self.window_size, stride=self.stride, padding=self.padding)
@@ -149,10 +142,12 @@ class CombineTensorPatches(Module):
extracting tensor patches and defines the shape of the output patch.
* :attr:`window_size` is the size of the sliding window used while
extracting tensor patches.
+ * :attr:`stride` controls the stride to apply to the sliding window and
+ regulates the overlapping between the extracted patches.
* :attr:`unpadding` is the amount of padding to be removed. This value
must be the same as padding used while extracting tensor patches.
- The parameters :attr:`original_size`, :attr:`window_size`, and :attr:`unpadding` can
+ The parameters :attr:`original_size`, :attr:`window_size`, :attr:`stride`, and :attr:`unpadding` can
be either:
- a single ``int`` -- in which case the same value is used for the
@@ -168,6 +163,7 @@ class CombineTensorPatches(Module):
patches: patched tensor.
original_size: the size of the original tensor and the output patch size.
window_size: the size of the sliding window used.
+ stride: stride of the sliding window.
unpadding: remove the padding added to both side of the input.
Shape:
@@ -190,16 +186,18 @@ class CombineTensorPatches(Module):
self,
original_size: Union[int, Tuple[int, int]],
window_size: Union[int, Tuple[int, int]],
- unpadding: Union[int, PadType] = 0,
+ stride: Union[int, Tuple[int, int]],
+ unpadding: Union[int, Tuple[int, int]] = 0,
) -> None:
super().__init__()
self.original_size: Tuple[int, int] = _pair(original_size)
self.window_size: Tuple[int, int] = _pair(window_size)
- self.unpadding: PadType = _pair(unpadding)
+ self.stride: Tuple[int, int] = _pair(stride)
+ self.unpadding: Tuple[int, int] = _pair(unpadding)
def forward(self, input: Tensor) -> Tensor:
return combine_tensor_patches(
- input, self.original_size, self.window_size, stride=self.window_size, unpadding=self.unpadding
+ input, self.original_size, self.window_size, stride=self.stride, unpadding=self.unpadding
)
@@ -208,7 +206,8 @@ def combine_tensor_patches(
original_size: Union[int, Tuple[int, int]],
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]],
- unpadding: Union[int, PadType] = 0,
+ unpadding: Union[int, Tuple[int, int]] = 0,
+ eps: float = 1e-8,
) -> Tensor:
r"""Restore input from patches.
@@ -236,51 +235,49 @@ def combine_tensor_patches(
This function is supposed to be used in conjunction with :func:`extract_tensor_patches`.
"""
- if len(patches.shape) != 5:
+ if patches.ndim != 5:
raise ValueError(f"Invalid input shape, we expect BxNxCxHxW. Got: {patches.shape}")
original_size = cast(Tuple[int, int], _pair(original_size))
window_size = cast(Tuple[int, int], _pair(window_size))
stride = cast(Tuple[int, int], _pair(stride))
-
- if stride[0] != window_size[0] or stride[1] != window_size[1]:
- raise NotImplementedError(
- f"Only stride == window_size is supported. Got {stride} and {window_size}."
- "Please feel free to drop a PR to Kornia Github."
- )
-
- if unpadding:
- unpadding = cast(PadType, _pair(unpadding))
-
- if len(unpadding) not in [2, 4]:
- raise AssertionError("Unpadding must be either an int, tuple of two ints or tuple of four ints")
-
- if len(unpadding) == 2:
- pad_vert = _pair(unpadding[0])
- pad_horz = _pair(unpadding[1])
- else:
- pad_vert = unpadding[:2]
- pad_horz = unpadding[2:]
- unpadding = cast(Tuple[int, int, int, int], pad_horz + pad_vert)
-
- hpad_check = (original_size[0] + unpadding[2] + unpadding[3]) % window_size[0] == 0
- wpad_check = (original_size[1] + unpadding[0] + unpadding[1]) % window_size[1] == 0
-
- if not hpad_check or not wpad_check:
- raise NotImplementedError("Insufficient padding")
-
- window_size = (
- (original_size[0] + (unpadding[2] + unpadding[3])) // window_size[0],
- (original_size[1] + (unpadding[0] + unpadding[1])) // window_size[1],
- )
-
- patches_tensor = patches.view(-1, window_size[0], window_size[1], *patches.shape[-3:])
- restored_tensor = concatenate(torch.chunk(patches_tensor, window_size[0], 1), -2).squeeze(1)
- restored_tensor = concatenate(torch.chunk(restored_tensor, window_size[1], 1), -1).squeeze(1)
-
- if unpadding:
- unpadding = cast(Tuple[int, int, int, int], unpadding)
- restored_tensor = pad(restored_tensor, [-i for i in unpadding])
+ unpadding = cast(Tuple[int, int], _pair(unpadding))
+
+ if len(unpadding) != 2:
+ raise AssertionError("Unpadding must be either an int or a tuple of two ints")
+
+ ones = torch.ones(
+ patches.shape[0],
+ patches.shape[2],
+ original_size[0],
+ original_size[1],
+ device=patches.device,
+ dtype=patches.dtype,
+ )
+ patches = patches.permute(0, 2, 3, 4, 1)
+ patches = patches.reshape(patches.shape[0], -1, patches.shape[-1])
+ int_flag = 0
+ if not torch.is_floating_point(patches):
+ int_flag = 1
+ dtype = patches.dtype
+ patches = patches.float()
+ ones = ones.float()
+
+ # Calculate normalization map
+ unfold_ones = F.unfold(ones, kernel_size=window_size, stride=stride, padding=unpadding)
+ norm_map = F.fold(
+ input=unfold_ones, output_size=original_size, kernel_size=window_size, stride=stride, padding=unpadding
+ )
+
+ # Restored tensor
+ saturated_restored_tensor = F.fold(
+ input=patches, output_size=original_size, kernel_size=window_size, stride=stride, padding=unpadding
+ )
+
+ # Remove satuation effect due to multiple summations
+ restored_tensor = saturated_restored_tensor / (norm_map + eps)
+ if int_flag:
+ restored_tensor = restored_tensor.to(dtype)
return restored_tensor
@@ -297,7 +294,7 @@ def extract_tensor_patches(
input: Tensor,
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]] = 1,
- padding: Union[int, PadType] = 0,
+ padding: Union[int, Tuple[int, int]] = 0,
) -> Tensor:
r"""Function that extract patches from tensors and stack them.
@@ -329,19 +326,21 @@ def extract_tensor_patches(
if len(input.shape) != 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
+ window_size = cast(Tuple[int, int], _pair(window_size))
+ stride = cast(Tuple[int, int], _pair(stride))
+
+ if (stride[0] > window_size[0]) | (stride[1] > window_size[1]):
+ raise AssertionError(f"Stride={stride} should be less than or equal to Window size={window_size}")
+
if padding:
- padding = cast(PadType, _pair(padding))
+ padding = cast(Tuple[int, int], _pair(padding))
- if len(padding) not in [2, 4]:
- raise AssertionError("Padding must be either an int, tuple of two ints or tuple of four ints")
+ if len(padding) != 2:
+ raise AssertionError("Padding must be either an int or a tuple of two ints")
- if len(padding) == 2:
- pad_vert = _pair(padding[0])
- pad_horz = _pair(padding[1])
- else:
- pad_vert = padding[:2]
- pad_horz = padding[2:]
- padding = cast(Tuple[int, int, int, int], pad_horz + pad_vert)
- input = pad(input, padding)
+ pad_vert = _pair(padding[0])
+ pad_horz = _pair(padding[1])
+ padding4 = cast(Tuple[int, int, int, int], pad_horz + pad_vert)
+ input = pad(input, padding4)
- return _extract_tensor_patchesnd(input, _pair(window_size), _pair(stride))
+ return _extract_tensor_patchesnd(input, window_size, stride)
diff --git a/test/contrib/test_contrib.py b/test/contrib/test_contrib.py
index 0379b85d4..7e6e42949 100644
--- a/test/contrib/test_contrib.py
+++ b/test/contrib/test_contrib.py
@@ -188,9 +188,9 @@ class TestConnectedComponents:
def test_compute_padding():
- assert kornia.contrib.compute_padding((6, 6), (2, 2)) == (0, 0, 0, 0)
- assert kornia.contrib.compute_padding((7, 7), (2, 2)) == (1, 0, 1, 0)
- assert kornia.contrib.compute_padding((8, 7), (4, 4)) == (0, 0, 1, 0)
+ assert kornia.contrib.compute_padding((6, 6), (2, 2)) == (0, 0)
+ assert kornia.contrib.compute_padding((7, 7), (2, 2)) == (1, 1)
+ assert kornia.contrib.compute_padding((8, 7), (4, 4)) == (0, 1)
class TestExtractTensorPatches:
@@ -314,7 +314,7 @@ class TestExtractTensorPatches:
class TestCombineTensorPatches:
def test_smoke(self, device, dtype):
img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
- m = kornia.contrib.CombineTensorPatches((4, 4), (2, 2))
+ m = kornia.contrib.CombineTensorPatches((4, 4), (2, 2), (2, 2))
patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2))
assert m(patches).shape == (1, 1, 4, 4)
assert_close(img, m(patches))
@@ -323,14 +323,14 @@ class TestCombineTensorPatches:
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), padding=1
)
- with pytest.raises(NotImplementedError):
+ with pytest.raises(RuntimeError):
kornia.contrib.combine_tensor_patches(patches, original_size=(4, 4), window_size=(2, 2), stride=(3, 2))
def test_rect_odd_dim(self, device, dtype):
img = torch.arange(12, device=device, dtype=dtype).view(1, 1, 4, 3)
- patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=(0, 0, 0, 1))
+ patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=(0, 2))
m = kornia.contrib.combine_tensor_patches(
- patches, original_size=(4, 3), window_size=(2, 2), stride=(2, 2), unpadding=(0, 0, 0, 1)
+ patches, original_size=(4, 3), window_size=(2, 2), stride=(2, 2), unpadding=(0, 2)
)
assert m.shape == (1, 1, 4, 3)
assert_close(img, m)
@@ -339,7 +339,7 @@ class TestCombineTensorPatches:
patches = kornia.contrib.extract_tensor_patches(
torch.arange(64, device=device, dtype=dtype).view(1, 1, 8, 8), window_size=(4, 4), stride=(4, 4), padding=1
)
- with pytest.raises(NotImplementedError):
+ with pytest.raises(AssertionError):
kornia.contrib.combine_tensor_patches(
patches, original_size=(8, 8), window_size=(4, 4), stride=(4, 4), unpadding=(1, 1, 1, 1)
)
@@ -353,36 +353,33 @@ class TestCombineTensorPatches:
patches, original_size=(6, 6), window_size=(4, 4), stride=(4, 4), unpadding=(1, 1, 1)
)
- def test_pad_quadruple(self, device, dtype):
- img = torch.arange(36, device=device, dtype=dtype).view(1, 1, 6, 6)
- patches = kornia.contrib.extract_tensor_patches(img, window_size=(4, 4), stride=(4, 4), padding=1)
-
- merged = kornia.contrib.combine_tensor_patches(
- patches, original_size=(6, 6), window_size=(4, 4), stride=(4, 4), unpadding=(1, 1, 1, 1)
- )
- assert merged.shape == (1, 1, 6, 6)
-
def test_rectangle_array(self, device, dtype):
img = torch.arange(24, device=device, dtype=dtype).view(1, 1, 4, 6)
patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=1)
- m = kornia.contrib.CombineTensorPatches((4, 6), (2, 2), unpadding=1)
+ m = kornia.contrib.CombineTensorPatches((4, 6), (2, 2), (2, 2), unpadding=1)
assert m(patches).shape == (1, 1, 4, 6)
assert_close(img, m(patches))
def test_padding1(self, device, dtype):
img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
- patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=1)
- m = kornia.contrib.CombineTensorPatches((4, 4), (2, 2), unpadding=1)
+ padding = kornia.contrib.compute_padding((4, 4), (2, 2))
+ patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(1, 1), padding=padding)
+ m = kornia.contrib.CombineTensorPatches((4, 4), (2, 2), stride=(1, 1), unpadding=padding)
assert m(patches).shape == (1, 1, 4, 4)
assert_close(img, m(patches))
def test_padding2(self, device, dtype):
img = torch.arange(64, device=device, dtype=dtype).view(1, 1, 8, 8)
patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=1)
- m = kornia.contrib.CombineTensorPatches((8, 8), (2, 2), unpadding=1)
+ m = kornia.contrib.CombineTensorPatches((8, 8), (2, 2), stride=(2, 2), unpadding=1)
assert m(patches).shape == (1, 1, 8, 8)
assert_close(img, m(patches))
+ def test_stride_greater_than_window_size(self, device, dtype):
+ img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
+ with pytest.raises(AssertionError):
+ kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(3, 3), padding=1)
+
def test_autopadding(self, device, dtype):
img = torch.arange(104, device=device, dtype=dtype).view(1, 1, 8, 13)
window_size = (3, 3)
@@ -390,7 +387,7 @@ class TestCombineTensorPatches:
patches = kornia.contrib.extract_tensor_patches(
img, window_size=window_size, stride=window_size, padding=padding
)
- m = kornia.contrib.CombineTensorPatches((8, 13), (3, 3), unpadding=padding)
+ m = kornia.contrib.CombineTensorPatches((8, 13), (3, 3), stride=window_size, unpadding=padding)
assert m(patches).shape == (1, 1, 8, 13)
assert_close(img, m(patches))