Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): exclude zero-weight matches from Hartley normalization (#4908)

llllgt73ec30977096
diff --git a/changelog.d/4908.added.md b/changelog.d/4908.added.md
new file mode 100644
index 000000000..0dff67fe0
--- /dev/null
+++ b/changelog.d/4908.added.md
@@ -0,0 +1,3 @@
+`normalize_points` accepts optional per-point `weights` of shape `(B, N)`: the centroid and the mean radius are
+weighted, negative weights count as zero, and a batch element whose weights are all zero uses the unweighted
+statistics.
diff --git a/changelog.d/4908.breaking.md b/changelog.d/4908.breaking.md
new file mode 100644
index 000000000..f59e865c1
--- /dev/null
+++ b/changelog.d/4908.breaking.md
@@ -0,0 +1,8 @@
+`find_fundamental` (`method="8POINT"`), `find_homography_dlt` and `find_homography_lines_dlt` now compute the
+Hartley normalisation with the correspondence weights, as the linear system already did, so a zero-weight
+correspondence (or segment) no longer changes the result (#4875, #4890). Before, the normalisation used every
+point unweighted, and on noisy data a far correspondence given weight 0 still moved the estimate: by 97% of `F` in
+the #4875 example. Non-uniform weights on noisy data now give a different result, and so does
+`find_homography_dlt_iterated`, which re-weights after its first solve, and with it the homography polish in
+`RANSAC`. `weights=None` gives the same result as before and uniform weights give it up to rounding; negative
+weights count as zero in the normalisation, and a batch element whose weights are all zero keeps the unweighted one.
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index dcbf5187c..e8d320247 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -28,7 +28,9 @@ from kornia.geometry.conversions import convert_points_from_homogeneous, convert
from kornia.geometry.solvers import solve_cubic
-def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
+def normalize_points(
+ points: torch.Tensor, eps: float = 1e-8, weights: Optional[torch.Tensor] = None
+) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Normalize points (isotropic).
Computes the Hartley normalisation: the points are translated to zero mean and scaled isotropically so
@@ -40,6 +42,8 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten
Args:
points: Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.
eps: epsilon value to avoid numerical instabilities.
+ weights: Optional nonnegative weights with shape :math:`(B, N)` for the centroid and mean radius.
+ Zero-weight points do not influence the transform. An all-zero batch element uses unweighted statistics.
Returns:
tuple containing the normalized points in the shape :math:`(B, N, 2)` and the transformation matrix
@@ -54,12 +58,29 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten
B, _N, _ = points.shape
device, dtype = points.device, points.dtype
- # Center at mean
- x_mean = points.mean(dim=1, keepdim=True) # (B,1,2)
+ if weights is None:
+ x_mean = points.mean(dim=1, keepdim=True) # (B,1,2)
+ else:
+ if weights.shape != points.shape[:2]:
+ raise AssertionError(weights.shape)
+ # 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)
+ positive_weights = weights.to(acc_dtype).clamp_min(0)
+ total_weight = positive_weights.sum(dim=1, keepdim=True)
+ # A fully de-weighted sample is degenerate; keep its normalization finite and batched.
+ effective_weights = torch.where(total_weight > 0, positive_weights, torch.ones_like(positive_weights))
+ total_weight = effective_weights.sum(dim=1, keepdim=True)
+ weighted_sum = (points.to(acc_dtype) * effective_weights[..., None]).sum(dim=1, keepdim=True)
+ x_mean = (weighted_sum / total_weight[..., None]).to(dtype)
centered = points - x_mean # (B,N,2)
# Mean Euclidean distance to origin (radius)
- mean_radius = centered.norm(dim=-1, p=2).mean(dim=-1) # (B,)
+ radii = centered.norm(dim=-1, p=2)
+ if weights is None:
+ mean_radius = radii.mean(dim=-1) # (B,)
+ else:
+ mean_radius = ((radii.to(acc_dtype) * effective_weights).sum(dim=-1) / total_weight.squeeze(-1)).to(dtype)
# Scale so that mean radius becomes sqrt(2)
scale = (math.sqrt(2.0)) / (mean_radius + eps) # (B,)
@@ -283,9 +304,9 @@ def run_8point(
if weights.shape[1] != points1.shape[1]:
raise AssertionError(weights.shape)
- # Hartley normalization (same as before)
- pts1n, T1 = normalize_points(points1)
- pts2n, T2 = normalize_points(points2)
+ # Use the same correspondences for Hartley statistics and the weighted DLT system.
+ pts1n, T1 = normalize_points(points1, weights=weights)
+ pts2n, T2 = normalize_points(points2, weights=weights)
x1, y1 = torch.chunk(pts1n, dim=-1, chunks=2) # (B,N,1)
x2, y2 = torch.chunk(pts2n, dim=-1, chunks=2) # (B,N,1)
@@ -346,10 +367,8 @@ def find_fundamental(
``method="7POINT"`` returns three candidates in no particular order.
- ``weights`` weight each correspondence's equation in the linear system: only their ratios matter, a
negative weight counts as zero, and ``method="7POINT"`` ignores them.
- - Known defects: when the 7-point cubic has one real root, the two extra candidates are one rank-3
- matrix repeated instead of zeros (`#4862 <https://github.com/kornia/kornia/issues/4862>`_); a zero weight
- does not drop a correspondence, which still enters the point normalisation and changes the result
- (`#4875 <https://github.com/kornia/kornia/issues/4875>`_).
+ - Known defect: when the 7-point cubic has one real root, the two extra candidates are one rank-3
+ matrix repeated instead of zeros (`#4862 <https://github.com/kornia/kornia/issues/4862>`_).
Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`: :math:`N \ge 8` for
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index e7510780a..5e971e225 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -219,13 +219,12 @@ def find_homography_dlt(
correspondence from the equations, and only relative weights matter.
- ``solver="lu"`` and ``"svd"`` give the same homography on exact data, to roundoff scaled by the
conditioning of the system; on noisy data they solve different least-squares problems and differ.
- - Known defect: a zero-weight correspondence still enters the point normalisation, so on noisy data it
- moves the result (`#4890 <https://github.com/kornia/kornia/issues/4890>`_).
Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.
weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
+ Zero-weight points are excluded from the DLT equations and Hartley normalization.
solver: variants: svd, lu.
@@ -243,8 +242,10 @@ def find_homography_dlt(
device, dtype = _extract_device_dtype([points1, points2])
eps: float = 1e-8
- points1_norm, transform1 = normalize_points(points1)
- points2_norm, transform2 = normalize_points(points2)
+ if weights is not None and weights.shape != points1.shape[:2]:
+ raise AssertionError(weights.shape)
+ points1_norm, transform1 = normalize_points(points1, weights=weights)
+ points2_norm, transform2 = normalize_points(points2, weights=weights)
x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # BxNx1
x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # BxNx1
@@ -332,9 +333,8 @@ def find_homography_dlt_iterated(
Convention:
- Direction and ``H[2, 2] = 1`` as :func:`find_homography_dlt`. Each solve after the first re-weights
with ``exp(-e / (2 * soft_inl_th**2))`` of the unsquared symmetric transfer error ``e``.
- - Known defects: the exponent is linear, not quadratic, in ``e``, so ``soft_inl_th`` is not a pixel
- standard deviation (`#4870 <https://github.com/kornia/kornia/issues/4870>`_); that of
- :func:`find_homography_dlt` applies (`#4890 <https://github.com/kornia/kornia/issues/4890>`_).
+ - Known defect: the exponent is linear, not quadratic, in ``e``, so ``soft_inl_th`` is not a pixel
+ standard deviation (`#4870 <https://github.com/kornia/kornia/issues/4870>`_).
Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
@@ -412,11 +412,10 @@ def find_homography_lines_dlt(
Convention:
- ``H`` maps image-1 points to image-2 points, as in :func:`find_homography_dlt`. Each segment is a
``[start, end]`` pair of ``(x, y)`` points, and ``weights`` has one entry per segment.
- - Known defects: each segment's equations are built from endpoints of two different segments, not from
+ - Known defect: each segment's equations are built from endpoints of two different segments, not from
its own start and end, so the estimate is correct only when the endpoints are themselves point
correspondences, and a zero weight does not remove its segment
- (`#4866 <https://github.com/kornia/kornia/issues/4866>`_); and the endpoints of a zero-weight segment
- still enter the point normalisation (`#4890 <https://github.com/kornia/kornia/issues/4890>`_).
+ (`#4866 <https://github.com/kornia/kornia/issues/4866>`_).
Args:
ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`, or
@@ -424,6 +423,7 @@ def find_homography_lines_dlt(
ls2: A set of line segments in the second image with a tensor shape :math:`(B, N, 2, 2)`, or
:math:`(N, 2, 2)`, which is treated as :math:`B = 1`.
weights: Tensor containing the weights per segment with a shape of :math:`(B, N)`.
+ Zero-weight segments are excluded from Hartley normalization.
Returns:
the computed homography matrix with shape :math:`(B, 3, 3)`.
@@ -441,8 +441,11 @@ def find_homography_lines_dlt(
points1 = ls1.reshape(BS, 2 * N, 2)
points2 = ls2.reshape(BS, 2 * N, 2)
- points1_norm, transform1 = normalize_points(points1)
- points2_norm, transform2 = normalize_points(points2)
+ if weights is not None and weights.shape != ls1.shape[:2]:
+ raise AssertionError(weights.shape)
+ endpoint_weights = weights.repeat_interleave(2, dim=1) if weights is not None else None
+ points1_norm, transform1 = normalize_points(points1, weights=endpoint_weights)
+ points2_norm, transform2 = normalize_points(points2, weights=endpoint_weights)
lst1, le1 = torch.chunk(points1_norm, dim=1, chunks=2)
lst2, le2 = torch.chunk(points2_norm, dim=1, chunks=2)
@@ -494,8 +497,7 @@ def find_homography_lines_dlt_iterated(
- Known defects: those of the three functions apply
(`#4866 <https://github.com/kornia/kornia/issues/4866>`_,
`#4867 <https://github.com/kornia/kornia/issues/4867>`_,
- `#4870 <https://github.com/kornia/kornia/issues/4870>`_,
- `#4890 <https://github.com/kornia/kornia/issues/4890>`_).
+ `#4870 <https://github.com/kornia/kornia/issues/4870>`_).
Args:
ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`.
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index fd727f949..d2253637c 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -28,6 +28,30 @@ from testing.two_view import two_view_scene
class TestNormalizePoints(BaseTester):
+ def test_zero_weight_outlier_does_not_change_transform(self, device, dtype):
+ points = torch.tensor(
+ [[[0.0, 0.0], [0.0, 2.0], [2.0, 0.0], [2.0, 2.0], [100.0, -100.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ weights = torch.tensor([[1.0, 1.0, 1.0, 1.0, 0.0]], device=device, dtype=dtype)
+ normalized, transform = epi.normalize_points(points, weights=weights)
+ expected_normalized, expected_transform = epi.normalize_points(points[:, :-1])
+ self.assert_close(normalized[:, :-1], expected_normalized)
+ self.assert_close(transform, expected_transform)
+
+ def test_all_zero_weights_keep_transform_finite(self, device, dtype):
+ points = torch.tensor([[[0.0, 0.0], [0.0, 2.0], [2.0, 0.0], [2.0, 2.0]]], device=device, dtype=dtype)
+ normalized, transform = epi.normalize_points(points, weights=torch.zeros(1, 4, device=device, dtype=dtype))
+ expected_normalized, expected_transform = epi.normalize_points(points)
+ self.assert_close(normalized, expected_normalized)
+ self.assert_close(transform, expected_transform)
+
+ def test_gradcheck_weighted(self, device):
+ points = torch.rand(2, 6, 2, device=device, dtype=torch.float64, requires_grad=True)
+ weights = (torch.rand(2, 6, device=device, dtype=torch.float64) + 0.2).requires_grad_()
+ self.gradcheck(lambda p, w: epi.normalize_points(p, weights=w), (points, weights))
+
def test_smoke(self, device, dtype):
points = torch.rand(1, 1, 2, device=device, dtype=dtype)
output = epi.normalize_points(points)
@@ -784,11 +808,10 @@ class TestConventionFundamental(BaseTester):
out.sum().backward()
self.assert_close(M.grad, torch.ones_like(M), rtol=0, atol=0)
- def test_wart_find_fundamental_zero_weight_changes_result_4875(self, device, dtype):
+ def test_find_fundamental_zero_weight_ignores_outlier_4875(self, device, dtype):
two_view = two_view_scene(device, dtype)
_skip_half(dtype, _NO_HALF_EIGH)
- # #4875: a correspondence with weight 0 leaves the linear system but still enters the Hartley
- # normalisation, so a far outlier with weight 0 moves the estimate. Once fixed, the two estimates agree.
+ # #4875: zero-weight correspondences must not enter either the DLT system or Hartley statistics.
x1 = two_view["x1"]
x2 = two_view["x2"] + torch.tensor([_NOISE], device=device, dtype=dtype)
outlier1 = torch.tensor([[[2000.0, -1500.0]]], device=device, dtype=dtype)
@@ -797,9 +820,7 @@ class TestConventionFundamental(BaseTester):
weights[0, 12] = 0.0
F_weighted = epi.find_fundamental(torch.cat([x1, outlier1], 1), torch.cat([x2, outlier2], 1), weights)
F_dropped = epi.find_fundamental(x1, x2)
- err_weighted = epi.sampson_epipolar_distance(x1, x2, F_weighted).mean()
- err_dropped = epi.sampson_epipolar_distance(x1, x2, F_dropped).mean()
- assert err_weighted > 2.0 * err_dropped
+ self.assert_close(F_weighted, F_dropped, rtol=1e-3, atol=1e-3)
def test_wart_fundamental_from_projections_float16_overflow_4877(self, device, dtype):
two_view = two_view_scene(device, dtype)
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 2fdd21c25..2191fd3c0 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -206,6 +206,46 @@ class TestSymmetricTransferError(BaseTester):
class TestFindHomographyDLT(BaseTester):
+ @pytest.mark.parametrize("solver", ["lu", "svd"])
+ def test_zero_weight_outlier_does_not_change_estimate(self, solver, device, dtype):
+ if dtype != torch.float64 or device.type == "mps":
+ pytest.skip("This numerical regression requires float64 linear algebra")
+
+ points1 = torch.tensor(
+ [
+ [
+ [0.0, 0.0],
+ [100.0, 0.0],
+ [0.0, 100.0],
+ [100.0, 100.0],
+ [50.0, 15.0],
+ [15.0, 60.0],
+ [85.0, 65.0],
+ [40.0, 90.0],
+ [10.0, 20.0],
+ [70.0, 30.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ points2 = points1 * torch.tensor([1.1, 0.9], device=device, dtype=dtype) + 7.0
+ points2 = points2 + torch.arange(20, device=device, dtype=dtype).reshape(1, 10, 2) * 0.03
+ outlier1 = torch.tensor([[[5000.0, -3000.0]]], device=device, dtype=dtype)
+ outlier2 = torch.tensor([[[-4000.0, 6000.0]]], device=device, dtype=dtype)
+ weights = torch.tensor([[1.0] * 10 + [0.0]], device=device, dtype=dtype)
+
+ reference = find_homography_dlt(points1, points2, solver=solver)
+ with_outlier = find_homography_dlt(
+ torch.cat([points1, outlier1], dim=1), torch.cat([points2, outlier2], dim=1), weights, solver
+ )
+ self.assert_close(
+ kornia.geometry.transform_points(with_outlier, points1),
+ kornia.geometry.transform_points(reference, points1),
+ rtol=0.0,
+ atol=1e-5,
+ )
+
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -393,6 +433,56 @@ class TestFindHomographyDLT(BaseTester):
class TestFindHomographyFromLinesDLT(BaseTester):
+ def test_zero_weight_segment_does_not_change_estimate(self, device, dtype):
+ if dtype != torch.float64 or device.type == "mps":
+ pytest.skip("This numerical regression requires float64 linear algebra")
+
+ starts = torch.tensor(
+ [
+ [0.0, 0.0],
+ [20.0, 5.0],
+ [10.0, 35.0],
+ [55.0, 15.0],
+ [70.0, 50.0],
+ [25.0, 65.0],
+ [90.0, 80.0],
+ [45.0, 95.0],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ directions = torch.tensor(
+ [
+ [12.0, 4.0],
+ [7.0, 16.0],
+ [18.0, -6.0],
+ [-9.0, 14.0],
+ [11.0, -8.0],
+ [5.0, 20.0],
+ [-15.0, 6.0],
+ [8.0, -12.0],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ segments1 = torch.stack([starts, starts + directions], dim=1)[None]
+ segments2 = segments1 * torch.tensor([1.1, 0.9], device=device, dtype=dtype) + 7.0
+ segments2 = segments2 + torch.arange(32, device=device, dtype=dtype).reshape(1, 8, 2, 2) * 0.03
+ weights = torch.tensor([[0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]], device=device, dtype=dtype)
+ # #4866 pairs endpoints incorrectly; these two zero weights isolate the normalization defect here.
+ outlier1, outlier2 = segments1.clone(), segments2.clone()
+ outlier1[:, 0] += torch.tensor([5000.0, -3000.0], device=device, dtype=dtype)
+ outlier2[:, 0] += torch.tensor([-4000.0, 6000.0], device=device, dtype=dtype)
+
+ reference = find_homography_lines_dlt(segments1, segments2, weights)
+ with_outlier = find_homography_lines_dlt(outlier1, outlier2, weights)
+ self.assert_close(
+ kornia.geometry.transform_points(with_outlier, starts[None]),
+ kornia.geometry.transform_points(reference, starts[None]),
+ rtol=0.0,
+ atol=1e-5,
+ )
+
def test_smoke(self, device, dtype):
points1st = torch.rand(1, 4, 2, device=device, dtype=dtype)
points1end = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -758,7 +848,7 @@ class TestConventionHomography(BaseTester):
return _transfer_max(H, p1[:, clean], p2[:, clean])
# On exact data: unweighted, the outlier pulls H by about 12 px on the clean points, and a weight of 0 removes
- # its equations (on noisy data it still moves H through the point normalisation, #4890).
+ # its equations and excludes it from point normalisation, including on noisy data.
assert clean_error(find_homography_dlt(p1, p2_out, None, solver)) > 5.0
w_zero = torch.ones(1, 12, device=device, dtype=dtype)
w_zero[0, 5] = 0.0
@@ -1011,7 +1101,7 @@ class TestConventionHomography(BaseTester):
self.assert_close(h22, torch.ones_like(h22), rtol=0.0, atol=1e-6)
@pytest.mark.parametrize("solver", ["lu", "svd"])
- def test_wart_find_homography_dlt_zero_weight_moves_normalisation_4890(self, solver, device, dtype):
+ def test_find_homography_dlt_zero_weight_preserves_normalisation_4890(self, solver, device, dtype):
_skip_half(dtype, _HALF_DLT)
p1, p2, _ = _planar(device, dtype)
# 3-px noise on the twelve matches, generated by
@@ -1029,7 +1119,6 @@ class TestConventionHomography(BaseTester):
weights[0, 12] = 0.0
H_weighted = find_homography_dlt(far1, far2, weights, solver)
H_dropped = find_homography_dlt(p1, p2, None, solver)
- # #4890: the zero-weight correspondence leaves the equations but still enters the Hartley normalisation, so
- # on noisy data it moves H (by 0.08 px with solver="lu" and 0.25 px with "svd" here). Once the normalisation
- # uses the weights, the two estimates agree to roundoff.
- assert _transfer_max(H_weighted, p1, kornia.geometry.transform_points(H_dropped, p1)) > 1e-2
+ # #4890: excluding the zero-weight match from Hartley statistics must match dropping it entirely.
+ tol = 1e-8 if dtype == torch.float64 else 1e-2
+ assert _transfer_max(H_weighted, p1, kornia.geometry.transform_points(H_dropped, p1)) < tol