Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Initialized RandomCrop and RandomResizedCrop

Jian S45ed894d736e
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index cbe3d47c8..fa2a42d8c 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -1,7 +1,10 @@
from typing import Callable, Tuple, Union, List, Optional, Dict, cast
+import random
+import math
import torch
import torch.nn as nn
+from torch.nn.functional import pad
from . import functional as F
from . import param_gen as pg
@@ -9,6 +12,7 @@ from . import param_gen as pg
UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]
+Int2DBoarderUnionType = Union[int, Tuple[int, int], Tuple[int, int, int, int]]
class AugmentationBase(nn.Module):
@@ -240,3 +244,149 @@ class RandomRectangleErasing(nn.Module):
self.erase_scale_range,
self.aspect_ratio_range
)
+
+
+class RandomCrop(AugmentationBase):
+ r"""Random Crop on given size.
+
+ Args:
+ size (tuple): Desired output size of the crop, like (h, w).
+ padding (int or sequence, optional): Optional padding on each border
+ of the image. Default is None, i.e no padding. If a sequence of length
+ 4 is provided, it is used to pad left, top, right, bottom borders
+ respectively. If a sequence of length 2 is provided, it is used to
+ pad left/right, top/bottom borders, respectively.
+ pad_if_needed (boolean): It will pad the image if smaller than the
+ desired size to avoid raising an exception. Since cropping is done
+ after padding, the padding seems to be done at a random offset.
+ fill: Pixel fill value for constant fill. Default is 0. If a tuple of
+ length 3, it is used to fill R, G, B channels respectively.
+ This value is only used when the padding_mode is constant
+ padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ wont be concatenated
+ """
+
+ def __init__(self, size: Tuple[int, int], padding: Optional[Int2DBoarderUnionType] = None,
+ pad_if_needed: Optional[bool]=False, fill=0, padding_mode='constant',
+ return_transform: bool = False) -> None:
+ super(RandomCrop, self).__init__(F.apply_crop, return_transform)
+ self.size = size
+ self.padding = padding
+ self.pad_if_needed = pad_if_needed
+ self.fill = fill
+ self.padding_mode = padding_mode
+
+ def __repr__(self) -> str:
+ repr = f"(crop_size={self.size}, return_transform={self.return_transform})"
+ return self.__class__.__name__ + repr
+
+ @staticmethod
+ def get_params(batch_size: int, input_size: Tuple[int, int], size: Tuple[int, int]) -> Dict[str, torch.Tensor]:
+ return pg._random_crop_gen(batch_size, input_size, size)
+
+ def precrop_padding(self, input: torch.Tensor):
+
+ if self.padding is not None:
+ if isinstance(self.padding, int):
+ padding = [self.padding, self.padding, self.padding, self.padding]
+ elif isinstance(self.padding, tuple) and len(self.padding) == 2:
+ padding = [self.padding[1], self.padding[1], self.padding[0], self.padding[0]]
+ elif isinstance(self.padding, tuple) and len(self.padding) == 4:
+ padding = [self.padding[3], self.padding[2], self.padding[1], self.padding[0]] # type:ignore
+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+
+ if self.pad_if_needed and input.shape[-2] < self.size[1]:
+ padding = [self.size[1] - input.shape[-2], self.size[1] - input.shape[-2], 0, 0]
+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+
+ if self.pad_if_needed and input.shape[-1] < self.size[0]:
+ padding = [0, 0, self.size[0] - input.shape[-1], self.size[0] - input.shape[-1]]
+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+
+ return input
+
+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
+ if isinstance(input, tuple):
+ batch_shape = input[0].shape
+ input = (self.precrop_padding(input[0]), self.precrop_padding(input[1]))
+ else:
+ batch_shape = input.shape
+ input = self.precrop_padding(input)
+
+ if params is None:
+ batch_size = self.infer_batch_size(input)
+ params = RandomCrop.get_params(batch_size, batch_shape[-2:], self.size) # type: ignore
+ return super().forward(input, params)
+
+
+class RandomResizedCrop(AugmentationBase):
+ r"""Random Crop on given size and resizing the cropped patch to another.
+
+ Args:
+ size (Tuple[int, int]): expected output size of each edge
+ scale: range of size of the origin size cropped
+ ratio: range of aspect ratio of the origin aspect ratio cropped
+ interpolation: Default: PIL.Image.BILINEAR
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ wont be concatenated
+ """
+
+ def __init__(self, size: Tuple[int, int], scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.),
+ interpolation=None, return_transform: bool = False) -> None:
+ super(RandomResizedCrop, self).__init__(F.apply_crop, return_transform)
+ self.size = size
+ self.scale = scale
+ self.ratio = ratio
+ self.interpolation = interpolation
+ if interpolation is not None:
+ raise ValueError("Interpolation has not been implemented. Please set to None")
+
+ def __repr__(self) -> str:
+ repr = f"(size={self.size}, resize_to={self.resize_to}, return_transform={self.return_transform})"
+ return self.__class__.__name__ + repr
+
+ @staticmethod
+ def get_params(batch_size: int, input_size: Tuple[int, int], size: Tuple[int, int],
+ scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)) -> Dict[str, torch.Tensor]:
+ target_size = RandomResizedCrop.get_aspected_size(size, scale, ratio)
+ # TODO: scale and aspect ratio were fixed for one batch for now. Need to be separated.
+ return pg._random_crop_gen(batch_size, input_size, target_size, resize_to=size)
+
+ @staticmethod
+ def get_aspected_size(size, scale, ratio):
+ for attempt in range(10):
+ target_area = random.uniform(*scale) * size[0] * size[1]
+ log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
+ aspect_ratio = math.exp(random.uniform(*log_ratio))
+
+ w = int(round(math.sqrt(target_area * aspect_ratio)))
+ h = int(round(math.sqrt(target_area / aspect_ratio)))
+ if 0 < w < size[0] and 0 < h < size[1]:
+ return (w, h)
+
+ # Fallback to center crop
+ in_ratio = float(size[0]) / float(size[1])
+ if (in_ratio < min(ratio)):
+ w = size[0]
+ h = int(round(w / min(ratio)))
+ elif (in_ratio > max(ratio)):
+ h = size[1]
+ w = int(round(h * max(ratio)))
+ else: # whole image
+ w = size[0]
+ h = size[1]
+ return (w, h)
+
+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
+ if params is None:
+ batch_size = self.infer_batch_size(input)
+ if isinstance(input, tuple):
+ batch_shape = input[0].shape
+ else:
+ batch_shape = input.shape
+ params = RandomResizedCrop.get_params(
+ batch_size, batch_shape[-2:], self.size, self.resize_to) # type: ignore
+ return super().forward(input, params)
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index 1a0f45103..31a7ffde8 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -4,11 +4,13 @@ import torch
import torch.nn as nn
from kornia.geometry.transform.flips import hflip, vflip
+from kornia.geometry.transform.crop import _crop_wrapper, _get_perspective_dst, _get_perspective_src
from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHue
from kornia.color.gray import rgb_to_grayscale
from . import param_gen as pg
from .erasing import erase_rectangles, get_random_rectangles_params
+from .utils import _reshape_input, _validate_input_shape
UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
@@ -89,17 +91,7 @@ def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_tra
is set to ``True``
"""
- if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if len(input.shape) == 2:
- input = input.unsqueeze(0)
-
- if len(input.shape) == 3:
- input = input.unsqueeze(0)
-
- if len(input.shape) != 4:
- raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")
+ input = _reshape_input(input)
if not isinstance(return_transform, bool):
raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")
@@ -146,17 +138,7 @@ def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_tra
"""
# TODO: params validation
- if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if len(input.shape) == 2:
- input = input.unsqueeze(0)
-
- if len(input.shape) == 3:
- input = input.unsqueeze(0)
-
- if len(input.shape) != 4:
- raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")
+ input = _reshape_input(input)
if not isinstance(return_transform, bool):
raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")
@@ -206,17 +188,7 @@ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor],
"""
# TODO: params validation
- if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if len(input.shape) == 2:
- input = input.unsqueeze(0)
-
- if len(input.shape) == 3:
- input = input.unsqueeze(0)
-
- if len(input.shape) != 4:
- raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")
+ input = _reshape_input(input)
if not isinstance(return_transform, bool):
raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")
@@ -261,13 +233,9 @@ def apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor], return
"""
# TODO: params validation
- if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ input = _reshape_input(input)
- if len(input.shape) == 3 and input.shape[-3] == 3:
- input = input.unsqueeze(0)
-
- if len(input.shape) != 4 or input.shape[-3] != 3:
+ if _validate_input_shape(input, -3, 3):
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}")
if not isinstance(return_transform, bool):
@@ -327,3 +295,23 @@ def random_rectangle_erase(
)
images = erase_rectangles(images, rect_params)
return images
+
+
+def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:
+ """
+ Args:
+ params (dict): A dict that must have {'src': torch.Tensor, 'dst': torch.Tensor}. Can be generated from
+ kornia.augmentation.param_gen._random_crop_gen
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor.
+
+ Returns:
+ torch.Tensor: The grayscaled input
+ torch.Tensor: The applied cropping matrix :math: `(*, 4, 2)` if return_transform flag
+ is set to ``True``
+ """
+
+ if return_transform:
+ return _crop_wrapper(input, params['src'], params['dst']), params['src']
+
+ return _crop_wrapper(input, params['src'], params['dst'])
diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.py
index 7ffa099bc..a2b21c5c6 100644
--- a/kornia/augmentation/param_gen.py
+++ b/kornia/augmentation/param_gen.py
@@ -1,9 +1,11 @@
-from typing import Tuple, List, Union, Dict
+from typing import Tuple, List, Union, Dict, Optional
+import numpy as np
import torch
from torch.distributions import Uniform
from kornia.geometry import pi
+from kornia.geometry.transform.crop import _get_perspective_src, _get_perspective_dst
UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
@@ -121,3 +123,26 @@ def _random_prob_gen(batch_size: int, p: float = .5) -> Dict[str, torch.Tensor]:
batch_prob: torch.Tensor = probs < p
return {'batch_prob': batch_prob}
+
+
+def _random_crop_gen(batch_size: int, input_size: Tuple[int, int], size: Tuple[int, int],
+ resize_to: Optional[Tuple[int, int]] = None) -> Dict[str, torch.Tensor]:
+ x_diff = size[1] - input_size[1]
+ y_diff = size[0] - input_size[0]
+
+ if x_diff < 0 or y_diff < 0:
+ raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."
+ % (str(input_size), str(size)))
+
+ def _get_random_perspective_src(x_range, y_range, size):
+ x_start = np.random.randint(x_range)
+ y_start = np.random.randint(y_range)
+ return _get_perspective_src(x_start, y_start, size)
+
+ crop_src = torch.cat([ _get_random_perspective_src(x_diff, y_diff, size) for _ in range(batch_size)], dim=0)
+ if resize_to is None:
+ crop_dst = _get_perspective_dst(size)
+ else:
+ crop_dst = _get_perspective_dst(resize_to)
+
+ return {'src': crop_src, 'dst': crop_dst.repeat(batch_size, 1, 1)}
diff --git a/kornia/augmentation/utils.py b/kornia/augmentation/utils.py
new file mode 100644
index 000000000..13ebc0d12
--- /dev/null
+++ b/kornia/augmentation/utils.py
@@ -0,0 +1,43 @@
+import torch
+
+
+def _reshape_input(input: torch.Tensor) -> torch.Tensor:
+ r"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
+
+ Args:
+ input: torch.Tensor
+
+ Returns:
+ torch.Tensor
+ """
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ if len(input.shape) not in [2, 3, 4]:
+ raise ValueError(
+ f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")
+
+ if len(input.shape) == 2:
+ input = input.unsqueeze(0)
+
+ if len(input.shape) == 3:
+ input = input.unsqueeze(0)
+
+ return input
+
+
+def _validate_input_shape(input: torch.Tensor, channel_index: int, number: int) -> bool:
+ r"""Validate if an input has the right shape. e.g. to check if an input is channel first.
+ If channel first, the second channel of an RGB input shall be fixed to 3. To verify using:
+
+ _validate_input_shape(input, 2, 3)
+
+ Args:
+ input: torch.Tensor
+ channel_index: int
+ number: int
+
+ Returns:
+ bool
+ """
+ return input.shape[channel_index] == number
diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.py
index 7d0d5e478..e391cd149 100644
--- a/kornia/geometry/transform/crop.py
+++ b/kornia/geometry/transform/crop.py
@@ -69,28 +69,15 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor,
# [x, y] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0],
- [dst_w - 1, 0],
- [dst_w - 1, dst_h - 1],
- [0, dst_h - 1],
- ]]).repeat(points_src.shape[0], 1, 1).to(
- tensor.device).to(tensor.dtype)
+ points_dst: torch.Tensor = _get_perspective_dst(
+ size).repeat(points_src.shape[0], 1, 1).to(tensor.device).to(tensor.dtype)
# warping needs data in the shape of BCHW
is_unbatched: bool = tensor.ndimension() == 3
if is_unbatched:
tensor = torch.unsqueeze(tensor, dim=0)
- # compute transformation between points and warp
- dst_trans_src: torch.Tensor = get_perspective_transform(
- points_src, points_dst)
-
- # simulate broadcasting
- dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1)
-
- patches: torch.Tensor = warp_perspective(
- tensor, dst_trans_src, (int(dst_h), int(dst_w)))
+ patches = _crop_wrapper(tensor, points_src, points_dst)
# return in the original shape
if is_unbatched:
@@ -135,56 +122,71 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
.format(size))
# unpack input sizes
- dst_h: torch.Tensor = torch.tensor(size[0])
- dst_w: torch.Tensor = torch.tensor(size[1])
- src_h: torch.Tensor = torch.tensor(tensor.shape[-2])
- src_w: torch.Tensor = torch.tensor(tensor.shape[-1])
+ dst_h, dst_w = size
+ src_h, src_w = tensor.shape[-2:]
# compute start/end offsets
- dst_h_half: torch.Tensor = dst_h / 2
- dst_w_half: torch.Tensor = dst_w / 2
- src_h_half: torch.Tensor = src_h / 2
- src_w_half: torch.Tensor = src_w / 2
-
- start_x: torch.Tensor = src_h_half - dst_h_half
- start_y: torch.Tensor = src_w_half - dst_w_half
+ dst_h_half = dst_h / 2
+ dst_w_half = dst_w / 2
+ src_h_half = src_h / 2
+ src_w_half = src_w / 2
- end_x: torch.Tensor = start_x + dst_w - 1
- end_y: torch.Tensor = start_y + dst_h - 1
+ start_x = src_h_half - dst_h_half
+ start_y = src_w_half - dst_w_half
# [y, x] origin
# top-left, top-right, bottom-left, bottom-right
- points_src: torch.Tensor = torch.tensor([[
- [start_y, start_x],
- [start_y, end_x],
- [end_y, start_x],
- [end_y, end_x],
- ]]).to(tensor.device).to(tensor.dtype)
+ points_src: torch.Tensor = _get_perspective_src(start_x, start_y, size).to(tensor.device).to(tensor.dtype)
# [y, x] destination
# top-left, top-right, bottom-left, bottom-right
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0],
- [0, dst_w - 1],
- [dst_h - 1, 0],
- [dst_h - 1, dst_w - 1],
- ]]).to(tensor.device).to(tensor.dtype)
+ points_dst: torch.Tensor = _get_perspective_dst(size).to(tensor.device).to(tensor.dtype)
# warping needs data in the shape of BCHW
is_unbatched: bool = tensor.ndimension() == 3
if is_unbatched:
tensor = torch.unsqueeze(tensor, dim=0)
- # compute transformation between points and warp
- dst_trans_src: torch.Tensor = get_perspective_transform(
- points_src, points_dst)
- dst_trans_src = dst_trans_src.repeat(tensor.shape[0], 1, 1)
-
- patches: torch.Tensor = warp_perspective(
- tensor, dst_trans_src, (int(dst_h), int(dst_w)))
+ patches = _crop_wrapper(tensor, points_src, points_dst)
# return in the original shape
if is_unbatched:
patches = torch.squeeze(patches, dim=0)
return patches
+
+
+def _get_perspective_src(start_x: int, start_y: int, size: Tuple[int, int]) -> torch.Tensor:
+
+ end_x = start_x + size[1] - 1
+ end_y = start_y + size[0] - 1
+
+ # [y, x] origin
+ # top-left, top-right, bottom-left, bottom-right
+ return torch.tensor([[
+ [start_y, start_x],
+ [start_y, end_x],
+ [end_y, start_x],
+ [end_y, end_x],
+ ]])
+
+
+def _get_perspective_dst(size: Tuple[int, int]) -> torch.Tensor:
+ # [y, x] destination
+ # top-left, top-right, bottom-left, bottom-right
+ return torch.tensor([[
+ [0, 0],
+ [size[1] - 1, 0],
+ [size[1] - 1, size[0] - 1],
+ [0, size[0] - 1],
+ ]])
+
+
+def _crop_wrapper(input: torch.Tensor, src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:
+ dst_trans_src: torch.Tensor = get_perspective_transform(src, dst)
+ dst_trans_src = dst_trans_src.repeat(input.shape[0], 1, 1)
+
+ size = (int(dst.squeeze()[-1][-1] + 1), int(dst.squeeze()[1][0] + 1))
+
+ patches: torch.Tensor = warp_perspective(input, dst_trans_src, size)
+ return patches