Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): let Affine share a batch-1 parameter set across a batch without center (#6457)

Debanjan Sarkar37e80158c4d0
diff --git a/changelog.d/6457.fixed.md b/changelog.d/6457.fixed.md
new file mode 100644
index 000000000..e3a82dd06
--- /dev/null
+++ b/changelog.d/6457.fixed.md
@@ -0,0 +1 @@
+`Affine` without `center` now builds its default centre at the parameters' batch size, so one parameter set warps every image of a batch, and `B` parameter sets warp one image into `(B, C, H, W)`, as they already did with `center` given. Both used to raise `ValueError: Inputs must have same batch size dimension`. A parameter batch that differs from the input batch, neither being 1, now raises a `ValueError` that names both batch sizes. With `center` given, that case used to fail with a `RuntimeError` from a tensor expansion; without `center`, it used to raise the same generic batch-size `ValueError`, which reported the shape of a centre the caller never passed.
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index d3ebda6bb..2606daceb 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -1125,9 +1125,9 @@ class Affine(nn.Module):
then ``out = warper(input)`` warps ``(B, C, H, W)`` images, or one ``(C, H, W)`` image, by the matrix of
:func:`get_affine_matrix2d`: a shear, a scale, a counter-clockwise rotation in degrees and a translation in pixels,
the first three about ``center`` (by default the image centre). The parameters, and ``center`` when given, share
- one batch size; without ``center``, it must equal the input's, a ``(C, H, W)`` input counting as 1
- (`#6395 <https://github.com/kornia/kornia/issues/6395>`_). For a matrix you already have, use :func:`affine`;
- for one kind of warp, :class:`Rotate`, :class:`Translate`, :class:`Scale` or :class:`Shear`.
+ one batch size ``P``. ``P`` and the input batch must be equal, or one of them 1, a ``(C, H, W)`` input counting
+ as 1: one parameter set warps every image, and ``P`` sets warp one image. For a matrix you already have, use
+ :func:`affine`; for one kind of warp, :class:`Rotate`, :class:`Translate`, :class:`Scale` or :class:`Shear`.
Convention:
- ``shear`` contains angles in radians, using the negative-tangent, x-then-y convention
@@ -1158,25 +1158,23 @@ class Affine(nn.Module):
Raises:
RuntimeError: At construction, if not one of ``angle``, ``translation``, ``scale_factor``, or ``shear`` is
- set, or if their batch sizes differ. At the call with ``center`` given, if the parameter batch and the
- input batch differ and neither is 1.
+ set, or if their batch sizes differ.
DeviceError: If ``angle``, ``translation``, ``scale_factor`` and ``shear`` are not all on one device.
TypeCheckError: If they are on one device but do not all have one dtype. The ones not given are
created on that device and in that dtype.
ValueError: At the call, if ``center`` and the parameters have different batch sizes (construction does not
- check ``center``), or, without ``center``, if the parameter batch differs from the input batch, a
- ``(C, H, W)`` input counting as 1 (`#6395 <https://github.com/kornia/kornia/issues/6395>`_).
+ check ``center``), or if the parameter batch and the input batch differ and neither is 1, a
+ ``(C, H, W)`` input counting as 1.
Returns:
- The transformed tensor with same shape as input, except that with ``center`` given, one image warped by
- ``B > 1`` parameter sets returns ``(B, C, H, W)``.
+ The transformed tensor with same shape as input, except that one image warped by ``P > 1`` parameter sets
+ returns ``(P, C, H, W)``.
See Also:
- :func:`get_affine_matrix2d`: the ``(B, 3, 3)`` matrix this module warps by, whose own angle turns clockwise
(`#4408 <https://github.com/kornia/kornia/issues/4408>`_).
- :func:`affine`: warp by an affine matrix you already have.
- - :class:`Rotate`: a rotation alone, which, unlike this module without ``center``, shares one angle across a
- batch.
+ - :class:`Rotate`: a rotation alone.
- :class:`Shear`: raw shear factors about pixel ``(0, 0)``, which shear the other way below ``pi / 2``.
Example:
@@ -1247,8 +1245,8 @@ class Affine(nn.Module):
:math:`H` is height, and :math:`W` is width.
Returns:
- Affine-warped tensor with shape ``(B, C, H, W)``. Values
- sampled outside the input image are handled by ``self.padding_mode``.
+ Affine-warped tensor with the input's shape, except that one image warped by ``P > 1`` parameter sets
+ gives ``(P, C, H, W)``. Values sampled outside the input image are handled by ``self.padding_mode``.
"""
if self.shear is None:
sx = sy = None
@@ -1256,9 +1254,17 @@ class Affine(nn.Module):
sx, sy = self.shear[..., 0], self.shear[..., 1]
batch = input.shape[0] if input.dim() == 4 else 1
- center = _compute_tensor_center(input).expand(batch, -1) if self.center is None else self.center
+ params_batch = self.angle.shape[0]
+ # The default center is the same for every image, so it takes the parameters' batch: a batch-1 parameter set
+ # then warps every image, and B parameter sets warp one image, as with an explicit center.
+ center = _compute_tensor_center(input).expand(params_batch, -1) if self.center is None else self.center
matrix = get_affine_matrix2d(self.translation, center, self.scale_factor, -self.angle, sx=sx, sy=sy)
+ if params_batch not in (batch, 1) and batch != 1:
+ raise ValueError(
+ f"Affine has {params_batch} parameter sets for an input batch of {batch}: the two must match, or one "
+ "of them must be 1."
+ )
return affine(input, matrix[..., :2, :3], self.mode, self.padding_mode, self.align_corners)
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index 2119ca686..319a32615 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -1170,6 +1170,54 @@ class TestAffine2d(BaseTester):
with pytest.raises(DeviceError):
kornia.geometry.transform.Affine(angle=torch.zeros(1, device="meta", dtype=dtype), shear=shear)
+ @staticmethod
+ def _affine_parameters(kind, batch_size, device, dtype):
+ torch.manual_seed(0)
+ if kind == "angle":
+ value = 60.0 * torch.rand(batch_size)
+ elif kind == "scale_factor":
+ value = 1.0 + 0.3 * torch.rand(batch_size, 2)
+ else: # translation in pixels, shear in radians
+ value = 0.3 * torch.rand(batch_size, 2)
+ return {kind: value.to(device, dtype)}
+
+ @pytest.mark.parametrize("kind", ["angle", "translation", "scale_factor", "shear"])
+ @pytest.mark.parametrize("with_center", [False, True])
+ def test_affine_batch1_parameters_warp_every_image_6395(self, device, dtype, kind, with_center):
+ # One parameter set warps every image of a batch, with or without center, as Rotate and Translate do.
+ params = self._affine_parameters(kind, 1, device, dtype)
+ center = torch.tensor([[3.0, 2.0]], device=device, dtype=dtype) if with_center else None
+ torch.manual_seed(1)
+ images = torch.rand(3, 2, 5, 7).to(device, dtype)
+
+ transform = kornia.geometry.transform.Affine(**params, center=center)
+ expected = torch.cat([transform(image[None]) for image in images])
+ self.assert_close(transform(images), expected)
+
+ @pytest.mark.parametrize("unbatched", [False, True])
+ def test_affine_parameter_sets_warp_one_image_without_center_6395(self, device, dtype, unbatched):
+ # Without center, B parameter sets warp one image into (B, C, H, W), as they do with the image centre given.
+ params = self._affine_parameters("angle", 3, device, dtype)
+ params.update(self._affine_parameters("translation", 3, device, dtype))
+ torch.manual_seed(1)
+ image = torch.rand(1, 2, 5, 7).to(device, dtype)
+ image = image[0] if unbatched else image
+ image_centre = torch.tensor([[3.0, 2.0]], device=device, dtype=dtype).expand(3, -1)
+
+ actual = kornia.geometry.transform.Affine(**params)(image)
+ expected = kornia.geometry.transform.Affine(**params, center=image_centre)(image)
+ assert actual.shape == (3, 2, 5, 7)
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("with_center", [False, True])
+ def test_affine_parameter_and_input_batch_mismatch_raises_6395(self, device, dtype, with_center):
+ # Two parameter sets for three images pair in no sensible way: the error names both batch sizes.
+ params = self._affine_parameters("angle", 2, device, dtype)
+ center = torch.tensor([[3.0, 2.0]], device=device, dtype=dtype).expand(2, -1) if with_center else None
+ images = torch.zeros(3, 2, 5, 7, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Affine has 2 parameter sets for an input batch of 3"):
+ kornia.geometry.transform.Affine(**params, center=center)(images)
+
@pytest.mark.parametrize("as_module", [False, True])
def test_convention_shear_raw_factors_5661(self, device, dtype, as_module):
# Both off-diagonal factors act on the original coordinates, about pixel (0, 0).