Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry)!: reject unsupported transform input shapes (#6446)

Muhammad Talhad7abb91801a9
diff --git a/changelog.d/6446.breaking.md b/changelog.d/6446.breaking.md
new file mode 100644
index 000000000..61b63d771
--- /dev/null
+++ b/changelog.d/6446.breaking.md
@@ -0,0 +1 @@
+`warp_grid`, `warp_grid3d`, `get_translation_matrix2d`, `get_projective_transform` and `get_affine_matrix3d`, and through them `homography_warp` (with the default `normalized_homography=True`), `homography_warp3d` and `HomographyWarper`, now raise a `ShapeError` for an input of an unsupported rank instead of misreading it. An unbatched `(3, 3)` or `(4, 4)` homography used to have its first dimension taken as the batch size and its one matrix applied to every sample, so `warp_grid` returned 3 grids and `homography_warp` worked for exactly 3 images; a `(2,)` translation gave two matrices. Pass one homography per image, `(B, 3, 3)`, or `(B, 4, 4)` for the 3D functions (`M.expand(B, -1, -1)` shares one matrix across the batch), translations as `(B, 2)`, and scales as `(B, 3)` per axis or `(B, 1)` per sample, with `(3,)` or `(1, 3)` for shared `(sx, sy, sz)`. Working scale inputs retain their behavior; use `(B, 1)` for per-sample isotropic factors rather than the previously documented `(B,)`.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index e3b6e1f7b..0721d3fe9 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -660,6 +660,32 @@ def _fill_and_warp(
return _torch_grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode="zeros") + inv_color_mask
+def _check_homography_shape(src_homo_dst: torch.Tensor) -> None:
+ """Raise unless ``src_homo_dst`` is ``(B, 3, 3)`` or ``(B, 1, 3, 3)``.
+
+ A single ``(3, 3)`` matrix is refused: its first dimension would be read as the batch, so the grid would come
+ back with a batch of 3 instead of one grid.
+ """
+ msg = "src_homo_dst must be (B, 3, 3) or (B, 1, 3, 3); a single (3, 3) homography needs a leading batch dimension."
+ if src_homo_dst.dim() == 4:
+ KORNIA_CHECK_SHAPE(src_homo_dst, ["B", "1", "3", "3"], msg=msg)
+ else:
+ KORNIA_CHECK_SHAPE(src_homo_dst, ["B", "3", "3"], msg=msg)
+
+
+def _check_homography_shape3d(src_homo_dst: torch.Tensor) -> None:
+ """Raise unless ``src_homo_dst`` is ``(B, 4, 4)`` or ``(B, 1, 4, 4)``.
+
+ A single ``(4, 4)`` matrix is refused: its first dimension would be read as the batch, so the grid would come
+ back with a batch of 4 instead of one grid.
+ """
+ msg = "src_homo_dst must be (B, 4, 4) or (B, 1, 4, 4); a single (4, 4) homography needs a leading batch dimension."
+ if src_homo_dst.dim() == 4:
+ KORNIA_CHECK_SHAPE(src_homo_dst, ["B", "1", "4", "4"], msg=msg)
+ else:
+ KORNIA_CHECK_SHAPE(src_homo_dst, ["B", "4", "4"], msg=msg)
+
+
def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
"""Warp a grid of 2D points by homographies, returning the coordinates without sampling an image.
@@ -693,6 +719,10 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
Returns:
the transformed grid of shape ``(N, H, W, 2)``.
+ Raises:
+ ShapeError: If ``grid`` is not ``(B, H, W, 2)``, or ``src_homo_dst`` is not ``(B, 3, 3)`` or
+ ``(B, 1, 3, 3)``. A single ``(3, 3)`` homography needs a leading batch dimension.
+
See Also:
- :func:`warp_grid3d`: the same for a 3D ``(x, y, z)`` grid and ``(N, 4, 4)`` homographies.
- :func:`homography_warp`: builds the grid, warps it with this function and samples the image.
@@ -701,6 +731,8 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
matrices.
"""
+ KORNIA_CHECK_SHAPE(grid, ["B", "H", "W", "2"], msg="grid must be (1, H, W, 2) or (N, H, W, 2).")
+ _check_homography_shape(src_homo_dst)
batch_size: int = src_homo_dst.size(0)
_, height, width, _ = grid.size()
# expand grid to match the input batch size
@@ -738,6 +770,7 @@ def _warp_pixel_grid(src_homo_dst: torch.Tensor, height: int, width: int) -> tor
also in a scripted call, which cannot leave it, and round the pixel coordinates of a 640 px wide grid to whole
pixels in bfloat16. Autocast leaves elementwise products alone, so eager and scripted calls compute the same grid.
"""
+ _check_homography_shape(src_homo_dst)
work_dtype = _pixel_grid_work_dtype(src_homo_dst)
grid = create_meshgrid(height, width, normalized_coordinates=False, device=src_homo_dst.device, dtype=work_dtype)
matrix = src_homo_dst.to(work_dtype)
@@ -794,6 +827,10 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
Returns:
the transformed grid of shape ``(N, D, H, W, 3)``.
+ Raises:
+ ShapeError: If ``grid`` is not ``(B, D, H, W, 3)``, or ``src_homo_dst`` is not ``(B, 4, 4)`` or
+ ``(B, 1, 4, 4)``. A single ``(4, 4)`` homography needs a leading batch dimension.
+
See Also:
- :func:`warp_grid`: the same for a 2D ``(x, y)`` grid and ``(N, 3, 3)`` homographies.
- :func:`homography_warp3d`: builds and reorders the grid, warps it with this function and samples the volume.
@@ -801,6 +838,8 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
in.
"""
+ KORNIA_CHECK_SHAPE(grid, ["B", "D", "H", "W", "3"], msg="grid must be (1, D, H, W, 3) or (N, D, H, W, 3).")
+ _check_homography_shape3d(src_homo_dst)
batch_size: int = src_homo_dst.size(0)
_, depth, height, width, _ = grid.size()
# expand grid to match the input batch size
@@ -824,6 +863,7 @@ def _warp_pixel_grid3d(src_homo_dst: torch.Tensor, depth: int, height: int, widt
elementwise column products that a caller's autocast region leaves alone, scripted or not. The result is
``(N, D, H, W, 3)`` in the ``(x, y, z)`` order the homography and ``grid_sample`` read.
"""
+ _check_homography_shape3d(src_homo_dst)
work_dtype = _pixel_grid_work_dtype(src_homo_dst)
grid = create_meshgrid3d(
depth, height, width, normalized_coordinates=False, device=src_homo_dst.device, dtype=work_dtype
@@ -1379,11 +1419,17 @@ def get_translation_matrix2d(translations: torch.Tensor) -> torch.Tensor:
Returns:
the affine transformation matrix ``(B, 3, 3)``.
+ Raises:
+ ShapeError: If ``translations`` is not ``(B, 2)``. A single translation needs shape ``(1, 2)``.
+
See Also:
- :func:`translate`: shift an image without building the matrix.
- :func:`get_affine_matrix2d`: a translation composed with a rotation, a scale and a shear.
"""
+ KORNIA_CHECK_SHAPE(
+ translations, ["B", "2"], msg="translations must be (B, 2); a single (2,) translation needs a batch dimension."
+ )
transform: torch.Tensor = eye_like(3, translations)[:, :2, :]
transform[..., 2] += translations # tx/ty
@@ -1494,10 +1540,10 @@ def get_affine_matrix3d(
Args:
translations: torch.Tensor containing the translation vector (dx,dy,dz) with shape ``(B, 3)``.
center: torch.Tensor containing the center vector (x,y,z) with shape ``(B, 3)``.
- scale: per-axis scale factors ``(sx, sy, sz)`` with shape ``(B, 3)``; a ``(B, 1)`` or ``(1,)`` tensor scales
- the three axes alike. A ``(B,)`` tensor is not one factor per matrix: for ``B = 3`` it is read as
- ``(sx, sy, sz)``, and for another ``B > 1`` it raises
- (`#6398 <https://github.com/kornia/kornia/issues/6398>`_).
+ scale: per-axis scale factors ``(sx, sy, sz)`` with shape ``(B, 3)``, or ``(1, 3)`` or ``(3,)`` shared
+ across the batch. A ``(3,)`` tensor always means per-axis factors, including when ``B = 3``.
+ Use ``(B, 1)`` for one isotropic factor per sample, or ``(1,)`` for one factor shared across all samples
+ and axes. Per-sample isotropic factors must have shape ``(B, 1)``, not ``(B,)``.
angles: axis angle vector containing the rotation angles in degrees in the form
of (rx, ry, rz) with shape ``(B, 3)``. Internally it calls Rodrigues to compute
the rotation matrix from axis-angle.
@@ -1511,6 +1557,10 @@ def get_affine_matrix3d(
Returns:
the 3d affine transformation matrix ``(B, 4, 4)``.
+ Raises:
+ ShapeError: If ``scale`` is not ``(B, 3)``, ``(B, 1)``, ``(1, 3)``, ``(3,)`` or ``(1,)``;
+ see :func:`get_projective_transform`.
+
See Also:
- :func:`get_affine_matrix2d`: the 2D composition, whose positive angle turns clockwise on screen.
- :func:`get_projective_transform`: rotation and scale only, ``(B, 3, 4)``, with the angles as given.
@@ -1777,6 +1827,27 @@ def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
return torch.cat([rmat, tvec], -1) # Bx3x4
+def _check_scale_shape3d(scales: torch.Tensor) -> None:
+ """Validate batched scale factors or shared ``(3,)`` per-axis and ``(1,)`` isotropic factors.
+
+ A ``(3,)`` tensor means ``(sx, sy, sz)`` shared by every sample, including at ``B = 3``. Per-sample isotropic
+ factors go in a column, ``(B, 1)``; other 1-D lengths are unsupported.
+ """
+ msg = (
+ "scale must be (B, 3) or (1, 3) per-axis, (B, 1) isotropic, (3,) shared per-axis or (1,) shared isotropic "
+ "factors; reshape per-sample factors (B,) to (B, 1)."
+ )
+ if scales.dim() == 1:
+ if scales.shape[0] == 3:
+ KORNIA_CHECK_SHAPE(scales, ["3"], msg=msg)
+ else:
+ KORNIA_CHECK_SHAPE(scales, ["1"], msg=msg)
+ elif scales.dim() == 2 and scales.shape[1] == 1:
+ KORNIA_CHECK_SHAPE(scales, ["B", "1"], msg=msg)
+ else:
+ KORNIA_CHECK_SHAPE(scales, ["B", "3"], msg=msg)
+
+
def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
"""Compute the 3x4 affine matrix of a 3D scaling and axis-angle rotation about a centre.
@@ -1804,11 +1875,17 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
angles: axis angle vector containing the rotation angles in degrees in the form
of (rx, ry, rz) with shape ``(B, 3)``. Internally it calls Rodrigues to compute
the rotation matrix from axis-angle.
- scales: scale factor for x-y-z-directions with shape ``(B, 3)``.
+ scales: per-axis scale factors ``(sx, sy, sz)`` with shape ``(B, 3)``, or ``(1, 3)`` or ``(3,)`` shared
+ across the batch. A ``(3,)`` tensor always means per-axis factors, including when ``B = 3``.
+ Use ``(B, 1)`` for one isotropic factor per sample, or ``(1,)`` for one factor shared across all samples
+ and axes. Per-sample isotropic factors must have shape ``(B, 1)``, not ``(B,)``.
Returns:
the projection matrix of 3D rotation with shape ``(B, 3, 4)``.
+ Raises:
+ ShapeError: If ``scales`` is not ``(B, 3)``, ``(B, 1)``, ``(1, 3)``, ``(3,)`` or ``(1,)``.
+
See Also:
- :func:`get_rotation_matrix2d`: the 2D rotation and scale, counter-clockwise on screen.
- :func:`get_affine_matrix3d`: adds a translation and shears, and negates the angles.
@@ -1825,6 +1902,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
raise AssertionError(center.device, angles.device)
if center.dtype != angles.dtype:
raise AssertionError(center.dtype, angles.dtype)
+ _check_scale_shape3d(scales)
# create rotation matrix
axis_angle_rad: torch.Tensor = torch.torch.deg2rad(angles)
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index b7a508ecf..b91f91c73 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -19,6 +19,8 @@ import pytest
import torch
import kornia
+from kornia.core._compat import torch_version_lt
+from kornia.core.exceptions import ShapeError
from kornia.core.ops import eye_like
from kornia.core.utils import _torch_grid_sample, _torch_inverse_cast
@@ -1041,3 +1043,156 @@ class TestHomographyWarper3D(BaseTester):
self.assert_close(grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0], atol=1e-4, rtol=1e-4)
self.assert_close(grid[..., 1].to(device=device, dtype=dtype), flow[..., 1], atol=1e-4, rtol=1e-4)
self.assert_close(grid[..., 2].to(device=device, dtype=dtype), flow[..., 2], atol=1e-4, rtol=1e-4)
+
+
+class TestHomographyShapeChecks(BaseTester):
+ """A homography of an unsupported rank raises instead of having its first dimension read as the batch."""
+
+ @pytest.mark.parametrize("shape", [(3, 3), (2, 2, 3, 3), (1, 2, 3, 3, 1), (3,), (4, 4)])
+ def test_warp_grid_rejects_unsupported_homography_shape(self, shape, device, dtype):
+ grid = kornia.geometry.create_meshgrid(4, 5, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.warp_grid(grid, torch.ones(shape, device=device, dtype=dtype))
+
+ def test_warp_grid_unbatched_identity_is_not_read_as_a_batch_of_three(self, device, dtype):
+ # The case from the issue: the 3x3 identity used to give a grid of shape (3, 4, 5, 2).
+ grid = kornia.geometry.create_meshgrid(4, 5, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match="leading batch dimension"):
+ kornia.geometry.transform.warp_grid(grid, torch.eye(3, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("shape", [(3, 4, 5), (4, 5, 2), (1, 4, 5, 3), (1, 1, 4, 5, 2)])
+ def test_warp_grid_rejects_unsupported_grid_shape(self, shape, device, dtype):
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.warp_grid(
+ torch.zeros(shape, device=device, dtype=dtype), eye_like(3, torch.zeros(1, device=device, dtype=dtype))
+ )
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 5])
+ def test_warp_grid_keeps_the_documented_shapes(self, batch, device, dtype):
+ grid = kornia.geometry.create_meshgrid(4, 5, normalized_coordinates=False, device=device, dtype=dtype)
+ homography = eye_like(3, torch.zeros(batch, device=device, dtype=dtype))
+ homography[:, 0, 2] = torch.arange(batch, device=device, dtype=dtype) # a different x offset per sample
+
+ flow = kornia.geometry.transform.warp_grid(grid, homography) # (1, H, W, 2) grid, (N, 3, 3)
+ assert flow.shape == (batch, 4, 5, 2)
+ for i in range(batch):
+ self.assert_close(flow[i, ..., 0], grid[0, ..., 0] + i)
+ self.assert_close(flow[i, ..., 1], grid[0, ..., 1])
+
+ # (N, 1, 3, 3) is the same warp as (N, 3, 3)
+ self.assert_close(kornia.geometry.transform.warp_grid(grid, homography[:, None]), flow)
+ # a batched grid with a matching batch of homographies
+ self.assert_close(kornia.geometry.transform.warp_grid(grid.expand(batch, -1, -1, -1), homography), flow)
+
+ @pytest.mark.parametrize("batch", [1, 2, 3])
+ def test_homography_warp_pixel_homography_path_rejects_unbatched_homography(self, batch, device, dtype):
+ # normalized_homography=False is handed to warp_perspective, which raises its own ValueError for an unbatched
+ # matrix. Only "still an error for every batch" is pinned. The exception type is left open on purpose: a
+ # ShapeError there would be an improvement and is a ValueError anyway.
+ image = torch.rand(batch, 1, 4, 5, device=device, dtype=dtype)
+ with pytest.raises(ValueError):
+ kornia.geometry.transform.homography_warp(
+ image, torch.eye(3, device=device, dtype=dtype), (4, 5), normalized_homography=False
+ )
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 5])
+ def test_homography_warp_shares_one_homography_with_expand(self, batch, device, dtype):
+ # The migration for an unbatched (3, 3) is one homography per image. expand shares one matrix without a copy
+ # and is what the old (3, 3) call amounted to at a batch of 3.
+ image = torch.rand(batch, 1, 4, 5, device=device, dtype=dtype)
+ homography = torch.eye(3, device=device, dtype=dtype)
+ homography[0, 2], homography[1, 2] = 0.2, -0.1
+
+ out = kornia.geometry.transform.homography_warp(image, homography.expand(batch, -1, -1), (4, 5))
+ expected = torch.cat(
+ [
+ kornia.geometry.transform.homography_warp(image[i : i + 1], homography[None], (4, 5))
+ for i in range(batch)
+ ]
+ )
+ self.assert_close(out, expected)
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 5])
+ @pytest.mark.parametrize("normalized_coordinates", [True, False])
+ def test_homography_warp_rejects_unbatched_homography_for_any_batch(
+ self, batch, normalized_coordinates, device, dtype
+ ):
+ # (3, 3) used to work only for a batch of 3 images, where it was read as 3 homographies.
+ image = torch.rand(batch, 1, 4, 5, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.homography_warp(
+ image,
+ torch.eye(3, device=device, dtype=dtype),
+ (4, 5),
+ normalized_coordinates=normalized_coordinates,
+ )
+
+ @pytest.mark.parametrize("normalized_coordinates", [True, False])
+ def test_homography_warper_rejects_unbatched_homography(self, normalized_coordinates, device, dtype):
+ warper = kornia.geometry.transform.HomographyWarper(4, 5, normalized_coordinates=normalized_coordinates)
+ with pytest.raises(ShapeError):
+ warper(torch.rand(3, 1, 4, 5, device=device, dtype=dtype), torch.eye(3, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("shape", [(4, 4), (2, 2, 4, 4), (1, 2, 4, 4, 1), (4,), (3, 3)])
+ def test_warp_grid3d_rejects_unsupported_homography_shape(self, shape, device, dtype):
+ grid = kornia.geometry.create_meshgrid3d(2, 4, 5, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.warp_grid3d(grid, torch.ones(shape, device=device, dtype=dtype))
+
+ def test_warp_grid3d_unbatched_identity_is_not_read_as_a_batch_of_four(self, device, dtype):
+ # The case from the issue: the 4x4 identity used to give a grid of shape (4, 2, 4, 5, 3).
+ grid = kornia.geometry.create_meshgrid3d(2, 4, 5, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match="leading batch dimension"):
+ kornia.geometry.transform.warp_grid3d(grid, torch.eye(4, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("shape", [(4, 5, 3), (2, 4, 5, 3), (1, 2, 4, 5, 2), (1, 1, 2, 4, 5, 3)])
+ def test_warp_grid3d_rejects_unsupported_grid_shape(self, shape, device, dtype):
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.warp_grid3d(
+ torch.zeros(shape, device=device, dtype=dtype), eye_like(4, torch.zeros(1, device=device, dtype=dtype))
+ )
+
+ @pytest.mark.parametrize("batch", [1, 2, 4, 5])
+ def test_warp_grid3d_keeps_the_documented_shapes(self, batch, device, dtype):
+ grid = kornia.geometry.create_meshgrid3d(2, 4, 5, normalized_coordinates=False, device=device, dtype=dtype)
+ homography = eye_like(4, torch.zeros(batch, device=device, dtype=dtype))
+ homography[:, 0, 3] = torch.arange(batch, device=device, dtype=dtype)
+
+ flow = kornia.geometry.transform.warp_grid3d(grid, homography) # (1, D, H, W, 3) grid, (N, 4, 4)
+ assert flow.shape == (batch, 2, 4, 5, 3)
+ for i in range(batch):
+ self.assert_close(flow[i, ..., 0], grid[0, ..., 0] + i)
+ self.assert_close(flow[i, ..., 1:], grid[0, ..., 1:])
+
+ self.assert_close(kornia.geometry.transform.warp_grid3d(grid, homography[:, None]), flow)
+ self.assert_close(kornia.geometry.transform.warp_grid3d(grid.expand(batch, -1, -1, -1, -1), homography), flow)
+
+ @pytest.mark.parametrize("batch", [1, 2, 4, 5])
+ def test_homography_warp3d_shares_one_homography_with_expand(self, batch, device, dtype):
+ if device.type == "mps" and torch_version_lt(2, 9, 0):
+ pytest.skip("MPS grid_sampler_3d requires PyTorch 2.9 or newer")
+ # The 3D counterpart of the migration for an unbatched (4, 4): one homography per volume, shared with expand.
+ volume = torch.rand(batch, 1, 2, 4, 5, device=device, dtype=dtype)
+ homography = torch.eye(4, device=device, dtype=dtype)
+ homography[0, 3], homography[1, 3] = 0.2, -0.1
+
+ out = kornia.geometry.transform.homography_warp3d(volume, homography.expand(batch, -1, -1), (2, 4, 5))
+ expected = torch.cat(
+ [
+ kornia.geometry.transform.homography_warp3d(volume[i : i + 1], homography[None], (2, 4, 5))
+ for i in range(batch)
+ ]
+ )
+ self.assert_close(out, expected)
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 4])
+ def test_homography_warp3d_rejects_unbatched_homography_for_any_batch(self, batch, device, dtype):
+ volume = torch.rand(batch, 1, 2, 4, 5, device=device, dtype=dtype)
+ for normalized_coordinates in (True, False):
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.homography_warp3d(
+ volume,
+ torch.eye(4, device=device, dtype=dtype),
+ (2, 4, 5),
+ normalized_coordinates=normalized_coordinates,
+ )
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 319bdbc1d..bf754c5ab 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -22,7 +22,7 @@ import torch
import kornia
from kornia.core._compat import torch_version, torch_version_lt
-from kornia.core.exceptions import BaseError
+from kornia.core.exceptions import BaseError, ShapeError
from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
@@ -1520,3 +1520,31 @@ class TestGetPerspectiveTransformAutocast(BaseTester):
dst = torch.tensor([[[1.0, 0.5], [11.0, 1.0], [9.5, 8.5], [-0.5, 7.5]]], device=device, dtype=dtype)
scripted = torch.jit.script(kornia.geometry.transform.get_perspective_transform)
self.assert_close(scripted(src, dst), kornia.geometry.transform.get_perspective_transform(src, dst))
+
+
+class TestGetTranslationMatrix2d(BaseTester):
+ @pytest.mark.parametrize("shape", [(2,), (1,), (3,), (1, 1, 2), (2, 3), (2, 2, 2), ()])
+ def test_rejects_unsupported_shape(self, shape, device, dtype):
+ # (2,) used to give two matrices, one per component, and (1,) one matrix with dx = dy.
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.get_translation_matrix2d(torch.ones(shape, device=device, dtype=dtype))
+
+ def test_unbatched_translation_is_not_read_as_two_matrices(self, device, dtype):
+ with pytest.raises(ShapeError, match="batch dimension"):
+ kornia.geometry.transform.get_translation_matrix2d(torch.tensor([1.0, 2.0], device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 5])
+ def test_batch(self, batch, device, dtype):
+ translations = torch.stack(
+ (
+ torch.arange(batch, device=device, dtype=dtype) + 1.0,
+ -2.0 * torch.arange(batch, device=device, dtype=dtype),
+ ),
+ dim=-1,
+ ) # (B, 2)
+ matrix = kornia.geometry.transform.get_translation_matrix2d(translations)
+ assert matrix.shape == (batch, 3, 3)
+
+ expected = torch.eye(3, device=device, dtype=dtype).repeat(batch, 1, 1)
+ expected[:, :2, 2] = translations
+ self.assert_close(matrix, expected)
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index 76fd75e28..a41d01ff3 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -22,6 +22,7 @@ import torch
import kornia
import kornia.geometry.transform as proj
+from kornia.core.exceptions import ShapeError
from kornia.core.utils import _torch_grid_sample, _torch_inverse_cast
from testing.base import BaseTester, assert_close
@@ -1055,3 +1056,109 @@ class TestPerspectiveTransform3D(BaseTester):
# compute gradient check
self.gradcheck(kornia.geometry.transform.get_perspective_transform3d, (src, dst))
+
+
+class TestScaleShape3d(BaseTester):
+ """Preserve shared per-axis scales while rejecting unsupported scale shapes."""
+
+ @staticmethod
+ def _inputs(batch, device, dtype):
+ center = torch.zeros(batch, 3, device=device, dtype=dtype)
+ angles = torch.zeros(batch, 3, device=device, dtype=dtype)
+ translations = torch.zeros(batch, 3, device=device, dtype=dtype)
+ return translations, center, angles
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 4])
+ def test_projective_transform_keeps_shared_per_axis_scale(self, batch, device, dtype):
+ _, center, angles = self._inputs(batch, device, dtype)
+ scale = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
+ matrix = proj.get_projective_transform(center, angles, scale)
+ self.assert_close(matrix, proj.get_projective_transform(center, angles, scale[None]))
+ self.assert_close(matrix[..., :3], torch.diag(scale).expand(batch, 3, 3))
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 4])
+ @pytest.mark.parametrize("shape", [(), (0,), (2,), (4,), (5,), (2, 2)])
+ def test_rejects_unsupported_scale_shape(self, batch, shape, device, dtype):
+ translations, center, angles = self._inputs(batch, device, dtype)
+ scale = torch.ones(shape, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ proj.get_projective_transform(center, angles, scale)
+ with pytest.raises(ShapeError):
+ proj.get_affine_matrix3d(translations, center, scale, angles)
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 4])
+ def test_rejects_extra_scale_dimension(self, batch, device, dtype):
+ translations, center, angles = self._inputs(batch, device, dtype)
+ scale = torch.ones(batch, 3, 1, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ proj.get_projective_transform(center, angles, scale)
+ with pytest.raises(ShapeError):
+ proj.get_affine_matrix3d(translations, center, scale, angles)
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 4])
+ def test_affine_matrix3d_keeps_shared_per_axis_scale(self, batch, device, dtype):
+ translations, center, angles = self._inputs(batch, device, dtype)
+ scale = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
+ matrix = proj.get_affine_matrix3d(translations, center, scale, angles)
+ self.assert_close(matrix, proj.get_affine_matrix3d(translations, center, scale[None], angles))
+ self.assert_close(matrix[..., :3, :3], torch.diag(scale).expand(batch, 3, 3))
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 4])
+ def test_per_axis_scale_is_the_diagonal(self, batch, device, dtype):
+ translations, center, angles = self._inputs(batch, device, dtype)
+ # A different (sx, sy, sz) for every sample, so reusing one sample's scale for the others is caught.
+ scale = torch.arange(1, 3 * batch + 1, device=device, dtype=dtype).reshape(batch, 3) # (B, 3)
+ expected = torch.diag_embed(scale)
+
+ projective = proj.get_projective_transform(center, angles, scale)
+ assert projective.shape == (batch, 3, 4)
+ self.assert_close(projective[..., :3], expected)
+
+ affine = proj.get_affine_matrix3d(translations, center, scale, angles)
+ assert affine.shape == (batch, 4, 4)
+ self.assert_close(affine[..., :3, :3], expected)
+
+ @pytest.mark.parametrize("batch", [1, 2, 3, 4])
+ def test_isotropic_scale_matches_the_repeated_per_axis_scale(self, batch, device, dtype):
+ translations, center, angles = self._inputs(batch, device, dtype)
+ angles = angles + torch.tensor([10.0, -20.0, 30.0], device=device, dtype=dtype)
+ isotropic = torch.linspace(1.0, 2.0, batch, device=device, dtype=dtype)[:, None] # (B, 1)
+
+ self.assert_close(
+ proj.get_projective_transform(center, angles, isotropic),
+ proj.get_projective_transform(center, angles, isotropic.repeat(1, 3)),
+ )
+ self.assert_close(
+ proj.get_affine_matrix3d(translations, center, isotropic, angles),
+ proj.get_affine_matrix3d(translations, center, isotropic.repeat(1, 3), angles),
+ )
+
+ @pytest.mark.parametrize("batch", [2, 3, 4])
+ def test_the_two_reshapes_of_a_flat_scale_mean_different_things(self, batch, device, dtype):
+ # Per-sample isotropic factors use (B, 1); a (1, 3) row is per axis and shared by every sample.
+ translations, center, angles = self._inputs(batch, device, dtype)
+ per_sample = torch.arange(1, batch + 1, device=device, dtype=dtype)
+ axes = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
+
+ column_expected = torch.diag_embed(per_sample[:, None].expand(batch, 3))
+ row_expected = torch.diag(axes).expand(batch, 3, 3)
+
+ column = proj.get_projective_transform(center, angles, per_sample[:, None])
+ row = proj.get_projective_transform(center, angles, axes[None])
+ self.assert_close(column[..., :3], column_expected)
+ self.assert_close(row[..., :3], row_expected)
+
+ column = proj.get_affine_matrix3d(translations, center, per_sample[:, None], angles)
+ row = proj.get_affine_matrix3d(translations, center, axes[None], angles)
+ self.assert_close(column[..., :3, :3], column_expected)
+ self.assert_close(row[..., :3, :3], row_expected)
+
+ @pytest.mark.parametrize("batch", [1, 3])
+ def test_single_scale_factor_still_applies_to_every_sample(self, batch, device, dtype):
+ # A (1,) tensor worked before and is unambiguous, so it is still accepted.
+ _, center, angles = self._inputs(batch, device, dtype)
+ single = torch.tensor([2.0], device=device, dtype=dtype)
+ self.assert_close(
+ proj.get_projective_transform(center, angles, single),
+ proj.get_projective_transform(center, angles, single.expand(batch, 3).contiguous()),
+ )