Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): use warp_perspective in crop_and_resize for non-parallel boxes (#3650)

FloodExLLCd72d71c24c29
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 855f324f4..af88cfa5d 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -232,7 +232,7 @@ class RandomCrop(GeometricAugmentationBase2D):
return crop_by_transform_mat(
input,
- transform,
+ transform[:, :2, :],
flags["size"],
mode=flags["resample"].name.lower(),
padding_mode=padding_mode,
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 27807c183..32c171d68 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -129,7 +129,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
return crop_by_transform_mat(
input,
- transform,
+ transform[:, :2, :],
flags["size"],
mode=flags["resample"].name.lower(),
padding_mode="zeros",
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 320ef5967..be9bd6123 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -207,7 +207,7 @@ class RandomMosaic(MixAugmentationBaseV2):
return crop_by_transform_mat(
input,
- transform,
+ transform[:, :2, :],
flags["output_size"],
mode=flags["resample"].name.lower(),
padding_mode=padding_mode,
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index c20802755..f0890d678 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -26,7 +26,7 @@ from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.bbox import infer_bbox_shape
from .affwarp import resize
-from .imgwarp import get_perspective_transform, warp_affine
+from .imgwarp import get_perspective_transform, warp_affine, warp_perspective
__all__ = [
"CenterCrop2D",
@@ -283,7 +283,8 @@ def crop_by_transform_mat(
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
- transform: a perspective transformation matrix with shape (B, 3, 3).
+ transform: a perspective transformation matrix with shape (B, 3, 3), or an
+ affine matrix with shape (B, 2, 3) that takes the cheaper warp_affine path.
out_size: size of the output image (height, width).
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
@@ -300,9 +301,51 @@ def crop_by_transform_mat(
transform.expand(input_tensor.shape[0], -1, -1), device=input_tensor.device, dtype=input_tensor.dtype
)
- patches: torch.Tensor = warp_affine(
+ # dispatch on the transform shape, which is static and therefore safe for torch.export:
+ # (B, 2, 3) is affine by construction and keeps the cheaper warp_affine path (no perspective
+ # divide, shared-grid broadcast), while (B, 3, 3) takes the full perspective warp.
+ if transform.shape[-2:] == (2, 3):
+ return warp_affine(
+ input_tensor,
+ dst_trans_src,
+ out_size,
+ mode=mode,
+ padding_mode=padding_mode,
+ align_corners=align_corners,
+ )
+
+ h_out, w_out = out_size
+ if not align_corners and (h_out == 1 or w_out == 1):
+ # the destination-side reparametrization below is singular for 1-pixel outputs,
+ # so keep the historical affine sampling for this degenerate size
+ return warp_affine(
+ input_tensor,
+ dst_trans_src[:, :2, :],
+ out_size,
+ mode=mode,
+ padding_mode=padding_mode,
+ align_corners=align_corners,
+ )
+
+ if not align_corners:
+ # warp_perspective always builds its grid with align_corners=True spacing, while this
+ # function historically followed warp_affine/F.affine_grid; this destination-side
+ # reparametrization maps one convention onto the other. It depends only on out_size,
+ # keeping the graph free of data-dependent control flow for torch.export.
+ correction = torch.tensor(
+ [
+ [w_out / (w_out - 1.0), 0.0, -0.5],
+ [0.0, h_out / (h_out - 1.0), -0.5],
+ [0.0, 0.0, 1.0],
+ ],
+ device=dst_trans_src.device,
+ dtype=dst_trans_src.dtype,
+ )
+ dst_trans_src = correction.unsqueeze(0) @ dst_trans_src
+
+ patches: torch.Tensor = warp_perspective(
input_tensor,
- dst_trans_src[:, :2, :],
+ dst_trans_src,
out_size,
mode=mode,
padding_mode=padding_mode,
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index 3d2c757f4..b6b05b6bc 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -79,6 +79,45 @@ class TestCropAndResize(BaseTester):
patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (2, 2))
self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ def test_crop_non_parallel_box(self, device, dtype):
+ # regression test for https://github.com/kornia/kornia/issues/3560:
+ # boxes with non-parallel opposite sides need a perspective warp, not affine
+ inp = torch.arange(1.0, 37.0, device=device, dtype=dtype).view(1, 1, 6, 6)
+
+ boxes = torch.tensor(
+ [[[1.0, 1.0], [4.0, 0.0], [5.0, 4.0], [0.0, 3.0]]], device=device, dtype=dtype
+ ) # 1x4x2 trapezoid
+
+ # Snippet used to generate expected (requires numpy only): solve the DLT for the
+ # homography mapping output corners to the box corners, then bilinear-sample:
+ # import numpy as np
+ # img = np.arange(1.0, 37.0).reshape(6, 6)
+ # src = np.array([[1.0, 1.0], [4.0, 0.0], [5.0, 4.0], [0.0, 3.0]])
+ # dst = np.array([[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]])
+ # A, b = [], []
+ # for (xs, ys), (xd, yd) in zip(src, dst):
+ # A += [[xd, yd, 1, 0, 0, 0, -xs * xd, -xs * yd], [0, 0, 0, xd, yd, 1, -ys * xd, -ys * yd]]
+ # b += [xs, ys]
+ # H = np.append(np.linalg.solve(np.array(A), np.array(b)), 1.0).reshape(3, 3)
+ # expected = np.zeros((3, 3))
+ # for j in range(3):
+ # for i in range(3):
+ # p = H @ np.array([i, j, 1.0])
+ # x, y = p[0] / p[2], p[1] / p[2]
+ # x0, y0 = int(np.floor(x)), int(np.floor(y))
+ # ax, ay = x - x0, y - y0
+ # x1, y1 = min(x0 + 1, 5), min(y0 + 1, 5)
+ # expected[j, i] = (img[y0, x0] * (1 - ax) * (1 - ay) + img[y0, x1] * ax * (1 - ay)
+ # + img[y1, x0] * (1 - ax) * ay + img[y1, x1] * ax * ay)
+ expected = torch.tensor(
+ [[[[8.0, 6.9, 5.0], [12.46875, 12.583333, 12.8125], [19.0, 22.055556, 30.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+
+ patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (3, 3))
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+
def test_crop_batch_broadcast(self, device, dtype):
inp = torch.tensor(
[