Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): accept an empty batch in find_homography_lines_dlt (#5976)

Saksham Sharmab99ddce41673
diff --git a/changelog.d/5976.fixed.md b/changelog.d/5976.fixed.md
new file mode 100644
index 000000000..f26d3ee2e
--- /dev/null
+++ b/changelog.d/5976.fixed.md
@@ -0,0 +1 @@
+`find_homography_lines_dlt` and `find_homography_lines_dlt_iterated` return an empty `(0, 3, 3)` batch for an empty batch of line segments, as `find_homography_dlt` does, instead of raising a `reshape` error.
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 0ccd92683..ccdb742ce 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -832,7 +832,8 @@ def find_homography_lines_dlt(
# http://diis.unizar.es/biblioteca/00/09/000902.pdf
ax = torch.cat([A * xs1, A * ys1, A, B * xs1, B * ys1, B, C * xs1, C * ys1, C], dim=-1)
ay = torch.cat([A * xe1, A * ye1, A, B * xe1, B * ye1, B, C * xe1, C * ye1, C], dim=-1)
- A = torch.cat((ax, ay), dim=-1).reshape(ax.shape[0], -1, ax.shape[-1])
+ # The row count is spelled out: a ``-1`` cannot be inferred for an empty batch.
+ A = torch.cat((ax, ay), dim=-1).reshape(BS, 2 * N, ax.shape[-1])
if weights is None:
# All points are equally important
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index dbb74bf8b..154f028e9 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -894,6 +894,24 @@ class TestFindHomographyFromLinesDLT(BaseTester):
H = find_homography_lines_dlt(ls1, ls2, None)
assert H.shape == (B, 3, 3)
+ @pytest.mark.parametrize("num_points", [0, 4])
+ @pytest.mark.parametrize("use_weights", [False, True])
+ @pytest.mark.parametrize("solver", [find_homography_lines_dlt, find_homography_lines_dlt_iterated])
+ def test_empty_batch(self, num_points, use_weights, solver, device, dtype):
+ # An empty batch gives an empty batch of homographies, as find_homography_dlt does.
+ ls1 = torch.rand(0, num_points, 2, 2, device=device, dtype=dtype, requires_grad=True)
+ ls2 = torch.rand(0, num_points, 2, 2, device=device, dtype=dtype)
+ weights = torch.ones(0, num_points, device=device, dtype=dtype) if use_weights else None
+
+ H = solver(ls1, ls2, weights)
+
+ assert H.shape == (0, 3, 3)
+ assert H.dtype == dtype
+ assert H.device == ls1.device
+ H.sum().backward()
+ assert ls1.grad is not None
+ assert ls1.grad.shape == ls1.shape
+
@pytest.mark.parametrize("batch_size, num_points", [(1, 4), (2, 5), (3, 6)])
def test_points_noweights(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points