Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix cross_product_matrix batch dimensionality (#1530)

nitaifingerhut210f20f3413a
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index 487419111..011df8a6e 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -7,13 +7,13 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
r"""Return the cross_product_matrix symmetric matrix of a vector.
Args:
- x: The input vector to construct the matrix in the shape :math:`(B, 3)`.
+ x: The input vector to construct the matrix in the shape :math:`(*, 3)`.
Returns:
- The constructed cross_product_matrix symmetric matrix with shape :math:`(B, 3, 3)`.
+ The constructed cross_product_matrix symmetric matrix with shape :math:`(*, 3, 3)`.
"""
- if not (len(x.shape) == 2 and x.shape[1] == 3):
+ if not x.shape[-1] == 3:
raise AssertionError(x.shape)
# get vector compononens
x0 = x[..., 0]
@@ -23,4 +23,5 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
# construct the matrix, reshape to 3x3 and return
zeros = torch.zeros_like(x0)
cross_product_matrix_flat = torch.stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)
- return cross_product_matrix_flat.view(-1, 3, 3)
+ shape_ = x.shape[:-1] + (3, 3)
+ return cross_product_matrix_flat.view(*shape_)
diff --git a/test/geometry/epipolar/test_numeric.py b/test/geometry/epipolar/test_numeric.py
index ed02d8dc6..61d55f5be 100644
--- a/test/geometry/epipolar/test_numeric.py
+++ b/test/geometry/epipolar/test_numeric.py
@@ -20,6 +20,30 @@ class TestSkewSymmetric:
cross_product_matrix = epi.cross_product_matrix(vec)
assert cross_product_matrix.shape == (B, 3, 3)
+ @pytest.mark.parametrize("shapes", [(1, 1), (1, 5), (2, 1), (2, 5), (4, 1), (4, 5)])
+ def test_shapes(self, device, dtype, shapes):
+ input_shape = shapes + (3, )
+ output_shape = shapes + (3, 3)
+ t = torch.rand(*input_shape, device=device, dtype=dtype)
+ cross_product_matrix = epi.cross_product_matrix(t)
+ assert cross_product_matrix.shape == output_shape
+
+ @pytest.mark.parametrize("shapes", [(1, 1), (1, 5), (2, 1), (2, 5), (4, 1), (4, 5)])
+ def test_funcional_shapes(self, device, dtype, shapes):
+ input_shape = shapes + (3, )
+ t = torch.rand(*input_shape, device=device, dtype=dtype)
+
+ # Feed batches
+ cross_product_matrices = []
+ for i in range(t.shape[1]):
+ cross_product_matrices.append(epi.cross_product_matrix(t[:, i, ...]))
+ cross_product_matrix_parts = torch.stack(cross_product_matrices, dim=1)
+
+ # Feed one-shot
+ cross_product_matrix_whole = epi.cross_product_matrix(t)
+
+ assert_close(cross_product_matrix_parts, cross_product_matrix_whole)
+
def test_mean_std(self, device, dtype):
vec = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
cross_product_matrix = epi.cross_product_matrix(vec)