Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Added tests for RandomCrop

Jian S169a400e0327
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 73799a9d9..c330f109e 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -482,26 +482,27 @@ class RandomCrop(AugmentationBase):
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]
+ if self.pad_if_needed and input.shape[-2] < self.size[0]:
+ padding = [0, 0, (self.size[0] - input.shape[-2]), self.size[0] - input.shape[-2]]
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]]
+ if self.pad_if_needed and input.shape[-1] < self.size[1]:
+ padding = [self.size[1] - input.shape[-1], self.size[1] - input.shape[-1], 0, 0]
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]))
+ batch_shape = input[0].shape
else:
- batch_shape = input.shape
input = self.precrop_padding(input)
+ batch_shape = input.shape
if params is None:
batch_size = self.infer_batch_size(input)
+ print(batch_shape)
params = RandomCrop.get_params(batch_size, batch_shape[-2:], self.size) # type: ignore
return super().forward(input, params)
@@ -535,35 +536,10 @@ class RandomResizedCrop(AugmentationBase):
@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)
+ target_size = pd._random_crop_size_gen(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)
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index 45a63f85f..004147177 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -475,8 +475,6 @@ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor], return_
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated
"""
- src = params['src'].to(input.device).to(input.dtype)
- dst = params['dst'].to(input.device).to(input.dtype)
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.py
index fdecbb6e6..ad28468ee 100644
--- a/kornia/augmentation/param_gen.py
+++ b/kornia/augmentation/param_gen.py
@@ -315,17 +315,17 @@ def _random_crop_gen(batch_size: int, input_size: Tuple[int, int], size: Tuple[i
raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."
% (str(input_size), str(size)))
- x_start = Uniform(0, x_diff).rsample((batch_size,)).long()
- y_start = Uniform(0, y_diff).rsample((batch_size,)).long()
+ x_start = Uniform(0, x_diff + 1).rsample((batch_size,)).long()
+ y_start = Uniform(0, y_diff + 1).rsample((batch_size,)).long()
crop = torch.tensor([[
[0, 0],
- [0, size[1]],
- [size[0], 0],
- [size[0], size[1]]
+ [size[1] - 1, 0],
+ [size[1] - 1, size[0] - 1],
+ [0, size[0] - 1],
]]).repeat(batch_size, 1, 1)
- crop_src = crop.detach()
+ crop_src = crop.clone()
crop_src[:, :, 0] += x_start.unsqueeze(dim=0).reshape(batch_size, 1)
crop_src[:, :, 1] += y_start.unsqueeze(dim=0).reshape(batch_size, 1)
@@ -334,9 +334,34 @@ def _random_crop_gen(batch_size: int, input_size: Tuple[int, int], size: Tuple[i
else:
crop_dst = torch.tensor([[
[0, 0],
- [0, resize_to[1]],
- [resize_to[0], 0],
- [resize_to[0], resize_to[1]]
+ [resize_to[1] - 1, 0],
+ [resize_to[1] - 1, resize_to[0] - 1],
+ [0, resize_to[0] - 1],
]]).repeat(batch_size, 1, 1)
return {'src': crop_src, 'dst': crop_dst}
+
+
+def _random_crop_size_gen(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)
diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.py
index 5393b310f..3fb7b693f 100644
--- a/kornia/geometry/transform/crop.py
+++ b/kornia/geometry/transform/crop.py
@@ -73,7 +73,7 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
[0, dst_h - 1],
]]).repeat(points_src.shape[0], 1, 1)
- return crop_by_boxes(tensor, points_src, points_dst)
+ return crop_by_boxes(tensor, points_src, points_dst, return_transform=return_transform)
def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 802de454d..9d7f9837e 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -8,7 +8,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
from kornia.augmentation import RandomHorizontalFlip, RandomVerticalFlip, ColorJitter, \
- RandomRectangleErasing, RandomGrayscale, RandomRotation
+ RandomRectangleErasing, RandomGrayscale, RandomRotation, RandomCrop
from kornia.augmentation.erasing import get_random_rectangles_params, erase_rectangles
from test.common import device
@@ -1263,3 +1263,113 @@ class TestRandomRotation:
input = torch.rand((3, 3)).to(device) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(RandomRotation(degrees=(15.0, 15.0)), (input, ), raise_exception=True)
+
+
+class TestRandomCrop:
+ def test_no_padding(self, device):
+ torch.manual_seed(0)
+ inp = torch.tensor([[[
+ [0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]
+ ]]])
+ expected = torch.tensor([[[
+ [3., 4., 5.],
+ [6., 7., 8.]
+ ]]])
+ rc = RandomCrop(size=(2, 3), padding=None)
+ out = rc(inp)
+
+ assert_allclose(out, expected)
+
+ def test_no_padding_batch(self, device):
+ torch.manual_seed(0)
+ batch_size = 2
+ inp = torch.tensor([[
+ [0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]
+ ]]).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor([[
+ [0., 1., 2.],
+ [3., 4., 5.],
+ ]]).repeat(batch_size, 1, 1, 1)
+ rc = RandomCrop(size=(2, 3), padding=None)
+ out = rc(inp)
+
+ assert_allclose(out, expected)
+
+ def test_padding_batch_1(self, device):
+ torch.manual_seed(0)
+ batch_size = 2
+ inp = torch.tensor([[
+ [0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]
+ ]]).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor([[[
+ [0., 0., 0.],
+ [0., 1., 2.]
+ ]], [[
+ [0., 0., 0.],
+ [1., 2., 0.]
+ ]]])
+ rc = RandomCrop(size=(2, 3), padding=1)
+ out = rc(inp)
+
+ assert_allclose(out, expected)
+
+ def test_padding_batch_2(self, device):
+ torch.manual_seed(0)
+ batch_size = 2
+ inp = torch.tensor([[
+ [0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]
+ ]]).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor([[[
+ [0., 1., 2.],
+ [3., 4., 5.]
+ ]], [[
+ [1., 2., 10.],
+ [4., 5., 10.]
+ ]]])
+ rc = RandomCrop(size=(2, 3), padding=(0, 1), fill=10)
+ out = rc(inp)
+
+ assert_allclose(out, expected)
+
+ def test_padding_batch_3(self, device):
+ torch.manual_seed(0)
+ batch_size = 2
+ inp = torch.tensor([[
+ [0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]
+ ]]).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor([[[
+ [8., 8., 8.],
+ [8., 0., 1.]
+ ]], [[
+ [8., 8., 8.],
+ [1., 2., 8.]
+ ]]])
+ rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8)
+ out = rc(inp)
+
+ assert_allclose(out, expected)
+
+ def test_pad_if_needed(self, device):
+ torch.manual_seed(0)
+ batch_size = 2
+ inp = torch.tensor([[
+ [0., 1., 2.],
+ ]]).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor([[
+ [9., 9., 9.],
+ [0., 1., 2.]
+ ]]).repeat(batch_size, 1, 1, 1)
+ rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9)
+ out = rc(inp)
+
+ assert_allclose(out, expected)
diff --git a/test/geometry/transform/test_crop.py b/test/geometry/transform/test_crop.py
index a6d7d90e3..2e8019218 100644
--- a/test/geometry/transform/test_crop.py
+++ b/test/geometry/transform/test_crop.py
@@ -11,6 +11,37 @@ from torch.testing import assert_allclose
from torch.autograd import gradcheck
+class TestBoundingBoxInferring:
+ def test_bounding_boxes_dim_inferring(self, device):
+ boxes = torch.tensor([[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ]])
+ expected_height = 2
+ expected_width = 3
+ h, w = kornia.geometry.transform.crop._infer_bounding_box(boxes)
+ assert (h, w) == (expected_height, expected_width)
+
+ def test_bounding_boxes_dim_inferring_batch(self, device):
+ boxes = torch.tensor([[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ], [
+ [2., 2.],
+ [4., 2.],
+ [4., 3.],
+ [2., 3.],
+ ]])
+ expected_height = 2
+ expected_width = 3
+ h, w = kornia.geometry.transform.crop._infer_bounding_box(boxes)
+ assert (h, w) == (expected_height, expected_width)
+
+
class TestCropAndResize:
def test_crop(self, device):
inp = torch.tensor([[