Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): centre weighted D >= 3 fit_line on the weighted centroid (#5029)

RitiGroverf7a13b1f65a8
diff --git a/changelog.d/5029.breaking.md b/changelog.d/5029.breaking.md
new file mode 100644
index 000000000..3c7cf3e13
--- /dev/null
+++ b/changelog.d/5029.breaking.md
@@ -0,0 +1,5 @@
+`fit_line` with `weights` now centres `D >= 3` points on the weighted centroid and returns it as the origin, as the
+`D = 2` branch does, so a point with weight 0 no longer moves the origin or tilts the direction. Previously the points
+were centred on the unweighted mean, which was also the returned origin, and only the scatter matrix was weighted, so
+any non-uniform weights gave a different origin and direction from weighted least squares. Uniform weights give the
+same line as before, and a row whose weights sum to 0 still gets the unweighted mean as its origin.
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index bcc1f57ad..1dcfe8c23 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -275,15 +275,23 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
return _fit_line_weighted_ols_2d(points, weights)
return _fit_line_ols_2d(points)
- mean = points.mean(-2, True)
- A = points - mean
-
if weights is not None:
KORNIA_CHECK_IS_TENSOR(weights, "weights must be a tensor")
KORNIA_CHECK_SHAPE(weights, ["B", "N"])
KORNIA_CHECK(points.shape[0] == weights.shape[0])
+ # Weighted total least squares: centre on the weighted centroid, as the D = 2 branch does. A row whose
+ # weights sum to 0 keeps the unweighted mean instead of 0 / 0, whose NaN would make the SVD raise.
+ w_sum = weights.sum(-1)[..., None, None]
+ has_weight = w_sum != 0
+ w_sum = torch.where(has_weight, w_sum, torch.ones_like(w_sum))
+ mean = torch.where(
+ has_weight, (weights[..., None] * points).sum(-2, keepdim=True) / w_sum, points.mean(-2, True)
+ )
+ A = points - mean
A = A.transpose(-2, -1) @ torch.diag_embed(weights) @ A
else:
+ mean = points.mean(-2, True)
+ A = points - mean
A = A.transpose(-2, -1) @ A
# NOTE: not optimal for 2d points, but for now works for other dimensions
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 8c1001a60..5a0903779 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -314,6 +314,47 @@ class TestFitLine(BaseTester):
assert angle_est.abs() > 0.998
+ def test_fit_line_weighted_3d_ignores_a_zero_weight_point_5014(self, device):
+ # #5014: for D >= 3 the points were centred on the unweighted mean, so a point with weight 0 still moved
+ # the origin and tilted the direction (by 16 degrees here). float32, not float64: MPS has no float64.
+ d = torch.float32
+ t = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0, 3.0], device=device, dtype=d)
+ u = torch.tensor([2.0, 1.0, -2.0], device=device, dtype=d) / 3
+ noise = torch.tensor(
+ [
+ [0.02, -0.01, 0.0],
+ [-0.01, 0.02, 0.01],
+ [0.0, 0.0, -0.02],
+ [0.01, -0.02, 0.0],
+ [-0.02, 0.01, 0.02],
+ [0.0, 0.01, -0.01],
+ ],
+ device=device,
+ dtype=d,
+ )
+ inliers = torch.tensor([1.0, 0.5, -1.0], device=device, dtype=d) + t[:, None] * u + noise
+ outlier = torch.tensor([[6.0, -4.0, 5.0]], device=device, dtype=d)
+ points = torch.cat([inliers, outlier])[None]
+ weights = torch.tensor([[1.0] * 6 + [0.0]], device=device, dtype=d)
+
+ expected = fit_line(inliers[None])
+ actual = fit_line(points, weights)
+ self.assert_close(actual.origin, expected.origin)
+ # The direction is defined up to sign.
+ self.assert_close((actual.direction * expected.direction).sum(-1).abs(), torch.ones(1, device=device, dtype=d))
+
+ # Uniform weights give the unweighted fit.
+ uniform = fit_line(points, torch.full((1, 7), 2.0, device=device, dtype=d))
+ self.assert_close(uniform.origin, fit_line(points).origin)
+
+ # Each batch row is centred on its own weighted centroid, whatever the other rows' weights sum to.
+ batch = fit_line(torch.cat([points, points]), torch.cat([weights, 3.0 * weights]))
+ self.assert_close(batch.origin, expected.origin.expand(2, 3))
+
+ # A row whose weights are all 0 keeps the unweighted mean and does not break the other rows.
+ zero = fit_line(torch.cat([points, points]), torch.cat([weights, torch.zeros_like(weights)]))
+ self.assert_close(zero.origin, torch.cat([expected.origin, points.mean(-2)]))
+
def test_fit_line_vertical_dtype(self, device, dtype):
pts = torch.tensor([[[0.0, 0.0], [0.0, 1.0], [0.0, 2.0]]], device=device, dtype=dtype)
line = fit_line(pts)