Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): raise ShapeError for homography shape checks; drop the run of spaces from Similarity repr (#6504)

Caner Demirc940fc862c79
diff --git a/changelog.d/6504.fixed.md b/changelog.d/6504.fixed.md
new file mode 100644
index 000000000..9ec8ba8f7
--- /dev/null
+++ b/changelog.d/6504.fixed.md
@@ -0,0 +1 @@
+`find_homography_dlt`, `find_homography_dlt_iterated`, `find_homography_lines_dlt`, `find_homography_lines_dlt_iterated` and `sample_is_valid_for_homography` raise `ShapeError`, naming the argument and the expected shape, instead of a bare `AssertionError` (in the first two, an `IndexError` for 0-d or 1-D points of the same shape). Fewer than four segments in `find_homography_lines_dlt` and `find_homography_lines_dlt_iterated` also raise `ShapeError` instead of `AssertionError`, as fewer than four points in `find_homography_dlt` now do. The `repr` of `Similarity` no longer has a run of spaces after the angle.
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 5fe76b2fa..ab7ad50e7 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -51,6 +51,7 @@ from typing import Optional, Tuple, Union
import torch
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.exceptions import ShapeError
from kornia.core.utils import (
_autocast_disabled,
_extract_device_dtype,
@@ -683,14 +684,26 @@ def _homography_dlt_system(
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Build the weighted-normalized DLT design matrix and its two normalizing transforms."""
if points1.shape != points2.shape:
- raise AssertionError(points1.shape)
- if points1.shape[1] < 4:
- raise AssertionError(points1.shape)
+ raise ShapeError(
+ f"points1 and points2 must have the same shape, got {list(points1.shape)} and {list(points2.shape)}.",
+ actual_shape=list(points1.shape),
+ expected_shape=list(points2.shape),
+ )
+ if points1.ndim != 3 or points1.shape[1] < 4:
+ raise ShapeError(
+ f"points1 and points2 must have shape (B, N, 2) with N >= 4, got {list(points1.shape)}.",
+ actual_shape=list(points1.shape),
+ expected_shape=["B", "N >= 4", "2"],
+ )
KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])
KORNIA_CHECK_SHAPE(points2, ["B", "N", "2"])
if weights is not None and weights.shape != points1.shape[:2]:
- raise AssertionError(weights.shape)
+ raise ShapeError(
+ f"weights must have shape (B, N) = {list(points1.shape[:2])}, got {list(weights.shape)}.",
+ actual_shape=list(weights.shape),
+ expected_shape=["B", "N"],
+ )
points1_norm, transform1 = normalize_points(points1, weights=weights)
points2_norm, transform2 = normalize_points(points2, weights=weights)
@@ -769,7 +782,11 @@ def _homography_from_dlt_system(
else:
# We should use provided weights
if not (len(weights.shape) == 2 and weights.shape == (A.shape[0], num_points)):
- raise AssertionError(weights.shape)
+ raise ShapeError(
+ f"weights must have shape (B, N) = {[A.shape[0], num_points]}, got {list(weights.shape)}.",
+ actual_shape=list(weights.shape),
+ expected_shape=["B", "N"],
+ )
w_full = weights.repeat_interleave(2, dim=1).unsqueeze(1)
# Only the minimal four-point LU path works from the design matrix itself (see below).
@@ -929,7 +946,11 @@ def sample_is_valid_for_homography(points1: torch.Tensor, points2: torch.Tensor)
"""
if points1.shape != points2.shape:
- raise AssertionError(points1.shape)
+ raise ShapeError(
+ f"points1 and points2 must have the same shape, got {list(points1.shape)} and {list(points2.shape)}.",
+ actual_shape=list(points1.shape),
+ expected_shape=list(points2.shape),
+ )
# Triples to test: (0,1,2), (0,1,3), (0,2,3), (1,2,3), gathered by slicing, shape (B, 4, 2). Index tensors
# would be copied to the device on every call.
@@ -989,7 +1010,7 @@ def find_homography_lines_dlt(
finite system, the whole batch is NaN and a ``RuntimeWarning`` is issued.
Raises:
- AssertionError: if fewer than four segments are given, as in :func:`find_homography_dlt`.
+ ShapeError: if fewer than four segments are given, as in :func:`find_homography_dlt`.
See Also:
- :func:`find_homography_dlt`: a homography from point correspondences.
@@ -1010,7 +1031,7 @@ def find_homography_lines_dlt(
# Fewer segments leave the DLT system under-determined: its null space then holds an arbitrary
# homography, or NaN for none at all (#5991).
if N < 4:
- raise AssertionError(f"find_homography_lines_dlt needs at least 4 line segments, got {N}: {ls1.shape}")
+ raise ShapeError(f"find_homography_lines_dlt needs at least 4 line segments, got {N}: {ls1.shape}")
# Raises unless both segment sets share a device and a dtype.
_extract_device_dtype([ls1, ls2])
@@ -1018,7 +1039,11 @@ def find_homography_lines_dlt(
points2 = ls2.reshape(BS, 2 * N, 2)
if weights is not None and weights.shape != ls1.shape[:2]:
- raise AssertionError(weights.shape)
+ raise ShapeError(
+ f"weights must have shape (B, N) = {list(ls1.shape[:2])}, got {list(weights.shape)}.",
+ actual_shape=list(weights.shape),
+ expected_shape=["B", "N"],
+ )
# Weights take the points' dtype, as a caller's autocast used to cast them; mixed dtypes now fit outside it too.
if weights is not None:
weights = weights.to(ls1.dtype)
@@ -1056,7 +1081,11 @@ def find_homography_lines_dlt(
else:
# We should use provided weights
if not ((len(weights.shape) == 2) and (weights.shape == ls1.shape[:2])):
- raise AssertionError(weights.shape)
+ raise ShapeError(
+ f"weights must have shape (B, N) = {list(ls1.shape[:2])}, got {list(weights.shape)}.",
+ actual_shape=list(weights.shape),
+ expected_shape=["B", "N"],
+ )
# Scale each segment's two design rows by its weight instead of materializing the
# (B, 2N, 2N) diagonal weight matrix, whose storage grows quadratically with N.
w_full = weights.repeat_interleave(2, dim=1).unsqueeze(1)
@@ -1100,7 +1129,7 @@ def find_homography_lines_dlt_iterated(
solves is, as in :func:`find_homography_lines_dlt`.
Raises:
- AssertionError: if fewer than four segments are given, as in :func:`find_homography_lines_dlt`.
+ ShapeError: if fewer than four segments are given, as in :func:`find_homography_lines_dlt`.
See Also:
- :func:`find_homography_lines_dlt`: a single weighted solve.
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index ada78f523..fe2077dfc 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -194,9 +194,7 @@ class Similarity(BaseModel):
self.reset_model()
def __repr__(self) -> str:
- return (
- f"{self.__class__.__name__}(angle = {self.rot}, \n shift={self.shift}, \n scale={self.scale})"
- )
+ return f"{self.__class__.__name__}(angle = {self.rot},\n shift={self.shift}, \n scale={self.scale})"
def reset_model(self) -> None:
"""Initialize the model with identity transform."""
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 48a2be58c..615845493 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import re
import sys
import pytest
@@ -87,6 +88,13 @@ class TestSampleValidation(BaseTester):
mask = sample_is_valid_for_homography(pts1, pts2)
assert mask.shape == torch.Size([batch_size])
+ def test_exception(self, device, dtype):
+ pts1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ pts2 = torch.rand(1, 5, 2, device=device, dtype=dtype)
+ message = "points1 and points2 must have the same shape, got [1, 4, 2] and [1, 5, 2]."
+ with pytest.raises(ShapeError, match=re.escape(message)):
+ sample_is_valid_for_homography(pts1, pts2)
+
class TestOneWayError(BaseTester):
def test_smoke(self, device, dtype):
@@ -838,6 +846,36 @@ class TestFindHomographyDLT(BaseTester):
H = find_homography_dlt(points1, points2, None)
assert H.shape == (B, 3, 3)
+ @pytest.mark.parametrize("solver", [find_homography_dlt, find_homography_dlt_iterated])
+ def test_shape_errors_name_the_argument(self, solver, device, dtype):
+ points = torch.rand(2, 5, 2, device=device, dtype=dtype)
+ other = torch.rand(2, 6, 2, device=device, dtype=dtype)
+ message = "points1 and points2 must have the same shape, got [2, 5, 2] and [2, 6, 2]."
+ with pytest.raises(ShapeError, match=re.escape(message)):
+ solver(points, other, None)
+ # One input per claim of "(B, N, 2) with N >= 4": no batch axis, 0-d, 1-D and 4-D inputs and too few points get
+ # this message; a last size of 3 is rejected by the KORNIA_CHECK_SHAPE that follows.
+ for shape in [(5, 2), (), (8,), (1, 5, 2, 2), (2, 3, 2)]:
+ bad = torch.rand(shape, device=device, dtype=dtype)
+ message = f"points1 and points2 must have shape (B, N, 2) with N >= 4, got {list(shape)}."
+ with pytest.raises(ShapeError, match=re.escape(message)):
+ solver(bad, bad, None)
+ bad = torch.rand(2, 5, 3, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ solver(bad, bad, None)
+ for shape in [(2, 4), (5,)]:
+ weights = torch.ones(shape, device=device, dtype=dtype)
+ message = f"weights must have shape (B, N) = [2, 5], got {list(shape)}."
+ with pytest.raises(ShapeError, match=re.escape(message)):
+ solver(points, points, weights)
+
+ def test_dlt_system_weights_shape_error(self, device, dtype):
+ A = torch.rand(1, 10, 9, device=device, dtype=dtype)
+ eye = torch.eye(3, device=device, dtype=dtype)[None]
+ weights = torch.ones(1, 4, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=re.escape("weights must have shape (B, N) = [1, 5], got [1, 4].")):
+ _homography_from_dlt_system(A, weights, eye, eye, "lu", torch.device(device), dtype)
+
@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
@@ -1131,6 +1169,15 @@ class TestFindHomographyFromLinesDLT(BaseTester):
H = find_homography_lines_dlt(ls1, ls2, None)
assert H.shape == (B, 3, 3)
+ @pytest.mark.parametrize("solver", [find_homography_lines_dlt, find_homography_lines_dlt_iterated])
+ def test_weights_shape_error(self, solver, device, dtype):
+ ls = torch.rand(2, 5, 2, 2, device=device, dtype=dtype)
+ for shape in [(2, 4), (5,)]:
+ weights = torch.ones(shape, device=device, dtype=dtype)
+ message = f"weights must have shape (B, N) = [2, 5], got {list(shape)}."
+ with pytest.raises(ShapeError, match=re.escape(message)):
+ solver(ls, ls, weights)
+
@pytest.mark.parametrize("num_segments", [0, 1, 2, 3])
@pytest.mark.parametrize("batched", [True, False])
@pytest.mark.parametrize("solver", [find_homography_lines_dlt, find_homography_lines_dlt_iterated])
@@ -1143,9 +1190,9 @@ class TestFindHomographyFromLinesDLT(BaseTester):
ls2 = torch.rand(shape, device=device, dtype=dtype)
weights = torch.ones(2 if batched else 1, num_segments, device=device, dtype=dtype)
- with pytest.raises(AssertionError, match=f"needs at least 4 line segments, got {num_segments}"):
+ with pytest.raises(ShapeError, match=f"needs at least 4 line segments, got {num_segments}"):
solver(ls1, ls2, weights)
- with pytest.raises(AssertionError):
+ with pytest.raises(ShapeError):
find_homography_dlt(ls1.reshape(1, -1, 2)[:, :num_segments], ls2.reshape(1, -1, 2)[:, :num_segments])
def test_four_segments_recover_the_homography_5991(self, device, dtype):
@@ -1649,7 +1696,7 @@ class TestConventionHomography(BaseTester):
# Relabelling the images returns the inverse.
self.assert_close(find_homography_dlt(p2, p1), _inverse(H_true), rtol=1e-4, atol=1e-4)
# Four or more correspondences: three are rejected before any solve.
- with pytest.raises(AssertionError):
+ with pytest.raises(ShapeError):
find_homography_dlt(p1[:, :3], p2[:, :3])
def test_convention_find_homography_dlt_lu_equals_svd(self, device, dtype):
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index ce45b4e24..462ff3137 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -58,6 +58,9 @@ class TestSimilarity(BaseTester):
for r, sc, sh in zip([True, False], [True, False], [True, False]):
s = kornia.geometry.transform.Similarity(r, sc, sh).to(device, dtype)
assert s is not None
+ text = repr(s)
+ assert text.startswith("Similarity(angle = ")
+ assert ",\n shift=" in text
@pytest.mark.parametrize(
"height, width, expected",