Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement augmentation CenterCrop

edgarribae178321a257e
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 1683bc3e4..933443b19 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -343,3 +343,32 @@ class RandomAffine(AugmentationBase):
batch_size: int = self.infer_batch_size(input)
params = self.get_params(batch_size, height, width, self.degrees, self.translate, self.scale, self.shear)
return super().forward(input, params)
+
+
+class CenterCrop(AugmentationBase):
+ r"""Crops the given torch.Tensor at the center.
+ Args:
+ size (sequence or int): Desired output size of the crop. If size is an
+ int instead of sequence like (h, w), a square crop (size, size) is
+ made.
+ """
+
+ def __init__(self, size: Union[int, Tuple[int, int]], return_transform: bool = False) -> None:
+ super(CenterCrop, self).__init__(F.apply_center_crop, return_transform)
+ self.size = size
+ self.return_transform = return_transform
+
+ @staticmethod
+ def get_params(size: Union[int, Tuple[int, int]]) -> Dict[str, torch.Tensor]:
+ if isinstance(size, tuple):
+ size_param = torch.tensor([size[0], size[1]])
+ elif isinstance(size, int):
+ size_param = torch.tensor([size, size])
+ else:
+ raise Exception(f"Invalid type: {type(size)}")
+ return dict(size=size_param)
+
+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
+ if params is None:
+ params = self.get_params(self.size)
+ return super().forward(input, params)
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index 56f3452bc..42eb63dbe 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
from kornia.geometry.transform.flips import hflip, vflip
-from kornia.geometry.transform import get_perspective_transform, warp_perspective
+from kornia.geometry.transform import get_perspective_transform, warp_perspective, center_crop
from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHue
from kornia.color.gray import rgb_to_grayscale
@@ -465,3 +465,14 @@ def apply_affine(input: torch.Tensor,
return out_data.view_as(input), transform
return out_data.view_as(input)
+
+
+def apply_center_crop(input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ return_transform: bool = False) -> UnionType:
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ size1: int = int(params['size'][0].item())
+ size2: int = int(params['size'][1].item())
+ return center_crop(input, (size1, size2), return_transform)
diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.py
index 7d0d5e478..c11022d3a 100644
--- a/kornia/geometry/transform/crop.py
+++ b/kornia/geometry/transform/crop.py
@@ -1,4 +1,4 @@
-from typing import Tuple
+from typing import Tuple, Union
import torch
@@ -99,7 +99,8 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor,
return patches
-def center_crop(tensor: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
+def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
+ return_transform: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Crops the given tensor at the center.
Args:
@@ -187,4 +188,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
if is_unbatched:
patches = torch.squeeze(patches, dim=0)
+ if return_transform:
+ return patches, dst_trans_src
+
return patches
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 07bf2b75f..aa48a16b7 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1054,3 +1054,28 @@ class TestRandomGrayscale:
assert gradcheck(kornia.random_grayscale, (input, 0.), raise_exception=True)
assert gradcheck(kornia.random_grayscale, (input, 1.), raise_exception=True)
+
+
+class TestCenterCrop:
+
+ def test_no_transform(self, device):
+ inp = torch.rand(1, 2, 4, 4).to(device)
+ out = kornia.augmentation.CenterCrop(2)(inp)
+ assert out.shape == (1, 2, 2, 2)
+
+ def test_transform(self, device):
+ inp = torch.rand(1, 2, 5, 4).to(device)
+ out = kornia.augmentation.CenterCrop(2, return_transform=True)(inp)
+ assert len(out) == 2
+ assert out[0].shape == (1, 2, 2, 2)
+ assert out[1].shape == (1, 3, 3)
+
+ def test_no_transform_tuple(self, device):
+ inp = torch.rand(1, 2, 5, 4).to(device)
+ out = kornia.augmentation.CenterCrop((3, 4))(inp)
+ assert out.shape == (1, 2, 3, 4)
+
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 3, 4).to(device)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(kornia.augmentation.CenterCrop(3), (input,), raise_exception=True)