Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): build the 2D crop matrix as a translation (#4753)

Rızgar Ozan7d65f05eca4b
diff --git a/changelog.d/4753.fixed.md b/changelog.d/4753.fixed.md
new file mode 100644
index 000000000..caf33fead
--- /dev/null
+++ b/changelog.d/4753.fixed.md
@@ -0,0 +1 @@
+`CenterCrop`, `RandomCrop`, `center_crop` and `CenterCrop2D` now accept a crop with a size-1 axis. The crop matrix is built as the translation it is, instead of being solved from the box vertices, which returned a matrix of `NaN` because those vertices are collinear. For every other crop the matrix is now the exact translation rather than the solver's approximation of it, so `transform_matrix`, transformed boxes and keypoints, and resampled pixels can differ from before in the last bits in float32, and by more in bfloat16, where the solve was inexact for coordinates above 256.
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 9358148c5..b79fadd0b 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -22,7 +22,8 @@ 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
+from kornia.geometry.transform import crop_by_transform_mat
+from kornia.geometry.transform.crop2d import _crop_translation
class CenterCrop(GeometricAugmentationBase2D):
@@ -127,7 +128,7 @@ class CenterCrop(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
if flags["cropping_mode"] in ("resample", "slice"):
- transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ transform = _crop_translation(params["src"].to(input), params["dst"].to(input))
return transform.expand(input.shape[0], -1, -1)
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 275624859..ff39c60fe 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -29,7 +29,8 @@ from kornia.constants import Resample
from kornia.core.utils import is_compiling, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
-from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
+from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat
+from kornia.geometry.transform.crop2d import _crop_translation
class RandomCrop(GeometricAugmentationBase2D):
@@ -213,7 +214,7 @@ class RandomCrop(GeometricAugmentationBase2D):
if flags["cropping_mode"] in ("resample", "slice"):
src = params["src"].to(input)
dst = params["dst"].to(input)
- transform: torch.Tensor = get_perspective_transform(src, dst)
+ transform = _crop_translation(src, dst)
# Scale against the canvas represented by the effective replay parameters.
# During export, retain the static-shape path rather than reading padding_size back to host.
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 240fc2f9a..d7401f3cb 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -125,6 +125,17 @@ def crop_and_resize(
)
+def _crop_translation(src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:
+ """Return the matrix of a crop, which only moves the first ``src`` vertex onto the first ``dst`` vertex.
+
+ Solving the perspective system from the four vertices instead fails for a crop with a size-1 axis, whose
+ vertices are collinear (#4751).
+ """
+ transform = torch.eye(3, device=src.device, dtype=src.dtype).repeat(src.shape[0], 1, 1)
+ transform[:, :2, 2] = dst[:, 0] - src[:, 0]
+ return transform
+
+
def center_crop(
input_tensor: torch.Tensor,
size: Tuple[int, int],
@@ -206,8 +217,10 @@ def center_crop(
dtype=input_tensor.dtype,
).expand(points_src.shape[0], -1, -1)
- return _crop_by_boxes_to_size(
- input_tensor, points_src, points_dst, (dst_h, dst_w), mode, padding_mode, align_corners
+ transform = _crop_translation(points_src, points_dst)
+
+ return crop_by_transform_mat(
+ input_tensor, transform, (dst_h, dst_w), mode=mode, padding_mode=padding_mode, align_corners=align_corners
)
@@ -301,9 +314,9 @@ def _crop_by_boxes_to_size(
padding_mode: str = "zeros",
align_corners: bool = False,
) -> torch.Tensor:
- # ``crop_by_boxes`` with the output size already known as Python ints. ``crop_and_resize`` and
- # ``center_crop`` build ``dst_box`` from ``size``, so they take this path and never read the box
- # values back from the device -- which also keeps them capturable by ``torch.onnx.export``.
+ # ``crop_by_boxes`` with the output size already known as Python ints. ``crop_and_resize`` builds
+ # ``dst_box`` from ``size``, so it takes this path and never reads the box values back from the
+ # device -- which also keeps it capturable by ``torch.onnx.export``.
if len(input_tensor.shape) != 4:
raise AssertionError(f"Only torch.Tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
@@ -626,7 +639,7 @@ class CenterCrop2D(nn.Module):
self.points_src[0, 3, 1] = end_y
if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- transform = get_perspective_transform(
+ transform = _crop_translation(
self.points_src.expand(batch_size, -1, -1).to(input),
self.points_dst.expand(batch_size, -1, -1).to(input),
)
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 6844fe5e0..ec88684ad 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -22,7 +22,7 @@ import torch
import kornia.augmentation as K
-from testing.base import BaseTester, supports_2d_border_padding
+from testing.base import BaseTester, supports_2d_border_padding, supports_bilinear_2d_grid_sample
class TestGeometricCropConventions(BaseTester):
@@ -45,6 +45,21 @@ class TestGeometricCropConventions(BaseTester):
nearest = K.CenterCrop((4, 4), resample="nearest", align_corners=False, cropping_mode="resample")
self.assert_close(nearest(x), expected)
+ @pytest.mark.parametrize("size", [(1, 3), (3, 1), (1, 1)])
+ def test_convention_crop2d_accepts_a_size_one_axis_4751(self, size, device, dtype):
+ # A crop is a translation. Solving the perspective system from the box vertices instead returned a
+ # matrix of NaNs here, because a size-1 axis makes the vertices collinear.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ x = torch.arange(20, device=device, dtype=dtype).reshape(1, 1, 4, 5)
+ for augmentation in (
+ K.CenterCrop(size, cropping_mode="resample", p=1.0),
+ K.RandomCrop(size, cropping_mode="resample", p=1.0),
+ ):
+ output = augmentation(x)
+ left, top = augmentation._params["src"][0, 0].long().tolist()
+ self.assert_close(output, x[..., top : top + size[0], left : left + size[1]])
+
@pytest.mark.parametrize("size", [(4, 4), (4, 8), (6, 8)])
def test_convention_center_crop_slice_returns_a_copy_4413(self, device, dtype, size):
# #4413: default slice mode used to return a view, so writing to the output changed the input.
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index d86b3020d..bcc952ec7 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -20,7 +20,7 @@ import torch
import kornia
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_bilinear_2d_grid_sample
class TestCropAndResize(BaseTester):
@@ -304,6 +304,53 @@ class TestCenterCrop(BaseTester):
# and both agree with the plain integer-index slice of the same region
self.assert_close(out_resample_false, inp[:, :, 1:3, 1:3], atol=1e-4, rtol=1e-4)
+ @pytest.mark.parametrize("size", [(1, 3), (3, 1), (1, 1)])
+ def test_convention_center_crop_accepts_a_size_one_axis_4751(self, size, device, dtype):
+ # A crop is a translation. Solving the perspective system from the box vertices instead returned a
+ # matrix of NaNs here, because a size-1 axis makes the vertices collinear.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.arange(25.0, device=device, dtype=dtype).view(1, 1, 5, 5)
+ top, left = (5 - size[0]) // 2, (5 - size[1]) // 2
+ expected = inp[..., top : top + size[0], left : left + size[1]]
+
+ self.assert_close(kornia.geometry.transform.center_crop(inp, size), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(
+ kornia.geometry.transform.CenterCrop2D(size, cropping_mode="resample")(inp), expected, atol=1e-4, rtol=1e-4
+ )
+
+ def test_center_crop_forwards_mode_padding_mode_and_align_corners(self, device, dtype):
+ # center_crop hands mode, padding_mode and align_corners on to the warp; each one changes this output.
+ # A 2-wide crop of a 5-wide image starts at pixel 1.5, so bilinear averages four neighbours while
+ # nearest returns one of them.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = (torch.arange(25, device=device, dtype=dtype) ** 2).view(1, 1, 5, 5)
+ bilinear = (inp[..., 1:3, 1:3] + inp[..., 1:3, 2:4] + inp[..., 2:4, 1:3] + inp[..., 2:4, 2:4]) / 4
+ self.assert_close(kornia.geometry.transform.center_crop(inp, (2, 2)), bilinear)
+ nearest = kornia.geometry.transform.center_crop(inp, (2, 2), mode="nearest")
+ assert torch.isin(nearest, inp).all()
+
+ # A 4x4 crop of a 2x2 image samples pixels -1..2, outside the image on every side.
+ small = torch.tensor([[[[1.0, 2.0], [3.0, 4.0]]]], device=device, dtype=dtype)
+ replicated = torch.tensor(
+ [[[[1.0, 1.0, 2.0, 2.0], [1.0, 1.0, 2.0, 2.0], [3.0, 3.0, 4.0, 4.0], [3.0, 3.0, 4.0, 4.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(kornia.geometry.transform.center_crop(small, (4, 4), padding_mode="border"), replicated)
+ # reflection mirrors about the edge pixel centres under align_corners=True and about the image border
+ # under align_corners=False, so the two settings disagree outside the image.
+ mirrored = torch.tensor(
+ [[[[4.0, 3.0, 4.0, 3.0], [2.0, 1.0, 2.0, 1.0], [4.0, 3.0, 4.0, 3.0], [2.0, 1.0, 2.0, 1.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+ reflected = kornia.geometry.transform.center_crop(small, (4, 4), padding_mode="reflection", align_corners=True)
+ self.assert_close(reflected, mirrored)
+ reflected = kornia.geometry.transform.center_crop(small, (4, 4), padding_mode="reflection", align_corners=False)
+ self.assert_close(reflected, replicated)
+
class TestCropByBoxes(BaseTester):
def test_crop_by_boxes_no_resizing(self, device, dtype):