Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): name the argument in epipolar shape errors; drop runs of spaces from messages (#6456)

Caner Demird3a416059c23
diff --git a/changelog.d/6456.fixed.md b/changelog.d/6456.fixed.md
new file mode 100644
index 000000000..59149beb6
--- /dev/null
+++ b/changelog.d/6456.fixed.md
@@ -0,0 +1 @@
+`normalize_points`, `normalize_transformation`, `run_8point`, `compute_correspond_epilines`, `fundamental_from_essential`, `fundamental_from_projections`, `intrinsics_like`, `projection_from_KRt` and `cross_product_matrix` raise `ShapeError`, naming the argument and the expected shape, instead of a bare `AssertionError` (an `IndexError` for a 0-d `cross_product_matrix` input); `intrinsics_like` raises `ValueCheckError` for a focal length that is zero or negative. `multiply_deg_two_one_poly` raises `ShapeError` when `a` is not `(B, 10)` or `b` is not `(B, 4)`, and batch sizes still broadcast as before: an unbatched input raised an `IndexError` or a `RuntimeError`, and some inputs of other shapes, such as `(2, 4)` and `(2, 10)`, returned a tensor. The length messages of `RandomGaussianIllumination`, `RandomLinearIllumination`, `RandomLinearCornerIllumination` and `RandomSaltAndPepperNoise`, the range messages of `RandomSaltAndPepperNoise` and the different-shapes message of `ImageRegistrator` no longer contain runs of spaces.
diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
index f2a9c8f2c..c72f9f5d4 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
@@ -137,8 +137,8 @@ class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBa
gain = (gain[0], gain[0])
elif len(gain) > 2 or len(gain) <= 0:
raise ValueError(
- "The length of gain must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of gain must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("gain must be a tuple or a float")
@@ -154,8 +154,8 @@ class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBa
center = (center[0], center[0])
elif len(center) > 2 or len(center) <= 0:
raise ValueError(
- "The length of center must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of center must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("center must be a tuple or a float")
@@ -171,8 +171,8 @@ class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBa
sigma = (sigma[0], sigma[0])
elif len(sigma) > 2 or len(sigma) <= 0:
raise ValueError(
- "The length of sigma must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of sigma must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("sigma must be a tuple or a float")
@@ -188,8 +188,8 @@ class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBa
sign = (sign[0], sign[0])
elif len(sign) > 2 or len(sign) <= 0:
raise ValueError(
- "The length of sign must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of sign must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("sign must be a tuple or a float")
diff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.py
index 43900ed53..58f8524e7 100644
--- a/kornia/augmentation/_2d/intensity/linear_illumination.py
+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py
@@ -103,8 +103,8 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
gain = (gain[0], gain[0])
elif len(gain) > 2 or len(gain) <= 0:
raise ValueError(
- "The length of gain must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of gain must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("gain must be a tuple or a float")
@@ -120,8 +120,8 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
sign = (sign[0], sign[0])
elif len(sign) > 2 or len(sign) <= 0:
raise ValueError(
- "The length of sign must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of sign must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("sign must be a tuple or a float")
@@ -223,8 +223,8 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
gain = (gain[0], gain[0])
elif len(gain) > 2 or len(gain) <= 0:
raise ValueError(
- "The length of gain must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of gain must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("gain must be a tuple or a float")
@@ -240,8 +240,8 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
sign = (sign[0], sign[0])
elif len(sign) > 2 or len(sign) <= 0:
raise ValueError(
- "The length of sign must be greater than 0 \
- and less than or equal to 2, and it should be a tuple or a float."
+ "The length of sign must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple or a float."
)
else:
raise ValueError("sign must be a tuple or a float")
diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
index cc03a3b7c..2fe339faf 100644
--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
@@ -107,15 +107,14 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
salt_vs_pepper = (salt_vs_pepper[0], salt_vs_pepper[0])
elif len(salt_vs_pepper) > 2 or len(salt_vs_pepper) <= 0:
raise ValueError(
- "The length of salt_vs_pepper must be greater than 0 \
- and less than or equal to 2, and it should be a tuple."
+ "The length of salt_vs_pepper must be greater than 0 "
+ "and less than or equal to 2, and it should be a tuple."
)
else:
raise ValueError("salt_vs_pepper must be a tuple or a float")
KORNIA_CHECK(
all(0 <= el <= 1 for el in salt_vs_pepper),
- "Salt_vs_pepper values must be between 0 and 1. \
- Recommended value 0.5.",
+ "Salt_vs_pepper values must be between 0 and 1. Recommended value 0.5.",
)
if isinstance(amount, (tuple, float)):
@@ -125,15 +124,13 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
amount = (amount[0], amount[0])
elif len(amount) > 2 or len(amount) <= 0:
raise ValueError(
- "The length of amount must be greater than 0 \
- and less than or equal to 2, and it should be a tuple."
+ "The length of amount must be greater than 0 and less than or equal to 2, and it should be a tuple."
)
else:
raise ValueError("amount must be a tuple or a float")
KORNIA_CHECK(
all(0 <= el <= 1 for el in amount),
- "amount of noise values must be between 0 and 1. \
- Recommended values less than 0.2.",
+ "amount of noise values must be between 0 and 1. Recommended values less than 0.2.",
)
# Generator of random parameters and masks.
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 997308f48..396ab0f12 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -60,10 +60,12 @@ def normalize_points(
:math:`[-1, 1]` by the image size, not by the point statistics.
"""
- if points.ndim != 3:
- raise AssertionError(points.shape)
- if points.shape[-1] != 2:
- raise AssertionError(points.shape)
+ if points.ndim != 3 or points.shape[-1] != 2:
+ raise ShapeError(
+ f"points must have shape (B, N, 2), got {list(points.shape)}.",
+ actual_shape=list(points.shape),
+ expected_shape=["B", "N", "2"],
+ )
B, _N, _ = points.shape
device, dtype = points.device, points.dtype
@@ -72,7 +74,11 @@ def normalize_points(
x_mean = points.mean(dim=1, keepdim=True) # (B,1,2)
else:
if weights.shape != points.shape[:2]:
- raise AssertionError(weights.shape)
+ raise ShapeError(
+ f"weights must have shape (B, N) = {list(points.shape[:2])}, got {list(weights.shape)}.",
+ actual_shape=list(weights.shape),
+ expected_shape=["B", "N"],
+ )
# Accumulate in at least float32: in half precision a sum followed by a division rounds twice where
# ``mean`` rounds once, and uniform weights would then not reproduce the unweighted statistics.
acc_dtype = torch.promote_types(dtype, torch.float32)
@@ -138,7 +144,11 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor
"""
if len(M.shape) < 2:
- raise AssertionError(M.shape)
+ raise ShapeError(
+ f"M must have shape (*, m, n), got {list(M.shape)}.",
+ actual_shape=list(M.shape),
+ expected_shape=["*", "m", "n"],
+ )
norm_val: torch.Tensor = M[..., -1:, -1:]
mask = norm_val.abs() > eps
divisor = torch.where(mask, norm_val, torch.ones_like(norm_val))
@@ -546,11 +556,19 @@ def run_8point(
KORNIA_CHECK_SHAPE(points2, ["B", "N", "2"])
KORNIA_CHECK_SAME_SHAPE(points1, points2)
if points1.shape[1] < 8:
- raise AssertionError(points1.shape)
+ raise ShapeError(
+ f"points1 and points2 must have shape (B, N, 2) with N >= 8, got {list(points1.shape)}.",
+ actual_shape=list(points1.shape),
+ expected_shape=["B", "N >= 8", "2"],
+ )
if weights is not None:
KORNIA_CHECK_SHAPE(weights, ["B", "N"])
- if weights.shape[1] != points1.shape[1]:
- raise AssertionError(weights.shape)
+ if weights.shape != points1.shape[:2]:
+ 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"],
+ )
# 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(points1.dtype)
@@ -698,7 +716,11 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> to
elif points.shape[-1] == 3:
points_h = points
else:
- raise AssertionError(points.shape)
+ raise ShapeError(
+ f"points must have shape (*, N, 2) or (*, N, 3), got {list(points.shape)}.",
+ actual_shape=list(points.shape),
+ expected_shape=["*", "N", "2 or 3"],
+ )
KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])
# project points and retrieve lines components
points_h = torch.transpose(points_h, dim0=-2, dim1=-1)
@@ -853,7 +875,10 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
KORNIA_CHECK_SHAPE(K1, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(K2, ["*", "3", "3"])
if not len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):
- raise AssertionError
+ raise ShapeError(
+ "E_mat, K1 and K2 must have shape (*, 3, 3) with the same number of dimensions, "
+ f"got {list(E_mat.shape)}, {list(K1.shape)} and {list(K2.shape)}."
+ )
K1_inv, valid1 = safe_inverse_with_mask(K1)
K2_inv, valid2 = safe_inverse_with_mask(K2)
@@ -903,7 +928,9 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Te
KORNIA_CHECK_SHAPE(P1, ["*", "3", "4"])
KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])
if P1.shape[:-2] != P2.shape[:-2]:
- raise AssertionError
+ raise ShapeError(
+ f"P1 and P2 must have shape (*, 3, 4) with the same batch shape, got {list(P1.shape)} and {list(P2.shape)}."
+ )
def vstack(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return torch.cat([x, y], dim=-2)
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index bea50c9e3..888ffa48a 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -19,6 +19,8 @@
import torch
+from kornia.core.exceptions import ShapeError
+
def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
r"""Build the skew-symmetric cross-product matrices of 3-vectors with any number of leading dimensions.
@@ -45,8 +47,10 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
vector.
"""
- if not x.shape[-1] == 3:
- raise AssertionError(x.shape)
+ if x.ndim == 0 or x.shape[-1] != 3:
+ raise ShapeError(
+ f"x must have shape (*, 3), got {list(x.shape)}.", actual_shape=list(x.shape), expected_shape=["*", "3"]
+ )
# get vector compononens
x0 = x[..., 0]
x1 = x[..., 1]
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 3f0381fb1..7813c0b51 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -23,6 +23,7 @@ import torch
from torch.linalg import qr as linalg_qr
from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.exceptions import ShapeError, ValueCheckError
from kornia.core.ops import eye_like, vec_like
from kornia.core.utils import _autocast_disabled, _torch_svd_cast
@@ -62,9 +63,13 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
"""
if len(input.shape) != 4:
- raise AssertionError(input.shape)
+ raise ShapeError(
+ f"input must have shape (B, C, H, W), got {list(input.shape)}.",
+ actual_shape=list(input.shape),
+ expected_shape=["B", "C", "H", "W"],
+ )
if focal <= 0:
- raise AssertionError(focal)
+ raise ValueCheckError(f"focal must not be zero or negative, got {focal}", actual_value=focal)
_, _, H, W = input.shape
@@ -179,7 +184,10 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> to
KORNIA_CHECK_SHAPE(R, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["*", "3", "1"])
if not len(K.shape) == len(R.shape) == len(t.shape):
- raise AssertionError
+ raise ShapeError(
+ "K, R and t must have shapes (*, 3, 3), (*, 3, 3) and (*, 3, 1) with the same number of dimensions, "
+ f"got {list(K.shape)}, {list(R.shape)} and {list(t.shape)}."
+ )
Rt = torch.cat([R, t], dim=-1) # 3x4
Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 7c3fab1aa..24f4b5852 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -1466,6 +1466,8 @@ def multiply_deg_two_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
- :func:`determinant_to_polynomial`: the step that follows the elimination of these cubics.
"""
+ KORNIA_CHECK_SHAPE(a, ["B", "10"], "a must have shape (B, 10).")
+ KORNIA_CHECK_SHAPE(b, ["B", "4"], "b must have shape (B, 4).")
global T_deg2 # noqa: PLW0603
if T_deg2.device != a.device or T_deg2.dtype != a.dtype:
T_deg2 = T_deg2.to(device=a.device, dtype=a.dtype)
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 488848d41..ada78f523 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -350,10 +350,7 @@ class ImageRegistrator(nn.Module):
"""Warp img_src into img_dst with transform_model and returns loss."""
# ToDo: Make possible registration of images of different shape
if img_src.shape != img_dst.shape:
- raise ValueError(
- "Cannot register images of different shapes "
- f" {img_src.shape} {img_dst.shape:} "
- )
+ raise ValueError(f"Cannot register images of different shapes {img_src.shape} {img_dst.shape}")
_height, _width = img_dst.shape[-2:]
warper = self.warper(_height, _width)
img_src_to_dst = warper(img_src, transform_model)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 21a00aee2..7e04f396f 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4678,7 +4678,7 @@ class TestRandomSaltAndPepperNoise(BaseTester):
RandomSaltAndPepperNoise(salt_vs_pepper=[0.4, 0.6])
with pytest.raises(
ValueError,
- match=r"The length of salt_vs_pepper must be greater than 0\s+and less than or equal to 2, "
+ match=r"The length of salt_vs_pepper must be greater than 0 and less than or equal to 2, "
r"and it should be a tuple\.",
):
RandomSaltAndPepperNoise(salt_vs_pepper=(0.1, 0.2, 0.3))
@@ -4686,7 +4686,7 @@ class TestRandomSaltAndPepperNoise(BaseTester):
with pytest.raises(
BaseError,
- match=r"Salt_vs_pepper values must be between 0 and 1\.\s+"
+ match=r"Salt_vs_pepper values must be between 0 and 1\. "
r"Recommended value 0\.5\.",
):
RandomSaltAndPepperNoise(salt_vs_pepper=(0.4, 3))
@@ -4694,13 +4694,13 @@ class TestRandomSaltAndPepperNoise(BaseTester):
RandomSaltAndPepperNoise(amount=[0.01, 0.06])
with pytest.raises(
ValueError,
- match=r"The length of amount must be greater than 0\s+and less than or equal to 2, "
+ match=r"The length of amount must be greater than 0 and less than or equal to 2, "
r"and it should be a tuple\.",
):
RandomSaltAndPepperNoise(amount=())
with pytest.raises(
BaseError,
- match=r"amount of noise values must be between 0 and 1\.\s+"
+ match=r"amount of noise values must be between 0 and 1\. "
r"Recommended values less than 0\.2\.",
):
RandomSaltAndPepperNoise(amount=(0.05, 3))
@@ -4908,6 +4908,16 @@ class TestRandomGaussianIllumination(BaseTester):
actual = aug(input_tensor, params=params)
self.assert_close(actual, expected)
+ @pytest.mark.parametrize("param", ["gain", "center", "sigma", "sign"])
+ def test_length_message_6454(self, param, device, dtype):
+ # The message carried a run of spaces from a backslash-continued string literal.
+ with pytest.raises(ValueError) as excinfo:
+ RandomGaussianIllumination(**{param: (0.1, 0.1, 0.1)})
+ assert str(excinfo.value) == (
+ f"The length of {param} must be greater than 0 and less than or equal to 2, "
+ "and it should be a tuple or a float."
+ )
+
class TestRandomLinearIllumination(BaseTester):
def _get_expected(self, device, dtype):
@@ -4974,6 +4984,16 @@ class TestRandomLinearIllumination(BaseTester):
output_tensor = transform(input_tensor)
self.assert_close(output_tensor[0], output_tensor[1])
+ @pytest.mark.parametrize("param", ["gain", "sign"])
+ def test_length_message_6454(self, param, device, dtype):
+ # The message carried a run of spaces from a backslash-continued string literal.
+ with pytest.raises(ValueError) as excinfo:
+ RandomLinearIllumination(**{param: (0.1, 0.1, 0.1)})
+ assert str(excinfo.value) == (
+ f"The length of {param} must be greater than 0 and less than or equal to 2, "
+ "and it should be a tuple or a float."
+ )
+
class TestRandomLinearCornerIllumination(BaseTester):
def _get_expected(self, device, dtype):
@@ -5040,6 +5060,16 @@ class TestRandomLinearCornerIllumination(BaseTester):
output_tensor = transform(input_tensor)
self.assert_close(output_tensor[0], output_tensor[1])
+ @pytest.mark.parametrize("param", ["gain", "sign"])
+ def test_length_message_6454(self, param, device, dtype):
+ # The message carried a run of spaces from a backslash-continued string literal.
+ with pytest.raises(ValueError) as excinfo:
+ RandomLinearCornerIllumination(**{param: (0.1, 0.1, 0.1)})
+ assert str(excinfo.value) == (
+ f"The length of {param} must be greater than 0 and less than or equal to 2, "
+ "and it should be a tuple or a float."
+ )
+
class TestRandomChannelDropout(BaseTester):
def _get_expected(self, device, dtype):
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index d091ee788..d5d3dd4c7 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -93,6 +93,19 @@ class TestNormalizePoints(BaseTester):
points = torch.rand(2, 3, 2, device=device, requires_grad=True, dtype=torch.float64)
self.gradcheck(epi.normalize_points, (points,))
+ @pytest.mark.parametrize("shape", [(5, 2), (1, 5, 3)])
+ def test_wrong_points_shape_raises_6454(self, shape, device, dtype):
+ # Points without the batch dimension or with three coordinates raised a bare AssertionError.
+ points = torch.rand(*shape, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=r"points must have shape \(B, N, 2\), got \["):
+ epi.normalize_points(points)
+
+ def test_wrong_weights_shape_raises_6454(self, device, dtype):
+ points = torch.rand(1, 5, 2, device=device, dtype=dtype)
+ weights = torch.rand(1, 4, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=r"weights must have shape \(B, N\) = \[1, 5\], got \[1, 4\]\."):
+ epi.normalize_points(points, weights=weights)
+
class TestNormalizeTransformation(BaseTester):
def test_smoke(self, device, dtype):
@@ -127,6 +140,11 @@ class TestNormalizeTransformation(BaseTester):
trans = torch.rand(2, 3, 3, device=device, requires_grad=True, dtype=torch.float64)
self.gradcheck(epi.normalize_transformation, (trans,))
+ def test_vector_raises_6454(self, device, dtype):
+ # A tensor with fewer than two dimensions raised a bare AssertionError.
+ with pytest.raises(ShapeError, match=r"M must have shape \(\*, m, n\), got \[3\]\."):
+ epi.normalize_transformation(torch.rand(3, device=device, dtype=dtype))
+
class TestFindFundamental(BaseTester):
def test_smoke(self, device, dtype):
@@ -367,6 +385,17 @@ class TestFindFundamental(BaseTester):
assert grads[1][0, 3].abs() > 1e-3 # control: the dropped match moves F, so a zero gradient would be wrong
self.assert_close(grads[0], grads[1], **tol)
+ def test_run_8point_wrong_sizes_raise_6454(self, device, dtype):
+ # Fewer than 8 points, or weights of another shape, raised a bare AssertionError.
+ points = torch.rand(1, 7, 2, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=r"points1 and points2 must have shape \(B, N, 2\) with N >= 8, got"):
+ fundamental_module.run_8point(points, points)
+ points = torch.rand(1, 8, 2, device=device, dtype=dtype)
+ for weights_shape in [(1, 9), (3, 8)]:
+ weights = torch.rand(*weights_shape, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=r"weights must have shape \(B, N\) = \[1, 8\], got \["):
+ fundamental_module.run_8point(points, points, weights)
+
class TestFundamentalAutocast(BaseTester):
@pytest.mark.parametrize(
@@ -501,6 +530,18 @@ class TestComputeCorrespondEpilines(BaseTester):
F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
self.gradcheck(epi.compute_correspond_epilines, (point, F_mat), requires_grad=(True, False))
+ @pytest.mark.parametrize("shape", [(1, 5, 4), (5, 1)])
+ def test_wrong_points_width_raises_6454(self, shape, device, dtype):
+ # A last dimension other than 2 or 3 raised a bare AssertionError, batched or not.
+ F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ points = torch.rand(*shape, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=r"points must have shape \(\*, N, 2\) or \(\*, N, 3\), got \["):
+ epi.compute_correspond_epilines(points, F_mat)
+ # get_closest_point_on_epipolar_line passes pts1 straight here.
+ pts2 = torch.rand(1, 5, 2, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=r"points must have shape \(\*, N, 2\) or \(\*, N, 3\), got \["):
+ epi.get_closest_point_on_epipolar_line(points, pts2, F_mat)
+
class TestFundamentlFromEssential(BaseTester):
def test_smoke(self, device, dtype):
@@ -557,6 +598,17 @@ class TestFundamentlFromEssential(BaseTester):
K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
self.gradcheck(epi.fundamental_from_essential, (E_mat, K1, K2), requires_grad=(True, False, False))
+ def test_mismatched_dimensions_raise_6454(self, device, dtype):
+ # A different number of batch dimensions raised an AssertionError without a message.
+ E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ K = torch.rand(3, 3, device=device, dtype=dtype)
+ with pytest.raises(
+ ShapeError,
+ match=r"E_mat, K1 and K2 must have shape \(\*, 3, 3\) with the same number of dimensions, "
+ r"got \[1, 3, 3\], \[3, 3\] and \[1, 3, 3\]\.",
+ ):
+ epi.fundamental_from_essential(E_mat, K, E_mat)
+
class TestFundamentalFromProjections(BaseTester):
def test_smoke(self, device, dtype):
@@ -661,6 +713,17 @@ class TestFundamentalFromProjections(BaseTester):
F = epi.fundamental_from_projections(P1, P2)
self.assert_close(F_batch[0], F[0])
+ def test_mismatched_batch_shapes_raise_6454(self, device, dtype):
+ # Different batch shapes raised an AssertionError without a message.
+ P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ P2 = torch.rand(2, 3, 4, device=device, dtype=dtype)
+ with pytest.raises(
+ ShapeError,
+ match=r"P1 and P2 must have shape \(\*, 3, 4\) with the same batch shape, "
+ r"got \[1, 3, 4\] and \[2, 3, 4\]\.",
+ ):
+ epi.fundamental_from_projections(P1, P2)
+
class TestPerpendicular(BaseTester):
def test_shape(self, device, dtype):
diff --git a/tests/geometry/epipolar/test_numeric.py b/tests/geometry/epipolar/test_numeric.py
index 95ead8115..f21a4a48d 100644
--- a/tests/geometry/epipolar/test_numeric.py
+++ b/tests/geometry/epipolar/test_numeric.py
@@ -20,6 +20,7 @@ import torch
import kornia
import kornia.geometry.epipolar as epi
+from kornia.core.exceptions import ShapeError
from testing.base import BaseTester
from testing.two_view import two_view_scene
@@ -73,6 +74,12 @@ class TestSkewSymmetric(BaseTester):
vec = torch.ones(2, 3, device=device, requires_grad=True, dtype=torch.float64)
assert self.gradcheck(epi.cross_product_matrix, (vec,), raise_exception=True, fast_mode=True)
+ @pytest.mark.parametrize("shape", [(1, 4), ()])
+ def test_wrong_last_dim_raises_6454(self, shape, device, dtype):
+ # A last dimension other than 3 raised a bare AssertionError, and a 0-d tensor an IndexError.
+ with pytest.raises(ShapeError, match=r"x must have shape \(\*, 3\), got \["):
+ epi.cross_product_matrix(torch.rand(shape, device=device, dtype=dtype))
+
class TestEyeLike:
def test_smoke(self, device, dtype):
diff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.py
index fc3acb4aa..7a9019b87 100644
--- a/tests/geometry/epipolar/test_projection.py
+++ b/tests/geometry/epipolar/test_projection.py
@@ -15,12 +15,14 @@
# limitations under the License.
#
+import re
+
import pytest
import torch
from torch.autograd import gradcheck
import kornia.geometry.epipolar as epi
-from kornia.core.exceptions import ShapeError
+from kornia.core.exceptions import ShapeError, ValueCheckError
from kornia.geometry.camera import PinholeCamera
from testing.base import BaseTester
@@ -44,6 +46,17 @@ class TestIntrinsicsLike:
assert camera_matrix.device == image.device
assert camera_matrix.dtype == image.dtype
+ def test_wrong_input_shape_raises_6454(self, device, dtype):
+ # An input that is not 4-D raised a bare AssertionError.
+ with pytest.raises(ShapeError, match=r"input must have shape \(B, C, H, W\), got \[3, 4, 5\]\."):
+ epi.intrinsics_like(1.0, torch.rand(3, 4, 5, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("focal", [0.0, -1.0])
+ def test_nonpositive_focal_raises_6454(self, focal, device, dtype):
+ # A zero or negative focal length raised a bare AssertionError; it is a value, not a shape.
+ with pytest.raises(ValueCheckError, match=re.escape(f"focal must not be zero or negative, got {focal}")):
+ epi.intrinsics_like(focal, torch.rand(1, 3, 4, 5, device=device, dtype=dtype))
+
class TestScaleIntrinsics(BaseTester):
def test_smoke_float(self, device, dtype):
@@ -323,7 +336,7 @@ class TestConventionProjection(BaseTester):
self.assert_close(Pb[:1], torch.cat([K1, torch.zeros_like(t)], -1))
self.assert_close(Pb[1:], P)
# K, R and t must have the same number of dimensions.
- with pytest.raises(AssertionError):
+ with pytest.raises(ShapeError, match=r"K, R and t must have shapes .* with the same number of dimensions, got"):
epi.projection_from_KRt(K2[0], R, t)
def test_convention_krt_from_projection_returns_extrinsic_t(self, device, dtype):
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index c7c7a6156..7d1e926f3 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -698,6 +698,26 @@ class TestMultiplyDegTwoOnePoly(BaseTester):
result = solver.multiply_deg_two_one_poly(a, b)
self.assert_close(result, expected, rtol=1e-4, atol=1e-4)
+ @pytest.mark.parametrize(
+ "a_shape, b_shape, message",
+ [
+ ((10,), (4,), r"a must have shape \(B, 10\)"),
+ ((1, 10), (4,), r"b must have shape \(B, 4\)"),
+ ((1, 2, 10), (1, 2, 4), r"a must have shape \(B, 10\)"),
+ ((2, 4), (2, 10), r"a must have shape \(B, 10\)"),
+ ((2, 8), (2, 5), r"a must have shape \(B, 10\)"),
+ ((2, 10), (2, 5), r"b must have shape \(B, 4\)"),
+ ],
+ ids=["unbatched_a", "unbatched_b", "extra_dim", "swapped", "other_product_40", "b_width"],
+ )
+ def test_wrong_shape_raises_6454(self, a_shape, b_shape, message, device, dtype):
+ # An unbatched a failed in unsqueeze(2) with an IndexError and an unbatched b with a RuntimeError; sizes whose
+ # product is 40 returned a (B, 20) tensor, as only the product of the last two sizes was used.
+ a = torch.rand(*a_shape, device=device, dtype=dtype)
+ b = torch.rand(*b_shape, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match=message):
+ solver.multiply_deg_two_one_poly(a, b)
+
class TestDeterminantToPolynomial(BaseTester):
def test_smoke(self, device, dtype):
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index ddd1fcb8e..ce45b4e24 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -367,6 +367,17 @@ class TestImageRegistrator(BaseTester):
ir.register(scene(0.0), scene(6.0))
assert abs(ir.model.rot.item() + 6.0) < 0.4
+ def test_different_shapes_message_6454(self, device, dtype):
+ # The message carried a run of spaces from its string literal.
+ ir = ImageRegistrator("similarity").to(device, dtype)
+ src = torch.rand(1, 1, 8, 8, device=device, dtype=dtype)
+ dst = torch.rand(1, 1, 6, 6, device=device, dtype=dtype)
+ with pytest.raises(ValueError) as excinfo:
+ ir.get_single_level_loss(src, dst, ir.model())
+ assert str(excinfo.value) == (
+ "Cannot register images of different shapes torch.Size([1, 1, 8, 8]) torch.Size([1, 1, 6, 6])"
+ )
+
class TestConventionsImageRegistrator(BaseTester):
height, width = 32, 48