π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feat] Added combine patches (#1309)
Jian Shi807e7178bca1
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex 8bd95a55f..778a36d40 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -1,6 +1,19 @@from kornia.contrib.classification import ClassificationHeadfrom kornia.contrib.connected_components import connected_components-from kornia.contrib.extract_patches import extract_tensor_patches, ExtractTensorPatches+from kornia.contrib.extract_patches import (+ combine_tensor_patches,+ CombineTensorPatches,+ extract_tensor_patches,+ ExtractTensorPatches,+)from kornia.contrib.vit import VisionTransformer-__all__ = ["connected_components", "extract_tensor_patches", "ExtractTensorPatches"]+__all__ = [+ "connected_components",+ "extract_tensor_patches",+ "ExtractTensorPatches",+ "combine_tensor_patches",+ "CombineTensorPatches",+ "VisionTransformer",+ "ClassificationHead"+]diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.pyindex 4cab25271..dd4b61a38 100644--- a/kornia/contrib/extract_patches.py+++ b/kornia/contrib/extract_patches.py@@ -75,9 +75,111 @@ class ExtractTensorPatches(nn.Module):return extract_tensor_patches(input, self.window_size, stride=self.stride, padding=self.padding)-######################-# functional interface-######################+class CombineTensorPatches(nn.Module):+ r"""Module that combine patches from tensors.++ In the simplest case, the output value of the operator with input size+ :math:`(B, N, C, H_{out}, W_{out})` is :math:`(B, C, H, W)`.++ where+ - :math:`B` is the batch size.+ - :math:`N` denotes the total number of extracted patches stacked in+ - :math:`C` denotes the number of input channels.+ - :math:`H`, :math:`W` the input height and width of the input in pixels.+ - :math:`H_{out}`, :math:`W_{out}` denote to denote to the patch size+ defined in the function signature.+ left-right and top-bottom order.++ * :attr:`window_size` is the size of the sliding window and controls the+ shape of the output tensor and defines the shape of the output patch.+ * :attr:`stride` controls the stride to apply to the sliding window and+ regulates the overlapping between the extracted patches.+ * :attr:`padding` controls the amount of implicit zeros-paddings on both+ sizes at each dimension.++ The parameters :attr:`window_size`, :attr:`stride` and :attr:`padding` can+ be either:++ - a single ``int`` -- in which case the same value is used for the+ height and width dimension.+ - a ``tuple`` of two ints -- in which case, the first `int` is used for+ the height dimension, and the second `int` for the width dimension.++ Args:+ patches: patched tensor.+ window_size: the size of the sliding window and the output patch size.+ unpadding: remove the padding added to both side of the input.++ Shape:+ - Input: :math:`(B, N, C, H_{out}, W_{out})`+ - Output: :math:`(B, C, H, W)`++ Example:+ >>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))+ >>> combine_tensor_patches(out, window_size=(2, 2), stride=(2, 2))+ tensor([[[[ 0, 1, 2, 3],+ [ 4, 5, 6, 7],+ [ 8, 9, 10, 11],+ [12, 13, 14, 15]]]])+ """++ def __init__(+ self,+ window_size: Union[int, Tuple[int, int]],+ unpadding: Union[int, Tuple[int, int]] = 0,+ ) -> None:+ super().__init__()+ 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])++ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore+ return combine_tensor_patches(input, self.window_size, stride=self.window_size, unpadding=self.unpadding)+++def combine_tensor_patches(+ patches: torch.Tensor,+ window_size: Tuple[int, int] = (4, 4),+ stride: Tuple[int, int] = (4, 4),+ unpadding: Optional[Tuple[int, int, int, int]] = None,+) -> torch.Tensor:+ """Restore input from patches.++ Args:+ patches: patched tensor.+ window_size: the size of the sliding window and the output patch size.+ stride: stride of the sliding window.+ unpadding: remove the padding added to both side of the input.++ Shape:+ - Input: :math:`(B, N, C, H_{out}, W_{out})`+ - Output: :math:`(B, C, H, W)`++ Example:+ >>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))+ >>> combine_tensor_patches(out, window_size=(2, 2), stride=(2, 2))+ tensor([[[[ 0, 1, 2, 3],+ [ 4, 5, 6, 7],+ [ 8, 9, 10, 11],+ [12, 13, 14, 15]]]])+ """+ 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 is not None:+ window_size = (+ window_size[0] + (unpadding[0] + unpadding[1]) // window_size[0],+ window_size[1] + (unpadding[2] + unpadding[3]) // 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:+ restored_tensor = torch.nn.functional.pad(restored_tensor, [-i for i in unpadding])+ return restored_tensordef _extract_tensor_patchesnd(diff --git a/test/test_contrib.py b/test/test_contrib.pyindex d2b82c901..be9aac2a4 100644--- a/test/test_contrib.py+++ b/test/test_contrib.py@@ -132,12 +132,12 @@ class TestConnectedComponents:class TestExtractTensorPatches:def test_smoke(self, device):- input = torch.arange(16.0).view(1, 1, 4, 4).to(device)+ input = 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)def test_b1_ch1_h4w4_ws3(self, device):- input = torch.arange(16.0).view(1, 1, 4, 4).to(device)+ input = torch.arange(16.0, device=device).view(1, 1, 4, 4)m = kornia.contrib.ExtractTensorPatches(3)patches = m(input)assert patches.shape == (1, 4, 1, 3, 3)@@ -147,7 +147,7 @@ class TestExtractTensorPatches:assert_close(input[0, :, 1:, 1:], patches[0, 3])def test_b1_ch2_h4w4_ws3(self, device):- input = torch.arange(16.0).view(1, 1, 4, 4).to(device)+ input = torch.arange(16.0, device=device).view(1, 1, 4, 4)input = input.expand(-1, 2, -1, -1) # copy all channelsm = kornia.contrib.ExtractTensorPatches(3)patches = m(input)@@ -158,7 +158,7 @@ class TestExtractTensorPatches:assert_close(input[0, :, 1:, 1:], patches[0, 3])def test_b1_ch1_h4w4_ws2(self, device):- input = torch.arange(16.0).view(1, 1, 4, 4).to(device)+ input = torch.arange(16.0, device=device).view(1, 1, 4, 4)m = kornia.contrib.ExtractTensorPatches(2)patches = m(input)assert patches.shape == (1, 9, 1, 2, 2)@@ -168,7 +168,7 @@ class TestExtractTensorPatches:assert_close(input[0, :, 2:4, 1:3], patches[0, 7])def test_b1_ch1_h4w4_ws2_stride2(self, device):- input = torch.arange(16.0).view(1, 1, 4, 4).to(device)+ input = torch.arange(16.0, device=device).view(1, 1, 4, 4)m = kornia.contrib.ExtractTensorPatches(2, stride=2)patches = m(input)assert patches.shape == (1, 4, 1, 2, 2)@@ -178,7 +178,7 @@ class TestExtractTensorPatches:assert_close(input[0, :, 2:4, 2:4], patches[0, 3])def test_b1_ch1_h4w4_ws2_stride21(self, device):- input = torch.arange(16.0).view(1, 1, 4, 4).to(device)+ input = torch.arange(16.0, device=device).view(1, 1, 4, 4)m = kornia.contrib.ExtractTensorPatches(2, stride=(2, 1))patches = m(input)assert patches.shape == (1, 6, 1, 2, 2)@@ -246,3 +246,33 @@ class TestExtractTensorPatches:input = torch.rand(2, 3, 4, 4).to(device)input = utils.tensor_to_gradcheck_var(input) # to varassert gradcheck(kornia.contrib.extract_tensor_patches, (input, 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)+ m = kornia.contrib.CombineTensorPatches((2, 2))+ patches = kornia.contrib.extract_tensor_patches(+ input, window_size=(2, 2), stride=(2, 2))+ assert m(patches).shape == (1, 1, 4, 4)+ assert (input == m(patches)).all()++ def test_error(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), padding=1)+ with pytest.raises(NotImplementedError):+ 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)+ patches = kornia.contrib.extract_tensor_patches(+ input, 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()++ 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)