Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Update `combine_tensor_patches` (#1603)

Ashwin Nair6176a6b4484a
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 8c423ebde..2e25dd4d6 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -1,10 +1,12 @@
-from typing import Optional, Tuple, Union
+from typing import Optional, Tuple, Union, cast
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
+PadType = Union[Tuple[int, int], Tuple[int, int, int, int]]
+
class ExtractTensorPatches(nn.Module):
r"""Module that extract patches from tensors and stack them.
@@ -137,8 +139,7 @@ class CombineTensorPatches(nn.Module):
super().__init__()
self.original_size: Tuple[int, int] = _pair(original_size)
self.window_size: Tuple[int, int] = _pair(window_size)
- pad: Tuple[int, int] = _pair(unpadding)
- self.unpadding: Tuple[int, int, int, int] = (pad[0], pad[0], pad[1], pad[1])
+ self.unpadding: Tuple[int, int] = _pair(unpadding)
def forward(self, input: torch.Tensor) -> torch.Tensor:
return combine_tensor_patches(
@@ -148,13 +149,15 @@ class CombineTensorPatches(nn.Module):
def combine_tensor_patches(
patches: torch.Tensor,
- original_size: Tuple[int, int] = (16, 16),
- window_size: Tuple[int, int] = (4, 4),
- stride: Tuple[int, int] = (4, 4),
- unpadding: Optional[Tuple[int, int, int, int]] = None,
+ 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,
) -> torch.Tensor:
r"""Restore input from patches.
+ See :class:`~kornia.contrib.CombineTensorPatches` for details.
+
Args:
patches: patched tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
original_size: the size of the original tensor and the output patch size.
@@ -176,6 +179,14 @@ def combine_tensor_patches(
.. note::
This function is supposed to be used in conjunction with :func:`extract_tensor_patches`.
"""
+
+ if len(patches.shape) != 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}."
@@ -185,23 +196,36 @@ def combine_tensor_patches(
if original_size[0] % 2 != 0 or original_size[1] % 2 != 0:
raise NotImplementedError(f"Original image size must be divisible by 2. Got {original_size}")
- if unpadding is not None:
- hpad_check = (original_size[0] + unpadding[0] + unpadding[1]) % window_size[0] == 0
- wpad_check = (original_size[1] + unpadding[2] + unpadding[3]) % window_size[1] == 0
+ 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])
+ unpadding = cast(Tuple[int, int, int, int], pad_horz + pad_vert)
+ else:
+ unpadding = cast(Tuple[int, int, int, int], unpadding)
+
+ 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[0] + unpadding[1])) // window_size[0],
- (original_size[1] + (unpadding[2] + unpadding[3])) // window_size[1],
+ (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 = torch.cat(torch.chunk(patches_tensor, window_size[0], dim=1), -2).squeeze(1)
restored_tensor = torch.cat(torch.chunk(restored_tensor, window_size[1], dim=1), -1).squeeze(1)
- if unpadding is not None:
+ if unpadding:
+ unpadding = cast(Tuple[int, int, int, int], unpadding)
restored_tensor = F.pad(restored_tensor, [-i for i in unpadding])
return restored_tensor
@@ -221,7 +245,7 @@ def extract_tensor_patches(
input: torch.Tensor,
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]] = 1,
- padding: Union[int, Tuple[int, int]] = 0,
+ padding: Union[int, PadType] = 0,
) -> torch.Tensor:
r"""Function that extract patches from tensors and stack them.
@@ -254,7 +278,17 @@ def extract_tensor_patches(
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
if padding:
- pad_vert, pad_horz = _pair(padding)
- input = F.pad(input, [pad_horz, pad_horz, pad_vert, pad_vert])
+ padding = cast(PadType, _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:
+ pad_vert = _pair(padding[0])
+ pad_horz = _pair(padding[1])
+ padding = cast(Tuple[int, int, int, int], pad_horz + pad_vert)
+ else:
+ padding = cast(Tuple[int, int, int, int], padding)
+ input = F.pad(input, padding)
return _extract_tensor_patchesnd(input, _pair(window_size), _pair(stride))
diff --git a/test/test_contrib.py b/test/test_contrib.py
index d11059fae..557e734f4 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -294,6 +294,24 @@ class TestCombineTensorPatches:
patches, original_size=(8, 8), window_size=(4, 4), stride=(4, 4), unpadding=(1, 1, 1, 1)
)
+ def test_pad_triple_error(self, device, dtype):
+ patches = kornia.contrib.extract_tensor_patches(
+ torch.arange(36, device=device, dtype=dtype).view(1, 1, 6, 6), window_size=(4, 4), stride=(4, 4), padding=1
+ )
+ with pytest.raises(AssertionError):
+ kornia.contrib.combine_tensor_patches(
+ 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)