Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): support symmetric broadcasting in compose_transformations and relative_transformation (#4933) (#4946)

yi1114cc4a29a036b
diff --git a/changelog.d/4946.fixed.md b/changelog.d/4946.fixed.md
new file mode 100644
index 000000000..e26f96192
--- /dev/null
+++ b/changelog.d/4946.fixed.md
@@ -0,0 +1,4 @@
+`compose_transformations` and `relative_transformation` now broadcast a batch of one against a batch of `N` in
+either argument. Before, a `(1, 4, 4)` first argument with an `(N, 4, 4)` second argument raised a torch
+`RuntimeError`, while the reverse order worked. Batches of two different sizes other than one now raise a
+`ValueError` instead of a torch `RuntimeError`. Fixes #4933.
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index f9f8df384..c76d90246 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -48,7 +48,8 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> t
shape of :math:`(N, 4, 4)` or :math:`(4, 4)`.
trans_12: tensor with the homogeneous transformation from
a reference frame 2 respect to a frame 1. The tensor has must have a
- shape of :math:`(N, 4, 4)` or :math:`(4, 4)`.
+ shape of :math:`(N, 4, 4)` or :math:`(4, 4)`. A batch of one broadcasts against a batch of
+ :math:`N` in either argument.
Returns:
the transformation between the two frames with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.
@@ -71,6 +72,11 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> t
if trans_01.dim() != trans_12.dim():
raise ValueError(f"Input number of dims must match. Got {trans_01.dim()} and {trans_12.dim()}")
+ try:
+ batch_shape = torch.broadcast_shapes(trans_01.shape[:-2], trans_12.shape[:-2])
+ except RuntimeError as err:
+ raise ValueError(f"Incompatible batch shapes: {trans_01.shape} and {trans_12.shape}") from err
+
# unpack input data
rmat_01 = trans_01[..., :3, :3]
rmat_12 = trans_12[..., :3, :3]
@@ -81,7 +87,7 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> t
rmat_02 = torch.matmul(rmat_01, rmat_12)
tvec_02 = torch.matmul(rmat_01, tvec_12) + tvec_01
- trans_02 = trans_01.new_zeros(trans_01.shape)
+ trans_02 = trans_01.new_zeros(batch_shape + (4, 4))
trans_02[..., :3, :3] = rmat_02
trans_02[..., :3, 3:] = tvec_02
trans_02[..., 3, 3] = 1.0
@@ -145,7 +151,8 @@ def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> t
Args:
trans_01: reference transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.
- trans_02: destination transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.
+ trans_02: destination transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`. A batch
+ of one broadcasts against a batch of :math:`N` in either argument.
Returns:
the relative transformation between the transformations with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.
@@ -165,6 +172,11 @@ def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> t
if not trans_01.dim() == trans_02.dim():
raise ValueError(f"Input number of dims must match. Got {trans_01.dim()} and {trans_02.dim()}")
+ try:
+ batch_shape = torch.broadcast_shapes(trans_01.shape[:-2], trans_02.shape[:-2])
+ except RuntimeError as err:
+ raise ValueError(f"Incompatible batch shapes: {trans_01.shape} and {trans_02.shape}") from err
+
rmat_01 = trans_01[..., :3, :3]
tvec_01 = trans_01[..., :3, 3:4]
rmat_02 = trans_02[..., :3, :3]
@@ -172,7 +184,7 @@ def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> t
rmat_10 = rmat_01.transpose(-1, -2)
rmat_12 = torch.matmul(rmat_10, rmat_02)
tvec_12 = torch.matmul(rmat_10, tvec_02 - tvec_01)
- trans_12 = torch.zeros_like(trans_01)
+ trans_12 = trans_01.new_zeros(batch_shape + (4, 4))
trans_12[..., :3, :3] = rmat_12
trans_12[..., :3, 3:4] = tvec_12
trans_12[..., 3, 3] = 1.0
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index f11a68243..d6bce6b39 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -27,6 +27,15 @@ from testing.geometry.create import create_random_homography
from testing.geometry.linalg import euler_angles_to_rotation_matrix, identity_matrix
+def _rigid_transforms(batch_size, device, dtype):
+ """Distinct, non-identity rigid transforms, so a swapped or dropped operand changes the result."""
+ angles = torch.linspace(0.1, 0.9, batch_size, device=device, dtype=dtype)
+ # the helper returns homogeneous (4, 4) rotations
+ trans = euler_angles_to_rotation_matrix(angles, 2 * angles, -angles).reshape(batch_size, 4, 4).clone()
+ trans[:, :3, 3] = torch.stack([angles, 1 - angles, 2 * angles], dim=-1)
+ return trans
+
+
class TestTransformPoints(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@pytest.mark.parametrize("num_points", [2, 3, 5])
@@ -176,6 +185,23 @@ class TestComposeTransforms(BaseTester):
self.gradcheck(kgl.compose_transformations, (trans_01, trans_12))
+ def test_broadcast(self, device, dtype):
+ # Broadcasting batch size 1 against B in both directions (#4933)
+ A = _rigid_transforms(1, device=device, dtype=dtype)
+ B = _rigid_transforms(3, device=device, dtype=dtype)
+ out_ab = kgl.compose_transformations(A, B)
+ out_ba = kgl.compose_transformations(B, A)
+ assert out_ab.shape == (3, 4, 4)
+ assert out_ba.shape == (3, 4, 4)
+ self.assert_close(out_ab, A @ B)
+ self.assert_close(out_ba, B @ A)
+
+ def test_mismatched_batch_exception(self, device, dtype):
+ A = identity_matrix(batch_size=2, device=device, dtype=dtype)
+ B = identity_matrix(batch_size=3, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Incompatible batch shapes"):
+ kgl.compose_transformations(A, B)
+
class TestInverseTransformation(BaseTester):
def test_smoke(self, device, dtype):
@@ -315,6 +341,23 @@ class TestRelativeTransformation(BaseTester):
self.gradcheck(kgl.relative_transformation, (trans_01, trans_02))
+ def test_broadcast(self, device, dtype):
+ # Broadcasting batch size 1 against B in both directions (#4933)
+ A = _rigid_transforms(1, device=device, dtype=dtype)
+ B = _rigid_transforms(3, device=device, dtype=dtype)
+ out_ab = kgl.relative_transformation(A, B)
+ out_ba = kgl.relative_transformation(B, A)
+ assert out_ab.shape == (3, 4, 4)
+ assert out_ba.shape == (3, 4, 4)
+ self.assert_close(out_ab, kgl.inverse_transformation(A) @ B)
+ self.assert_close(out_ba, kgl.inverse_transformation(B) @ A)
+
+ def test_mismatched_batch_exception(self, device, dtype):
+ A = identity_matrix(batch_size=2, device=device, dtype=dtype)
+ B = identity_matrix(batch_size=3, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Incompatible batch shapes"):
+ kgl.relative_transformation(A, B)
+
class TestPointsLinesDistances(BaseTester):
def test_smoke(self, device, dtype):