Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): read an unbatched (2, 3) matrix in affine as one shared matrix (#6463)

Saksham Sharmae4b87769b1fd
diff --git a/changelog.d/6463.fixed.md b/changelog.d/6463.fixed.md
new file mode 100644
index 000000000..763abb957
--- /dev/null
+++ b/changelog.d/6463.fixed.md
@@ -0,0 +1 @@
+`kornia.geometry.transform.affine` reads an unbatched `(2, 3)` matrix as one matrix, `(1, 2, 3)`, that serves every image. With one image, `(C, H, W)` or `(1, C, H, W)`, it used to read the matrix's 2 rows as 2 matrices and return the image twice, as a batch of 2, with no error. With more images the matrix was already shared, and the result is unchanged. A matrix of any other rank raises `ShapeError` up front, a `ValueError` like the one `warp_affine` raised for it before.
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 2606daceb..5d789427a 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -46,6 +46,7 @@ import torch
from torch import nn
from kornia.core._compat import _emit_deprecation_warning
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.ops import _device_literal, eye_like
from kornia.core.utils import _extract_device_dtype
from kornia.filters import gaussian_blur2d
@@ -185,9 +186,10 @@ def affine(
``out = affine(tensor, matrix)`` warps ``(C, H, W)`` or ``(B, C, H, W)`` images by ``(B, 2, 3)`` source→destination
pixel affine matrices and returns them at their own size: :func:`warp_affine` with ``dsize=(H, W)``, plus an
- unbatched image and broadcasting. One matrix serves every image of a batch, and one image, unbatched or of batch 1,
- is warped by every matrix, so it returns ``(B, C, H, W)`` for ``B > 1`` matrices. For another output size, use
- :func:`warp_affine`; to build the matrix from an angle, a shift, a scale and a shear, use :class:`Affine`.
+ unbatched image and broadcasting. One matrix, ``(1, 2, 3)`` or ``(2, 3)``, serves every image of a batch, and one
+ image, unbatched or of batch 1, is warped by every matrix, so it returns ``(B, C, H, W)`` for ``B > 1`` matrices.
+ For another output size, use :func:`warp_affine`; to build the matrix from an angle, a shift, a scale and a shear,
+ use :class:`Affine`.
.. image:: _static/img/warp_affine.png
@@ -195,12 +197,13 @@ def affine(
See :doc:`Conventions & Pitfalls </get-started/conventions>` for the ``align_corners``
defaults and sampling rules.
- - ``matrix`` is the source→destination **pixel** affine matrix ``(B, 2, 3)``
+ - ``matrix`` is the source→destination **pixel** affine matrix ``(B, 2, 3)``; an unbatched ``(2, 3)`` matrix
+ is read as ``(1, 2, 3)``.
Args:
tensor: The image tensor to be warped in shapes of
``(C, H, W)`` or ``(B, C, H, W)``.
- matrix: The 2x3 affine transformation matrices, with shape ``(B, 2, 3)``.
+ matrix: The 2x3 affine transformation matrices, with shape ``(B, 2, 3)``, or one ``(2, 3)`` matrix.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
``'zeros'`` | ``'border'`` | ``'reflection'``.
@@ -224,6 +227,12 @@ def affine(
torch.Size([1, 2, 3, 5])
"""
+ # One (2, 3) matrix serves every image, as a (1, 2, 3) one does; read as a batch below, its 2 rows warped a single
+ # image twice (#6462).
+ if matrix.dim() == 2:
+ matrix = matrix.unsqueeze(0)
+ KORNIA_CHECK_SHAPE(matrix, ["B", "2", "3"])
+
# warping needs data in the shape of BCHW
is_unbatched: bool = tensor.dim() == 3
if is_unbatched:
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index 319a32615..6cec2e5d4 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -24,7 +24,8 @@ import pytest
import torch
import kornia
-from kornia.core.exceptions import DeviceError, TypeCheckError
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
+from kornia.core.exceptions import DeviceError, ShapeError, TypeCheckError
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available, supports_reflect_padding
@@ -1106,6 +1107,29 @@ class TestAffine2d(BaseTester):
with pytest.raises(RuntimeError):
kornia.geometry.transform.affine(image, matrix)
+ @pytest.mark.parametrize("image_shape", [(0, 2, 5, 7), (1, 2, 5, 7), (2, 5, 7), (3, 2, 5, 7)])
+ @pytest.mark.parametrize("checks", [True, False])
+ def test_function_shares_unbatched_matrix_6462(self, device, dtype, image_shape, checks):
+ # A (2, 3) matrix serves every image, as (1, 2, 3) does. Read as a batch of 2, it used to warp one image,
+ # (1, C, H, W) or (C, H, W), twice; with checks disabled too, since the unbatched matrix is not a check.
+ image = torch.rand(image_shape, device=device, dtype=dtype)
+ matrix = torch.tensor([[0.9, 0.2, 1.0], [-0.1, 1.1, -0.5]], device=device, dtype=dtype)
+ was_enabled = are_checks_enabled()
+ if not checks:
+ disable_checks()
+ try:
+ out = kornia.geometry.transform.affine(image, matrix)
+ finally:
+ if was_enabled:
+ enable_checks()
+ assert out.shape == image.shape
+ self.assert_close(out, kornia.geometry.transform.affine(image, matrix[None]), atol=0, rtol=0)
+
+ def test_function_rejects_matrix_of_other_rank(self, device, dtype):
+ image = torch.rand(1, 2, 5, 7, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ kornia.geometry.transform.affine(image, torch.ones(1, 1, 2, 3, device=device, dtype=dtype))
+
def test_affine_no_args(self):
with pytest.raises(RuntimeError):
kornia.geometry.transform.Affine()