Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement extract_tensor_patches

edgarriba68505d026710
diff --git a/mypy_files.txt b/mypy_files.txt
index b07e675a8..8067b8860 100644
--- a/mypy_files.txt
+++ b/mypy_files.txt
@@ -6,3 +6,4 @@ torchgeometry/losses/tversky.py
torchgeometry/losses/depth_smooth.py
torchgeometry/homography_warper.py
torchgeometry/contrib/spatial_soft_argmax2d.py
+torchgeometry/contrib/extract_patches.py
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 7ed8feabd..179e9b9a9 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -7,6 +7,116 @@ from torch.autograd import gradcheck
import utils
+class TestExtractTensorPatches:
+ def _test_smoke(self):
+ input = torch.arange(16.).view(1, 1, 4, 4)
+ m = tgm.contrib.ExtractTensorPatches(3)
+ assert m(input).shape == (1, 4, 1, 3, 3)
+
+ def _test_b1_ch1_h4w4_ws3_4n(self):
+ input = torch.arange(16.).view(1, 1, 4, 4)
+ m = tgm.contrib.ExtractTensorPatches(3)
+ patches = m(input)
+ assert patches.shape == (1, 4, 1, 3, 3)
+ assert utils.check_equal_torch(input[0, :, :3, :3], patches[0, 0])
+ assert utils.check_equal_torch(input[0, :, :3, 1:], patches[0, 1])
+ assert utils.check_equal_torch(input[0, :, 1:, :3], patches[0, 2])
+ assert utils.check_equal_torch(input[0, :, 1:, 1:], patches[0, 3])
+
+ def _test_b1_ch2_h4w4_ws3_4n(self):
+ input = torch.arange(16.).view(1, 1, 4, 4)
+ input = input.expand(-1, 2, -1, -1) # copy all channels
+ m = tgm.contrib.ExtractTensorPatches(3)
+ patches = m(input)
+ assert patches.shape == (1, 4, 2, 3, 3)
+ assert utils.check_equal_torch(input[0, :, :3, :3], patches[0, 0])
+ assert utils.check_equal_torch(input[0, :, :3, 1:], patches[0, 1])
+ assert utils.check_equal_torch(input[0, :, 1:, :3], patches[0, 2])
+ assert utils.check_equal_torch(input[0, :, 1:, 1:], patches[0, 3])
+
+ def _test_b1_ch1_h4w4_ws2_4n(self):
+ input = torch.arange(16.).view(1, 1, 4, 4)
+ m = tgm.contrib.ExtractTensorPatches(2)
+ patches = m(input)
+ assert patches.shape == (1, 9, 1, 2, 2)
+ assert utils.check_equal_torch(input[0, :, 0:2, 0:2], patches[0, 0])
+ assert utils.check_equal_torch(input[0, :, 0:2, 1:3], patches[0, 1])
+ assert utils.check_equal_torch(input[0, :, 0:2, 2:4], patches[0, 2])
+ assert utils.check_equal_torch(input[0, :, 1:3, 0:2], patches[0, 3])
+ assert utils.check_equal_torch(input[0, :, 1:3, 1:3], patches[0, 4])
+ assert utils.check_equal_torch(input[0, :, 1:3, 2:4], patches[0, 5])
+ assert utils.check_equal_torch(input[0, :, 2:4, 0:2], patches[0, 6])
+ assert utils.check_equal_torch(input[0, :, 2:4, 1:3], patches[0, 7])
+ assert utils.check_equal_torch(input[0, :, 2:4, 2:4], patches[0, 8])
+
+ def _test_b1_ch1_h4w4_ws2_stride2(self):
+ input = torch.arange(16.).view(1, 1, 4, 4)
+ m = tgm.contrib.ExtractTensorPatches(2, stride=2)
+ patches = m(input)
+ assert patches.shape == (1, 4, 1, 2, 2)
+ assert utils.check_equal_torch(input[0, :, 0:2, 0:2], patches[0, 0])
+ assert utils.check_equal_torch(input[0, :, 0:2, 2:4], patches[0, 1])
+ assert utils.check_equal_torch(input[0, :, 2:4, 0:2], patches[0, 2])
+ assert utils.check_equal_torch(input[0, :, 2:4, 2:4], patches[0, 3])
+
+ def _test_b1_ch1_h4w4_ws2_stride21(self):
+ input = torch.arange(16.).view(1, 1, 4, 4)
+ m = tgm.contrib.ExtractTensorPatches(2, stride=(2, 1))
+ patches = m(input)
+ assert patches.shape == (1, 6, 1, 2, 2)
+ assert utils.check_equal_torch(input[0, :, 0:2, 0:2], patches[0, 0])
+ assert utils.check_equal_torch(input[0, :, 0:2, 1:3], patches[0, 1])
+ assert utils.check_equal_torch(input[0, :, 0:2, 2:4], patches[0, 2])
+ assert utils.check_equal_torch(input[0, :, 2:4, 0:2], patches[0, 3])
+ assert utils.check_equal_torch(input[0, :, 2:4, 1:3], patches[0, 4])
+ assert utils.check_equal_torch(input[0, :, 2:4, 2:4], patches[0, 5])
+
+ def _test_b1_ch1_h3w3_ws2_stride1_padding1(self):
+ input = torch.arange(9.).view(1, 1, 3, 3)
+ m = tgm.contrib.ExtractTensorPatches(2, stride=1, padding=1)
+ patches = m(input)
+ assert patches.shape == (1, 16, 1, 2, 2)
+ assert utils.check_equal_torch(input[0, :, 0:2, 0:2], patches[0, 5])
+ assert utils.check_equal_torch(input[0, :, 0:2, 1:3], patches[0, 6])
+ assert utils.check_equal_torch(input[0, :, 1:3, 0:2], patches[0, 9])
+ assert utils.check_equal_torch(input[0, :, 1:3, 1:3], patches[0, 10])
+
+ def _test_b2_ch1_h3w3_ws2_stride1_padding1(self):
+ batch_size = 2
+ input = torch.arange(9.).view(1, 1, 3, 3)
+ input = input.expand(batch_size, -1, -1, -1)
+ m = tgm.contrib.ExtractTensorPatches(2, stride=1, padding=1)
+ patches = m(input)
+ assert patches.shape == (batch_size, 16, 1, 2, 2)
+ for i in range(batch_size):
+ assert utils.check_equal_torch(input[i, :, 0:2, 0:2], patches[i, 5])
+ assert utils.check_equal_torch(input[i, :, 0:2, 1:3], patches[i, 6])
+ assert utils.check_equal_torch(input[i, :, 1:3, 0:2], patches[i, 9])
+ assert utils.check_equal_torch(
+ input[i, :, 1:3, 1:3], patches[i, 10])
+
+ # TODO: implement me
+ def _test_jit(self):
+ pass
+
+ def _test_gradcheck(self):
+ input = torch.rand(2, 3, 4, 4)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(tgm.contrib.extract_tensor_patches,
+ (input, 3,), raise_exception=True)
+
+ def test_run_all(self):
+ self._test_smoke()
+ self._test_b1_ch1_h4w4_ws3_4n()
+ self._test_b1_ch2_h4w4_ws3_4n()
+ self._test_b1_ch1_h4w4_ws2_4n()
+ self._test_b1_ch1_h4w4_ws2_stride2()
+ self._test_b1_ch1_h4w4_ws2_stride21()
+ self._test_b1_ch1_h3w3_ws2_stride1_padding1()
+ self._test_b2_ch1_h3w3_ws2_stride1_padding1()
+ self._test_gradcheck()
+
+
class TestSoftArgmax2d:
def _test_smoke(self):
input = torch.zeros(1, 1, 2, 3)
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index b9bd7a92c..f2ffb8bce 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -5,10 +5,10 @@ from .conversions import *
from .utils import *
from .imgwarp import *
from .transformations import *
-from .contrib import *
from torchgeometry import image
from torchgeometry import losses
+from torchgeometry import contrib
__version__ = '0.1.2rc1' # the current version of the lib
diff --git a/torchgeometry/contrib/__init__.py b/torchgeometry/contrib/__init__.py
index 3aa162bb2..897c4999b 100644
--- a/torchgeometry/contrib/__init__.py
+++ b/torchgeometry/contrib/__init__.py
@@ -1 +1,2 @@
from .spatial_soft_argmax2d import SpatialSoftArgmax2d, spatial_soft_argmax2d
+from .extract_patches import ExtractTensorPatches, extract_tensor_patches
diff --git a/torchgeometry/contrib/extract_patches.py b/torchgeometry/contrib/extract_patches.py
new file mode 100644
index 000000000..3aba5c299
--- /dev/null
+++ b/torchgeometry/contrib/extract_patches.py
@@ -0,0 +1,72 @@
+from typing import Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+class ExtractTensorPatches(nn.Module):
+ r"""Module that extract patches from tensors and stack them.
+ """
+
+ def __init__(
+ self,
+ window_size: int,
+ stride: int = 1,
+ padding: int = 0) -> None:
+ super(ExtractTensorPatches, self).__init__()
+ self.window_size: int = window_size
+ self.stride: int = stride
+ self.padding: int = padding
+ self.eps: float = 1e-6
+
+ # create base kernel
+ self.kernel: torch.Tensor = self.create_kernel(self.window_size)
+
+ @staticmethod
+ def create_kernel(window_size: int, eps: float = 1e-6) -> torch.Tensor:
+ window_range = window_size * window_size
+ kernel = torch.zeros(window_range, window_range) + eps
+ for i in range(window_range):
+ kernel[i, i] += 1.0
+ return kernel.view(window_range, 1, window_size, window_size)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(input):
+ raise TypeError("Input input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ # unpack shapes
+ batch_size, channels, height, width = input.shape
+
+ # run convolution 2d to extract patches
+ kernel: torch.Tensor = self.kernel.repeat(channels, 1, 1, 1)
+ kernel = kernel.to(input.device).to(input.dtype)
+ output_tmp: torch.Tensor = F.conv2d(
+ input,
+ kernel,
+ stride=self.stride,
+ padding=self.padding,
+ groups=channels)
+
+ # reshape the output tensor
+ output: torch.Tensor = output_tmp.view(
+ batch_size, channels, self.window_size, self.window_size, -1)
+ return output.permute(0, 4, 1, 2, 3) # BxNxCxhxw
+
+
+######################
+# functional interface
+######################
+
+
+def extract_tensor_patches(
+ input: torch.Tensor,
+ window_size: int, stride: int = 1, padding: int = 0) -> torch.Tensor:
+ r"""Function that extract patches from tensors and stack them.
+
+ See :class:`~torchgeometry.contrib.ExtractTensorPatches` for details.
+ """
+ return ExtractTensorPatches(window_size, stride, padding)(input)