Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Resize augmentations module (#1547)

Edgar Ribaedf538c3c61f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 63ddc43d2..d44fe3731 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## :rocket: [0.X.X] - 2022-XX-XX
### :new: New Features
- Devcontainer (#1515)
+- Resize augmentation (#1545)
### :lady_beetle: Bug fixes
diff --git a/kornia/augmentation/_2d/geometric/__init__.py b/kornia/augmentation/_2d/geometric/__init__.py
index aa909f451..6ca86b72c 100644
--- a/kornia/augmentation/_2d/geometric/__init__.py
+++ b/kornia/augmentation/_2d/geometric/__init__.py
@@ -6,6 +6,7 @@ from kornia.augmentation._2d.geometric.fisheye import RandomFisheye
from kornia.augmentation._2d.geometric.horizontal_flip import RandomHorizontalFlip
from kornia.augmentation._2d.geometric.pad import PadTo
from kornia.augmentation._2d.geometric.perspective import RandomPerspective
+from kornia.augmentation._2d.geometric.resize import LongestMaxSize, Resize, SmallestMaxSize
from kornia.augmentation._2d.geometric.resized_crop import RandomResizedCrop
from kornia.augmentation._2d.geometric.rotation import RandomRotation
from kornia.augmentation._2d.geometric.thin_plate_spline import RandomThinPlateSpline
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
new file mode 100644
index 000000000..456461127
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -0,0 +1,125 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample
+from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
+from kornia.utils import eye_like
+
+
+class Resize(GeometricAugmentationBase2D):
+ """Resize to size.
+
+ Args:
+ size: Size (h, w) in pixels of the resized region or just one side.
+ side: Which side to resize, if size is only of type int.
+ resample: Resampling mode.
+ """
+
+ def __init__(
+ self,
+ size: Union[int, Tuple[int, int]],
+ side: str = "short",
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ align_corners: bool = True,
+ p: float = 1.0,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=False)
+ self._param_generator = cast(rg.ResizeGenerator, rg.ResizeGenerator(resize_to=size, side=side))
+ self.flags = dict(size=size, side=side, resample=Resample.get(resample), align_corners=align_corners)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ if params["resize_to"] == input.shape[-2:]:
+ return eye_like(3, input)
+
+ transform: torch.Tensor = get_perspective_transform(params["src"], params["dst"])
+ transform = transform.expand(input.shape[0], -1, -1)
+ return transform
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ B, C, _, _ = input.shape
+ out_size = tuple(params["resize_to"].tolist())
+ out = torch.empty(B, C, *out_size, device=input.device, dtype=input.dtype)
+ for i in range(B):
+ x1 = int(params["src"][i, 0, 0])
+ x2 = int(params["src"][i, 1, 0]) + 1
+ y1 = int(params["src"][i, 0, 1])
+ y2 = int(params["src"][i, 3, 1]) + 1
+ out[i] = resize(
+ input[i : i + 1, :, y1:y2, x1:x2],
+ out_size,
+ interpolation=(self.flags["resample"].name).lower(),
+ align_corners=self.flags["align_corners"],
+ )
+ return out
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ size = cast(Tuple[int, int], size)
+ mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
+ align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
+ padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
+
+
+class LongestMaxSize(Resize):
+ """Rescale an image so that maximum side is equal to max_size, keeping the aspect ratio of the initial image.
+
+ Args:
+ max_size: maximum size of the image after the transformation.
+ """
+
+ def __init__(
+ self,
+ max_size: int,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ align_corners: bool = True,
+ p: float = 1.0,
+ ) -> None:
+ # TODO: Support max_size list input to randomly select from
+ super().__init__(
+ size=max_size,
+ side="long",
+ resample=resample,
+ return_transform=return_transform,
+ align_corners=align_corners,
+ p=p,
+ )
+
+
+class SmallestMaxSize(Resize):
+ """Rescale an image so that minimum side is equal to max_size, keeping the aspect ratio of the initial image.
+
+ Args:
+ max_size: maximum size of the image after the transformation.
+ """
+
+ def __init__(
+ self,
+ max_size: int,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ align_corners: bool = True,
+ p: float = 1.0,
+ ) -> None:
+ # TODO: Support max_size list input to randomly select from
+ super().__init__(
+ size=max_size,
+ side="short",
+ resample=resample,
+ return_transform=return_transform,
+ align_corners=align_corners,
+ p=p,
+ )
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 842e51ab9..a719122f5 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -2,6 +2,7 @@ from kornia.augmentation._2d import (
CenterCrop,
ColorJitter,
Denormalize,
+ LongestMaxSize,
Normalize,
PadTo,
RandomAffine,
@@ -28,6 +29,8 @@ from kornia.augmentation._2d import (
RandomSolarize,
RandomThinPlateSpline,
RandomVerticalFlip,
+ Resize,
+ SmallestMaxSize,
)
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
@@ -57,6 +60,7 @@ __all__ = [
"ColorJitter",
"Normalize",
"Denormalize",
+ "LongestMaxSize",
"PadTo",
"RandomAffine",
"RandomBoxBlur",
@@ -82,6 +86,8 @@ __all__ = [
"RandomThinPlateSpline",
"RandomMixUp",
"RandomCutMix",
+ "Resize",
+ "SmallestMaxSize",
"AugmentationBase3D",
"CenterCrop3D",
"RandomAffine3D",
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
index 5794a6c46..a790b7129 100644
--- a/kornia/augmentation/random_generator/_2d/__init__.py
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -10,3 +10,4 @@ from kornia.augmentation.random_generator._2d.plain_uniform import *
from kornia.augmentation.random_generator._2d.posterize import *
from kornia.augmentation.random_generator._2d.probability import *
from kornia.augmentation.random_generator._2d.rectangle_earase import *
+from kornia.augmentation.random_generator._2d.resize import *
diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.py
new file mode 100644
index 000000000..507534fb0
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/resize.py
@@ -0,0 +1,90 @@
+from typing import Dict, Optional, Tuple, Union
+
+import torch
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _common_param_check
+from kornia.geometry.bbox import bbox_generator
+from kornia.geometry.transform.affwarp import _side_to_image_size
+
+
+class ResizeGenerator(RandomGeneratorBase):
+ r"""Get parameters for ```resize``` transformation for resize transform.
+
+ Args:
+ resize_to: Desired output size of the crop, like (h, w).
+ side: Which side to resize if `resize_to` is only of type int.
+
+ Returns:
+ parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+ - input_size (torch.Tensor): (h, w) from batch input.
+ - resize_to (tuple): new (h, w) for batch input.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(self, resize_to: Union[int, Tuple[int, int]], side: str = "short") -> None:
+ super().__init__()
+ self.resize_to = resize_to
+ self.side = side
+ self.device: Optional[torch.device] = None
+ self.dtype: Optional[torch.dtype] = None
+
+ def __repr__(self) -> str:
+ repr = f"resize_to={self.resize_to}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.device = device
+ self.dtype = dtype
+ pass
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device = self.device
+ _dtype = self.dtype
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ )
+
+ input_size = h, w = (batch_shape[-2], batch_shape[-1])
+
+ src = bbox_generator(
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(input_size[1], device=_device, dtype=_dtype),
+ torch.tensor(input_size[0], device=_device, dtype=_dtype),
+ ).repeat(batch_size, 1, 1)
+
+ if isinstance(self.resize_to, int):
+ aspect_ratio = w / h
+ self.resize_to = _side_to_image_size(self.resize_to, aspect_ratio, self.side)
+
+ if not (
+ len(self.resize_to) == 2
+ and isinstance(self.resize_to[0], (int,))
+ and isinstance(self.resize_to[1], (int,))
+ and self.resize_to[0] > 0
+ and self.resize_to[1] > 0
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")
+
+ dst = bbox_generator(
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(self.resize_to[1], device=_device, dtype=_dtype),
+ torch.tensor(self.resize_to[0], device=_device, dtype=_dtype),
+ ).repeat(batch_size, 1, 1)
+
+ _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+
+ return dict(src=src, dst=dst, input_size=_input_size, resize_to=torch.as_tensor(self.resize_to))
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 32cfce339..3ddbe0af4 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -11,6 +11,7 @@ from kornia.augmentation import (
CenterCrop,
ColorJitter,
Denormalize,
+ LongestMaxSize,
Normalize,
PadTo,
RandomBoxBlur,
@@ -30,6 +31,8 @@ from kornia.augmentation import (
RandomRotation,
RandomThinPlateSpline,
RandomVerticalFlip,
+ Resize,
+ SmallestMaxSize,
)
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample, pi
@@ -2783,6 +2786,30 @@ class TestPadTo:
assert (aug.inverse(out) == img).all()
+class TestResize:
+ def test_smoke(self, device, dtype):
+ img = torch.rand(1, 1, 4, 6, device=device, dtype=dtype)
+ aug = Resize(size=(4, 5))
+ out = aug(img)
+ assert out.shape == (1, 1, 4, 5)
+
+
+class TestSmallestMaxSize:
+ def test_smoke(self, device, dtype):
+ img = torch.rand(1, 1, 4, 6, device=device, dtype=dtype)
+ aug = SmallestMaxSize(max_size=2)
+ out = aug(img)
+ assert out.shape == (1, 1, 2, 3)
+
+
+class TestLongestMaxSize:
+ def test_smoke(self, device, dtype):
+ img = torch.rand(1, 1, 4, 6, device=device, dtype=dtype)
+ aug = LongestMaxSize(max_size=3)
+ out = aug(img)
+ assert out.shape == (1, 1, 2, 3)
+
+
class TestRandomPosterize:
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 4, 5, device=device, dtype=dtype)