Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Adds gradcheck for RandomCrop and RandomResizedCrop (#439)

shijianjiana42c5f7bbfc1
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index ac5af2a2e..c61edb0c2 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -412,22 +412,22 @@ class RandomRotation(AugmentationBase):
def __init__(self, degrees: FloatUnionType = 45.0, return_transform: bool = False) -> None:
super(RandomRotation, self).__init__(F._apply_rotation, return_transform)
self.degrees = degrees
- self._params: Dict[str, torch.Tensor] = {}
def __repr__(self) -> str:
repr = f"(degrees={self.degrees}, return_transform={self.return_transform})"
return self.__class__.__name__ + repr
- def set_params(self, batch_size: int, degrees: FloatUnionType):
- self._params = pg._random_rotation_gen(batch_size, degrees)
+ @staticmethod
+ def get_params(batch_size: int, degrees: FloatUnionType):
+ return pg._random_rotation_gen(batch_size, degrees)
def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
if params is None:
height, width = self.infer_image_shape(input)
batch_size: int = self.infer_batch_size(input)
- self.set_params(batch_size, self.degrees)
- return super().forward(input, self._params)
+ params = RandomRotation.get_params(batch_size, self.degrees)
+ return super().forward(input, params)
class RandomCrop(AugmentationBase):
@@ -452,7 +452,7 @@ class RandomCrop(AugmentationBase):
"""
def __init__(self, size: Tuple[int, int], padding: Optional[BoarderUnionType] = None,
- pad_if_needed: Optional[bool] = False, fill=0, padding_mode='constant',
+ pad_if_needed: Optional[bool] = False, fill: int = 0, padding_mode: str = 'constant',
return_transform: bool = False) -> None:
super(RandomCrop, self).__init__(F._apply_crop, return_transform)
self.size = size
@@ -498,11 +498,9 @@ class RandomCrop(AugmentationBase):
else:
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
+ params = RandomCrop.get_params(batch_size, (batch_shape[-2], batch_shape[-1]), self.size)
return super().forward(input, params)
@@ -539,7 +537,8 @@ class RandomResizedCrop(AugmentationBase):
) -> Dict[str, torch.Tensor]:
target_size = pg._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)
+ return pg._random_crop_gen(batch_size, input_size,
+ (int(target_size[0].data.item()), int(target_size[1].data.item())), resize_to=size)
def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
if params is None:
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index 124b550f7..7a8dc91a7 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -518,4 +518,11 @@ def _apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor], return_tra
is set to ``True``
"""
input = _transform_input(input)
- return crop_by_boxes(input, params['src'], params['dst'], return_transform=return_transform)
+ device = input.device
+ dtype = input.dtype
+ return crop_by_boxes(
+ input,
+ params['src'].to(device).to(dtype),
+ params['dst'].to(device).to(dtype),
+ return_transform=return_transform
+ )
diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.py
index 69e831a0a..d5d58df43 100644
--- a/kornia/augmentation/param_gen.py
+++ b/kornia/augmentation/param_gen.py
@@ -343,26 +343,28 @@ def _random_crop_gen(batch_size: int, input_size: Tuple[int, int], size: Tuple[i
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 1 < w < size[0] and 1 < h < size[1]:
- return (h, w)
+def _random_crop_size_gen(size: Tuple[int, int], scale: Tuple[float, float],
+ ratio: Tuple[float, float]) -> Tuple[torch.Tensor, torch.Tensor]:
+ area = Uniform(scale[0] * size[0] * size[1], scale[1] * size[0] * size[1]).rsample((10,))
+ log_ratio = Uniform(math.log(ratio[0]), math.log(ratio[1])).rsample((10,))
+ 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 (h[torch.argmax(cond)], w[torch.argmax(cond)])
# 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)))
+ w = torch.tensor(size[0])
+ h = torch.round(w / min(ratio))
elif (in_ratio > max(ratio)):
- h = size[1]
- w = int(round(h * max(ratio)))
+ h = torch.tensor(size[1])
+ w = torch.round(h * max(ratio))
else: # whole image
- w = size[0]
- h = size[1]
+ w = torch.tensor(size[0])
+ h = torch.tensor(size[1])
return (h, w)
diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.py
index 3fb7b693f..df622d236 100644
--- a/kornia/geometry/transform/crop.py
+++ b/kornia/geometry/transform/crop.py
@@ -167,8 +167,9 @@ def crop_by_boxes(tensor, src_box, dst_box,
# simulate broadcasting
dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1)
+ bbox = _infer_bounding_box(dst_box)
patches: torch.Tensor = warp_perspective(
- tensor, dst_trans_src, _infer_bounding_box(dst_box))
+ tensor, dst_trans_src, (int(bbox[0].int().data.item()), int(bbox[1].int().data.item())))
# return in the original shape
if is_unbatched:
@@ -180,7 +181,7 @@ def crop_by_boxes(tensor, src_box, dst_box,
return patches
-def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[int, int]:
+def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Auto-infer the output sizes.
Args:
@@ -191,7 +192,7 @@ def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[int, int]:
coordinates must be in the x, y order.
Returns:
- torch.Tensor: tensor containing the patches with shape BxN1xN2
+ (torch.Tensor, torch.Tensor): tensor containing the patches with shape BxN1xN2
Example:
>>> boxes = torch.tensor([[
@@ -203,10 +204,10 @@ def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[int, int]:
>>> _infer_bounding_box(boxes)
(2, 2)
"""
- assert (boxes[:, 1, 0] - boxes[:, 0, 0] + 1).equal(boxes[:, 2, 0] - boxes[:, 3, 0] + 1), \
+ assert torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)), \
"Boxes must have be square, while get widths %s and %s" % \
(str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1))
- assert (boxes[:, 2, 1] - boxes[:, 0, 1] + 1).equal(boxes[:, 3, 1] - boxes[:, 1, 1] + 1), \
+ assert torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)), \
"Boxes must have be square, while get heights %s and %s" % \
(str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1))
assert len((boxes[:, 1, 0] - boxes[:, 0, 0] + 1).unique()) == 1, \
@@ -214,6 +215,6 @@ def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[int, int]:
assert len((boxes[:, 2, 1] - boxes[:, 0, 1] + 1).unique()) == 1, \
"Boxes can only have one heights, got %s" % str((boxes[:, 2, 1] - boxes[:, 0, 1] + 1).unique())
- width = int((boxes[:, 1, 0] - boxes[:, 0, 0] + 1).unique().data.item())
- height = int((boxes[:, 2, 1] - boxes[:, 0, 1] + 1).unique().data.item())
+ width: torch.Tensor = (boxes[:, 1, 0] - boxes[:, 0, 0] + 1)[0]
+ height: torch.Tensor = (boxes[:, 2, 1] - boxes[:, 0, 1] + 1)[0]
return (height, width)
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index d212f2cae..005a19b66 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1383,6 +1383,12 @@ class TestRandomCrop:
assert_allclose(out, expected)
+ def test_gradcheck(self, device):
+ torch.manual_seed(0) # for random reproductibility
+ inp = torch.rand((3, 3, 3)).to(device) # 3 x 3
+ inp = utils.tensor_to_gradcheck_var(inp) # to var
+ assert gradcheck(RandomCrop(size=(3, 3)), (inp, ), raise_exception=True)
+
class TestRandomResizedCrop:
def smoke_test(self, device):
@@ -1400,8 +1406,8 @@ class TestRandomResizedCrop:
]]).to(device)
expected = torch.tensor([[[
- [3.0000, 3.5000, 4.0000],
- [6.0000, 6.5000, 7.0000]
+ [4.0000, 4.5000, 5.0000],
+ [7.0000, 7.5000, 8.0000]
]]]).to(device)
rrc = RandomResizedCrop(size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
@@ -1439,8 +1445,18 @@ class TestRandomResizedCrop:
[0., 1., 2.],
[1.5, 2.5, 3.5],
[3., 4., 5.],
- ]]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], [[
+ [3., 4., 5.],
+ [4.5, 5.5, 6.5],
+ [6., 7., 8.],
+ ]]]).to(device)
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_gradcheck(self, device):
+ torch.manual_seed(0) # for random reproductibility
+ inp = torch.rand((1, 3, 3)).to(device) # 3 x 3
+ inp = utils.tensor_to_gradcheck_var(inp) # to var
+ assert gradcheck(RandomResizedCrop(size=(3, 3), scale=(1., 1.), ratio=(1., 1.)), (inp, ), raise_exception=True)
diff --git a/test/geometry/transform/test_crop.py b/test/geometry/transform/test_crop.py
index 2e8019218..be8482669 100644
--- a/test/geometry/transform/test_crop.py
+++ b/test/geometry/transform/test_crop.py
@@ -18,7 +18,7 @@ class TestBoundingBoxInferring:
[3., 1.],
[3., 2.],
[1., 2.],
- ]])
+ ]]).to(device)
expected_height = 2
expected_width = 3
h, w = kornia.geometry.transform.crop._infer_bounding_box(boxes)
@@ -35,12 +35,23 @@ class TestBoundingBoxInferring:
[4., 2.],
[4., 3.],
[2., 3.],
- ]])
+ ]]).to(device)
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_gradcheck(self, device):
+ boxes = torch.tensor([[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ]]).to(device)
+ boxes = utils.tensor_to_gradcheck_var(boxes)
+ assert gradcheck(kornia.kornia.geometry.transform.crop._infer_bounding_box,
+ (boxes,), raise_exception=True)
+
class TestCropAndResize:
def test_crop(self, device):
@@ -295,3 +306,84 @@ class TestCenterCrop:
img, (torch.tensor(crop_height), torch.tensor(crop_width)))
expected = kornia.center_crop(img, (crop_height, crop_width))
assert_allclose(actual, expected)
+
+
+class TestCropByBoxes:
+ def test_crop_by_boxes_no_resizing(self, device):
+ inp = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]).to(device)
+
+ src = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]]).to(device) # 1x4x2
+
+ dst = torch.tensor([[
+ [0., 0.],
+ [1., 0.],
+ [1., 1.],
+ [0., 1.],
+ ]]).to(device) # 1x4x2
+
+ expected = torch.tensor([[
+ [6., 7.],
+ [10., 11.],
+ ]]).to(device)
+
+ patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
+ assert_allclose(patches, expected)
+
+ def test_crop_by_boxes_resizing(self, device):
+ inp = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]).to(device)
+
+ src = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]]).to(device) # 1x4x2
+
+ dst = torch.tensor([[
+ [0., 0.],
+ [2., 0.],
+ [2., 1.],
+ [0., 1.],
+ ]]).to(device) # 1x4x2
+
+ expected = torch.tensor([[
+ [6., 6.5, 7.],
+ [10., 10.5, 11.],
+ ]]).to(device)
+
+ patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
+ assert_allclose(patches, expected)
+
+ def test_gradcheck(self, device):
+ inp = torch.randn((1, 3, 3)).to(device)
+ src = torch.tensor([[
+ [1., 0.],
+ [2., 0.],
+ [2., 1.],
+ [1., 1.]]]).to(device)
+ dst = torch.tensor([[
+ [0., 0.],
+ [1., 0.],
+ [1., 1.],
+ [0., 1.]]]).to(device)
+
+ inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
+
+ assert gradcheck(kornia.geometry.transform.crop_by_boxes,
+ (inp, src, dst,),
+ raise_exception=True)