Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add fn to automatically compute padding (#1634)

Ashwin Nair5570eb1a727c
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 96551b205..2296eda9a 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -24,6 +24,7 @@ Image Segmentation
Image Patches
-------------
+.. autofunction:: compute_padding
.. autofunction:: extract_tensor_patches
.. autofunction:: combine_tensor_patches
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 84749f9f6..48099040f 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,7 +1,13 @@
from .classification import ClassificationHead
from .connected_components import connected_components
from .distance_transform import DistanceTransform, distance_transform
-from .extract_patches import CombineTensorPatches, ExtractTensorPatches, combine_tensor_patches, extract_tensor_patches
+from .extract_patches import (
+ CombineTensorPatches,
+ ExtractTensorPatches,
+ combine_tensor_patches,
+ compute_padding,
+ extract_tensor_patches,
+)
from .face_detection import *
from .histogram_matching import histogram_matching, interp
from .image_stitching import ImageStitcher
@@ -15,6 +21,7 @@ __all__ = [
"ExtractTensorPatches",
"combine_tensor_patches",
"CombineTensorPatches",
+ "compute_padding",
"histogram_matching",
"interp",
"VisionTransformer",
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index bc1412b04..34fe9cfa7 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -8,6 +8,55 @@ from torch.nn.modules.utils import _pair
PadType = Union[Tuple[int, int], Tuple[int, int, int, int]]
+def compute_padding(
+ original_size: Union[int, Tuple[int, int]], window_size: Union[int, Tuple[int, int]]
+) -> Tuple[int, int, int, int]:
+ r"""Compute required padding to ensure chaining of :func:`extract_tensor_patches` and
+ :func:`combine_tensor_patches` produces expected result.
+
+ Args:
+ original_size: the size of the original tensor.
+ 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.
+
+ Example:
+ >>> image = torch.arange(12).view(1, 1, 4, 3)
+ >>> padding = compute_padding((4,3), (3,3))
+ >>> out = extract_tensor_patches(image, window_size=(3, 3), stride=(3, 3), padding=padding)
+ >>> combine_tensor_patches(out, original_size=(4, 3), window_size=(3, 3), stride=(3, 3), unpadding=padding)
+ tensor([[[[ 0, 1, 2],
+ [ 3, 4, 5],
+ [ 6, 7, 8],
+ [ 9, 10, 11]]]])
+
+ .. note::
+ This function is supposed to be used in conjunction with :func:`extract_tensor_patches`
+ and :func:`combine_tensor_patches`.
+ """
+ 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])
+
+ return (padt, padb, padl, padr)
+
+
class ExtractTensorPatches(nn.Module):
r"""Module that extract patches from tensors and stack them.
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 17430a591..ad8ae9aff 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -145,6 +145,12 @@ class TestConnectedComponents:
assert_close(op(img), op_jit(img))
+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)
+
+
class TestExtractTensorPatches:
def test_smoke(self, device):
img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
@@ -335,6 +341,17 @@ class TestCombineTensorPatches:
assert m(patches).shape == (1, 1, 8, 8)
assert (img == m(patches)).all()
+ def test_autopadding(self, device, dtype):
+ img = torch.arange(104, device=device, dtype=dtype).view(1, 1, 8, 13)
+ window_size = (3, 3)
+ padding = kornia.contrib.compute_padding((8, 13), (3, 3))
+ 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)
+ assert m(patches).shape == (1, 1, 8, 13)
+ assert (img == m(patches)).all()
+
def test_gradcheck(self, device, dtype):
patches = kornia.contrib.extract_tensor_patches(
torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)