Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Enabled RandomResizedCrop batch mode when same_on_batch=False (#683)

shijianjian13f7ce28734a
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index ce48d9fbf..b96071e72 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -1,6 +1,7 @@
from typing import Callable, Tuple, Union, List, Optional, Dict, cast
import torch
+import torch.nn as nn
from torch.nn.functional import pad
from kornia.constants import Resample, BorderType, SamplePadding
@@ -236,7 +237,7 @@ class RandomErasing(AugmentationBase2D):
Examples:
>>> rng = torch.manual_seed(0)
>>> inputs = torch.ones(1, 1, 3, 3)
- >>> rec_er = RandomErasing(0.5, (.4, .8), (.3, 1/.3))
+ >>> rec_er = RandomErasing((.4, .8), (.3, 1/.3), p=0.5)
>>> rec_er(inputs)
tensor([[[[1., 0., 0.],
[1., 0., 0.],
@@ -687,9 +688,9 @@ class RandomResizedCrop(AugmentationBase2D):
... [6., 7., 8.]]])
>>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1.)
>>> aug(inputs)
- tensor([[[[3.7500, 4.7500, 5.7500],
- [5.2500, 6.2500, 7.2500],
- [4.5000, 5.2500, 6.0000]]]])
+ tensor([[[[1.2500, 1.7500, 1.5000],
+ [4.2500, 4.7500, 3.7500],
+ [7.2500, 7.7500, 6.0000]]]])
"""
def __init__(
@@ -724,7 +725,7 @@ class RandomResizedCrop(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
target_size: torch.Tensor = rg.random_crop_size_generator(
- self.size, self.scale, self.ratio, same_on_batch=self.same_on_batch)['size']
+ batch_shape[0], self.size, self.scale, self.ratio, same_on_batch=self.same_on_batch)['size']
return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), target_size,
resize_to=self.size, same_on_batch=self.same_on_batch)
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index 37b9f7e7c..0944b3ca1 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -1,11 +1,11 @@
from typing import Tuple, List, Union, Dict, Optional, cast
import random
-import math
import torch
from torch.distributions import Bernoulli
from kornia.constants import Resample, BorderType, SamplePadding
+from kornia.geometry import bbox_generator
from ..utils import (
_adapted_sampling,
_adapted_uniform,
@@ -243,35 +243,75 @@ def random_crop_generator(
batch_size (int): the tensor batch size.
input_size (tuple): Input image shape, like (h, w).
size (tuple): Desired size of the crop operation, like (h, w).
+ If tensor, it must be (B, 2).
resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+
+ Example:
+ >>> _ = torch.manual_seed(0)
+ >>> crop_size = random_crop_size_generator(
+ ... 3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))['size']
+ >>> crop_size
+ tensor([[26, 29],
+ [27, 28],
+ [25, 28]], dtype=torch.int32)
+ >>> random_crop_generator(3, (30, 30), size=crop_size, same_on_batch=False)
+ {'src': tensor([[[ 1, 3],
+ [29, 3],
+ [29, 28],
+ [ 1, 28]],
+ <BLANKLINE>
+ [[ 2, 3],
+ [29, 3],
+ [29, 29],
+ [ 2, 29]],
+ <BLANKLINE>
+ [[ 0, 2],
+ [27, 2],
+ [27, 26],
+ [ 0, 26]]]), 'dst': tensor([[[ 0, 0],
+ [28, 0],
+ [28, 25],
+ [ 0, 25]],
+ <BLANKLINE>
+ [[ 0, 0],
+ [27, 0],
+ [27, 26],
+ [ 0, 26]],
+ <BLANKLINE>
+ [[ 0, 0],
+ [27, 0],
+ [27, 24],
+ [ 0, 24]]])}
"""
- x_diff = input_size[1] - size[1]
- y_diff = input_size[0] - size[0]
+ if not isinstance(size, torch.Tensor):
+ size = torch.tensor(size).repeat(batch_size, 1)
+ assert size.shape == torch.Size([batch_size, 2]), \
+ f"If `size` is a tensor, it must be shaped as (B, 2). Got {size.shape}."
+
+ x_diff = input_size[1] - size[:, 1] + 1
+ y_diff = input_size[0] - size[:, 0] + 1
- if x_diff < 0 or y_diff < 0:
+ if (x_diff < 0).any() or (y_diff < 0).any():
raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."
% (str(input_size), str(size)))
- x_start = _adapted_uniform((batch_size,), 0, x_diff + 1, same_on_batch).long()
- y_start = _adapted_uniform((batch_size,), 0, y_diff + 1, same_on_batch).long()
-
- crop = torch.tensor([[
- [0, 0],
- [size[1] - 1, 0],
- [size[1] - 1, size[0] - 1],
- [0, size[0] - 1],
- ]]).repeat(batch_size, 1, 1)
+ if same_on_batch:
+ # If same_on_batch, select the first then repeat.
+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch).long()
+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch).long()
+ else:
+ x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch).long()
+ y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch).long()
- 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)
+ crop_src = bbox_generator(x_start.view(-1), y_start.view(-1), size[:, 1] - 1, size[:, 0] - 1)
if resize_to is None:
- crop_dst = crop
+ crop_dst = bbox_generator(
+ torch.tensor([0] * batch_size), torch.tensor([0] * batch_size), size[:, 1] - 1, size[:, 0] - 1)
else:
crop_dst = torch.tensor([[
[0, 0],
@@ -285,6 +325,7 @@ def random_crop_generator(
def random_crop_size_generator(
+ batch_size: int,
size: Tuple[int, int],
scale: torch.Tensor,
ratio: torch.Tensor,
@@ -293,43 +334,60 @@ def random_crop_size_generator(
r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
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
+ batch_size (int): the tensor batch size.
+ size (Tuple[int, int]): expected output size of each edge.
+ scale (tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+
+ Examples:
+ >>> _ = torch.manual_seed(0)
+ >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
+ {'size': tensor([[26, 29],
+ [27, 28],
+ [25, 28]], dtype=torch.int32)}
"""
_joint_range_check(scale, "scale")
_joint_range_check(ratio, "ratio")
+ # 10 trails for each element
area = _adapted_uniform(
- (10,), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
+ (batch_size, 10), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
log_ratio = _adapted_uniform(
- (10,), math.log(ratio[0]), math.log(ratio[1]), same_on_batch)
+ (batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)
aspect_ratio = torch.exp(log_ratio)
w = torch.sqrt(area * aspect_ratio).int()
h = torch.sqrt(area / aspect_ratio).int()
-
# Element-wise w, h condition
cond = ((0 < h) * (h < size[1]) * (0 < w) * (w < size[0])).int()
- if torch.sum(cond) > 0:
- return dict(size=torch.stack([h[torch.argmax(cond)], w[torch.argmax(cond)]], dim=0))
-
- # Fallback to center crop
- in_ratio = float(size[0]) / float(size[1])
- if (in_ratio < min(ratio)):
- w = torch.tensor(size[0])
- h = torch.round(w / min(ratio))
- elif (in_ratio > max(ratio)):
- h = torch.tensor(size[1])
- w = torch.round(h * max(ratio))
- else: # whole image
- w = torch.tensor(size[0])
- h = torch.tensor(size[1])
- return dict(size=torch.stack([h.long(), w.long()]))
+ cond_bool = torch.sum(cond, dim=1) > 0
+
+ w_out = w[torch.arange(0, batch_size), torch.argmax(cond, dim=1)]
+ h_out = h[torch.arange(0, batch_size), torch.argmax(cond, dim=1)]
+
+ if not cond_bool.all():
+ # Fallback to center crop
+ in_ratio = float(size[0]) / float(size[1])
+ if (in_ratio < min(ratio)):
+ w_ct = torch.tensor(size[0])
+ h_ct = torch.round(w_ct / min(ratio))
+ elif (in_ratio > max(ratio)):
+ h_ct = torch.tensor(size[1])
+ w_ct = torch.round(h_ct * max(ratio))
+ else: # whole image
+ w_ct = torch.tensor(size[0])
+ h_ct = torch.tensor(size[1])
+ w_ct = w_ct.int()
+ h_ct = h_ct.int()
+
+ w_out = w_out.where(cond_bool, w_ct)
+ h_out = h_out.where(cond_bool, h_ct)
+
+ return dict(size=torch.stack([w_out, h_out], dim=1))
def random_rectangles_params_generator(
@@ -696,8 +754,8 @@ def random_cutmix_generator(
cutmix_betas = torch.min(torch.max(cutmix_betas, cut_size[0]), cut_size[1])
cutmix_rate = torch.sqrt(1. - cutmix_betas) * batch_probs
- cut_height = (cutmix_rate * height).long()
- cut_width = (cutmix_rate * width).long()
+ cut_height = (cutmix_rate * height).long() - 1
+ cut_width = (cutmix_rate * width).long() - 1
_gen_shape = (1,)
if same_on_batch:
@@ -705,25 +763,13 @@ def random_cutmix_generator(
cut_height = cut_height[0]
cut_width = cut_width[0]
+ # Reserve at least 1 pixel for cropping.
x_start = _adapted_uniform(
- _gen_shape, torch.zeros_like(cut_width, dtype=torch.float32), width - cut_width, same_on_batch).long()
+ _gen_shape, torch.zeros_like(cut_width, dtype=torch.float32), width - cut_width - 1, same_on_batch).long()
y_start = _adapted_uniform(
- _gen_shape, torch.zeros_like(cut_height, dtype=torch.float32), height - cut_height, same_on_batch).long()
+ _gen_shape, torch.zeros_like(cut_height, dtype=torch.float32), height - cut_height - 1, same_on_batch).long()
- bbox = torch.tensor([[
- [0, 0],
- [0, 0],
- [0, 0],
- [0, 0],
- ]]).repeat(batch_size * num_mix, 1, 1)
-
- crop_src = bbox.clone()
- crop_src[:, :, 0] += x_start.view(-1, 1)
- crop_src[:, :, 1] += y_start.view(-1, 1)
- crop_src[:, 1, 0] += cut_width - 1
- crop_src[:, 2, 0] += cut_width - 1
- crop_src[:, 2, 1] += cut_height - 1
- crop_src[:, 3, 1] += cut_height - 1
+ crop_src = bbox_generator(x_start.squeeze(), y_start.squeeze(), cut_width, cut_height)
# (B * num_mix, 4, 2) => (num_mix, batch_size, 4, 2)
crop_src = crop_src.view(num_mix, batch_size, 4, 2)
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 43c0f4836..175a41cbb 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -122,7 +122,7 @@ def _adapted_rsampling(
By default, same_on_batch is set to False.
"""
if same_on_batch:
- return dist.rsample((1, *shape[1:])).repeat(shape[0])
+ return dist.rsample((1, *shape[1:])).repeat(shape[0], *[1] * (len(shape) - 1))
else:
return dist.rsample(shape)
diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.py
index 233aac7ee..7a0865e06 100644
--- a/kornia/geometry/transform/crop.py
+++ b/kornia/geometry/transform/crop.py
@@ -13,6 +13,7 @@ __all__ = [
"bbox_to_mask",
"infer_box_shape",
"validate_bboxes",
+ "bbox_generator"
]
@@ -335,3 +336,59 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
mask_out.append(m_out)
return torch.stack(mask_out, dim=0).float()
+
+
+def bbox_generator(
+ x_start: torch.Tensor, y_start: torch.Tensor, width: torch.Tensor, height: torch.Tensor
+) -> torch.Tensor:
+ """Generate bounding boxes according to the provided start coords, width and height.
+
+ Args:
+ x_start (torch.Tensor): a tensor containing the x coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ y_start (torch.Tensor): a tensor containing the y coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ width (torch.Tensor): widths of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ height (torch.Tensor): heights of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+
+ Returns:
+ torch.Tensor: the bounding box tensor.
+
+ Examples:
+ >>> x_start = torch.tensor([0, 1])
+ >>> y_start = torch.tensor([1, 0])
+ >>> width = torch.tensor([5, 3])
+ >>> height = torch.tensor([7, 4])
+ >>> bbox_generator(x_start, y_start, width, height)
+ tensor([[[0, 1],
+ [4, 1],
+ [4, 7],
+ [0, 7]],
+ <BLANKLINE>
+ [[1, 0],
+ [3, 0],
+ [3, 3],
+ [1, 3]]])
+ """
+ assert x_start.shape == y_start.shape and x_start.dim() in [0, 1], \
+ f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."
+ assert width.shape == height.shape and width.dim() in [0, 1], \
+ f"`width` and `height` must be a scalar or (B,). Got {width}, {height}."
+
+ bbox = torch.tensor([[
+ [0, 0],
+ [0, 0],
+ [0, 0],
+ [0, 0],
+ ]]).repeat(len(x_start), 1, 1)
+
+ bbox[:, :, 0] += x_start.view(-1, 1)
+ bbox[:, :, 1] += y_start.view(-1, 1)
+ bbox[:, 1, 0] += width
+ bbox[:, 2, 0] += width
+ bbox[:, 2, 1] += height
+ bbox[:, 3, 1] += height
+
+ return bbox
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index a34d48d63..d3981734d 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1488,44 +1488,44 @@ class TestRandomResizedCrop:
res = f(input)
assert (res[0] == res[1]).all()
- def test_crop_scale_ratio(self, device):
+ def test_crop_scale_ratio(self, device, dtype):
# This is included in doctest
torch.manual_seed(0)
inp = torch.tensor([[
[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]
- ]]).to(device)
+ ]], device=device, dtype=dtype)
expected = torch.tensor(
- [[[[3.7500, 4.7500, 5.7500],
- [5.2500, 6.2500, 7.2500],
- [4.5000, 5.2500, 6.0000]]]]).to(device)
+ [[[[1.2500, 1.7500, 1.5000],
+ [4.2500, 4.7500, 3.7500],
+ [7.2500, 7.7500, 6.0000]]]], device=device, dtype=dtype)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
assert_allclose(out, expected)
- def test_crop_scale_ratio_batch(self, device):
+ def test_crop_scale_ratio_batch(self, device, dtype):
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).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch. tensor(
- [[[[0.0000, 0.7500, 1.5000],
- [0.7500, 1.7500, 2.7500],
- [2.2500, 3.2500, 4.2500]]],
- [[[3.7500, 4.7500, 5.7500],
- [5.2500, 6.2500, 7.2500],
- [4.5000, 5.2500, 6.0000]]]]).to(device)
+ [[[[1.2500, 1.7500, 1.5000],
+ [4.2500, 4.7500, 3.7500],
+ [7.2500, 7.7500, 6.0000]]],
+ [[[0.0000, 0.2500, 0.7500],
+ [2.2500, 3.2500, 3.7500],
+ [4.5000, 6.2500, 6.7500]]]], device=device, dtype=dtype)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
- assert_allclose(out, expected)
+ assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility