Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): fit 2-D lines by total least squares (#5040) (#5094)

niukanen1794e7c1b52bd
diff --git a/changelog.d/5094.breaking.md b/changelog.d/5094.breaking.md
new file mode 100644
index 000000000..e8f1b5c88
--- /dev/null
+++ b/changelog.d/5094.breaking.md
@@ -0,0 +1,9 @@
+`fit_line` now fits 2-D points by total least squares, as it does points of higher dimension: the line minimises the
+perpendicular distances to the points. It used to fit an ordinary least squares slope of y on x, which minimises the
+vertical distances, so noisy 2-D points gave a direction biased towards horizontal (8.3 degrees off for a near-vertical
+set whose total least squares fit is 1.4 degrees off), swapping x and y changed the line, and a set with
+`sum((x - x.mean()) ** 2) <= 1e-8`, such as a slanted set in small units, came out vertical. In `float16`, steep sets
+and sets spanning a few hundred units came out NaN or `(1, 0)`. Points exactly on a line give the same direction as
+before: the 2-D direction still has a non-negative x component, and an exactly vertical line still gets `(0, 1)`.
+Under `torch.compile` or `disable_checks()`, where degenerate input is not rejected, identical 2-D points now get the
+direction `(1, 0)` instead of `(0, 1)`.
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index da7c61b86..8a6ccd568 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -17,6 +17,7 @@
# kornia.geometry.line module inspired by Eigen::geometry::ParametrizedLine
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/ParametrizedLine.h
+import math
from typing import Iterator, Optional, Tuple, Union
import torch
@@ -201,58 +202,73 @@ class ParametrizedLine(nn.Module):
return res_lambda, res_point
-def _fit_line_ols_2d(points: torch.Tensor) -> ParametrizedLine:
- x = points[..., 0]
- y = points[..., 1]
+def _tls_direction_2d(dx: torch.Tensor, dy: torch.Tensor, weights: Optional[torch.Tensor]) -> torch.Tensor:
+ """Return the unit direction of the total least squares line through centred 2-D points (#5040).
+
+ The direction is the principal axis of the (weighted) scatter of ``(dx, dy)``, in closed form:
+ ``theta = 0.5 * atan2(2 * sxy, sxx - syy)`` lies in ``[-pi / 2, pi / 2]`` and the direction is
+ ``(cos(theta), sin(theta))``, so its x component is non-negative. ``theta`` does not change when the points are
+ scaled, so they are first divided by their largest magnitude: the second moments then cannot overflow (float16
+ does past 65504) or underflow, whatever the unit of the coordinates.
+ """
+ scale = torch.maximum(dx.abs().amax(dim=-1, keepdim=True), dy.abs().amax(dim=-1, keepdim=True)) # (B, 1)
+ scale = torch.where(scale > 0, scale, torch.ones_like(scale))
+ dx = dx / scale
+ dy = dy / scale
+ wdx = dx if weights is None else weights * dx
+ wdy = dy if weights is None else weights * dy
+ sxx = (wdx * dx).sum(dim=-1, keepdim=True)
+ syy = (wdy * dy).sum(dim=-1, keepdim=True)
+ sxy = (wdx * dy).sum(dim=-1, keepdim=True)
+
+ # theta and the direction in float32 for half-precision input: compiled half-precision kernels keep theta in
+ # float32 but round pi / 2 to the input dtype, which gave an exactly vertical line x = -4.8e-4.
+ dtype = sxy.dtype
+ if dtype in (torch.float16, torch.bfloat16):
+ sxx, syy, sxy = sxx.float(), syy.float(), sxy.float()
+ # 0.5 * atan2(2 * sxy, sxx - syy), computed with both signs flipped. An exactly vertical set has sxy = +0: eager
+ # atan2(+0, negative) is +pi, but the ONNX export's atan2 returns -pi for either zero. atan2(-0, negative) is -pi
+ # in both, so theta is +pi / 2 in eager, compiled and exported graphs alike.
+ theta = -0.5 * torch.atan2(-2 * sxy, sxx - syy) # (B, 1)
+ # cos(theta) as sin(pi / 2 - |theta|): float32 atan2 can return the float nearest to pi, which is larger than pi,
+ # and the cosine of half of it is -4.4e-8, whereas pi / 2 - |theta| is never negative.
+ return torch.cat([torch.sin(math.pi / 2 - theta.abs()), theta.sin()], dim=-1).to(dtype)
+
+
+def _fit_line_tls_2d(points: torch.Tensor) -> ParametrizedLine:
+ """Fit a 2-D line by total least squares (#5040).
+
+ The points are centred relative to the first one, so a coordinate that equals the first point's is exactly 0
+ after centring, whatever the rounding of the mean. An exactly vertical set then has ``sxy = +0`` and gets the
+ direction ``(0, 1)``; the float32 rounding of ``pi / 2`` can leave an x component of 1.2e-7.
+ """
+ x0 = points[..., :1, 0] # (B, 1)
+ y0 = points[..., :1, 1] # (B, 1)
+ x = points[..., 0] - x0 # (B, N)
+ y = points[..., 1] - y0 # (B, N)
x_mean = x.mean(dim=-1, keepdim=True)
y_mean = y.mean(dim=-1, keepdim=True)
- dx = x - x_mean
- dy = y - y_mean
-
- denom = (dx * dx).sum(dim=-1, keepdim=True) # (B, 1)
- slope = torch.where(denom > 1e-8, (dx * dy).sum(dim=-1, keepdim=True) / denom, torch.zeros_like(denom))
- # For vertical lines, fallback to [0,1] direction
- direction = torch.where(
- denom > 1e-8,
- torch.cat([torch.ones_like(slope), slope], dim=-1),
- torch.tensor([0.0, 1.0], device=points.device, dtype=points.dtype).expand(points.shape[0], 2),
- )
-
- direction = direction / direction.norm(dim=-1, keepdim=True)
- origin = torch.cat([x_mean, y_mean], dim=-1)
+ direction = _tls_direction_2d(x - x_mean, y - y_mean, None)
+ origin = torch.cat([x0 + x_mean, y0 + y_mean], dim=-1)
return ParametrizedLine(origin, direction)
-def _fit_line_weighted_ols_2d(points: torch.Tensor, weights: torch.Tensor) -> ParametrizedLine:
- x = points[..., 0] # (B, N)
- y = points[..., 1] # (B, N)
+def _fit_line_weighted_tls_2d(points: torch.Tensor, weights: torch.Tensor) -> ParametrizedLine:
+ """Fit a 2-D line by weighted total least squares: weighted centroid and weighted moments (#5040).
+ Centred relative to the first point, like :func:`_fit_line_tls_2d`.
+ """
+ x0 = points[..., :1, 0] # (B, 1)
+ y0 = points[..., :1, 1] # (B, 1)
+ x = points[..., 0] - x0 # (B, N)
+ y = points[..., 1] - y0 # (B, N)
w_sum = weights.sum(dim=-1, keepdim=True) # (B, 1)
x_mean = (weights * x).sum(dim=-1, keepdim=True) / w_sum # (B, 1)
y_mean = (weights * y).sum(dim=-1, keepdim=True) / w_sum # (B, 1)
- dx = x - x_mean # (B, N)
- dy = y - y_mean # (B, N)
-
- weighted_dx2 = weights * dx * dx
- weighted_dxdy = weights * dx * dy
-
- denom = weighted_dx2.sum(dim=-1, keepdim=True) # (B, 1)
- slope = weighted_dxdy.sum(dim=-1, keepdim=True) / denom # (B, 1)
-
- # Replace NaNs or infs from division by zero
- slope = torch.where(torch.isfinite(slope), slope, torch.zeros_like(slope))
-
- # direction = F.normalize([1, slope]) or [0,1] if vertical
- is_vertical = denom <= 1e-8
- direction = torch.cat([torch.ones_like(slope), slope], dim=-1) # (B, 2)
- replacement = torch.tensor([0.0, 1.0], device=points.device, dtype=points.dtype)
- direction[is_vertical.squeeze(-1)] = replacement
-
- direction = direction / direction.norm(dim=-1, keepdim=True)
- origin = torch.cat([x_mean, y_mean], dim=-1)
-
+ direction = _tls_direction_2d(x - x_mean, y - y_mean, weights)
+ origin = torch.cat([x0 + x_mean, y0 + y_mean], dim=-1)
return ParametrizedLine(origin, direction)
@@ -293,7 +309,12 @@ def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.Tensor
def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> ParametrizedLine:
- """Fit a line from a set of points.
+ """Fit a line from a set of points by total least squares.
+
+ The line minimises the perpendicular distances to the points, for every dimensionality.
+ For 2-D inputs the direction is computed in closed form and always has a non-negative
+ x component, so an exactly vertical line gets the direction (0, 1); higher-dimensional
+ inputs take the principal direction of the scatter matrix, whose sign is not specified.
Args:
points: tensor containing a batch of sets of n-dimensional points. The expected
@@ -323,14 +344,14 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
_reject_degenerate_line(points, weights)
- # Fast path: use OLS for unweighted 2D case
+ # Fast path: closed-form total least squares for the 2D case
if D == 2:
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])
- return _fit_line_weighted_ols_2d(points, weights)
- return _fit_line_ols_2d(points)
+ return _fit_line_weighted_tls_2d(points, weights)
+ return _fit_line_tls_2d(points)
if weights is not None:
KORNIA_CHECK_IS_TENSOR(weights, "weights must be a tensor")
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 80f30dd61..e6680fa83 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
@@ -311,6 +313,16 @@ class TestParametrizedLine(BaseTester):
assert [name for name, _ in plain.named_parameters()] == ["_origin", "_direction"]
+def _near_vertical_points_5040(device, dtype) -> torch.Tensor:
+ """Return 7 points (7, 2) off the line through (2, 0) along (0.1, 1), with perpendicular offsets (#5040)."""
+ t = torch.tensor([-2.0, -1.3, -0.2, 0.4, 1.1, 2.7, 3.5], device=device, dtype=dtype)
+ off = torch.tensor([0.21, -0.35, 0.12, 0.30, -0.27, 0.05, -0.18], device=device, dtype=dtype)
+ u = torch.tensor([0.1, 1.0], device=device, dtype=dtype)
+ u = u / u.norm()
+ n = torch.stack([-u[1], u[0]])
+ return torch.tensor([2.0, 0.0], device=device, dtype=dtype) + t[:, None] * u + off[:, None] * n
+
+
class TestFitLine(BaseTester):
@pytest.mark.parametrize("B", (1, 2))
@pytest.mark.parametrize("D", (2, 3, 4))
@@ -455,6 +467,130 @@ class TestFitLine(BaseTester):
assert line.direction.dtype == dtype
self.assert_close(line.direction, torch.tensor([[0.0, 1.0]], device=device, dtype=dtype))
+ def test_fit_line_2d_is_total_least_squares_5040(self, device, dtype):
+ # #5040: the 2-D branch used to fit y-on-x ordinary least squares, several degrees off
+ # a near-vertical set that the D >= 3 branch fits correctly.
+ points = _near_vertical_points_5040(device, dtype)
+
+ fit_2d = fit_line(points[None]).direction
+ points_3d = torch.cat([points, torch.zeros(len(points), 1, device=device, dtype=dtype)], -1)
+ fit_3d = fit_line(points_3d[None]).direction[..., :2]
+
+ # same line up to the arbitrary SVD sign
+ self.assert_close(fit_2d.abs(), fit_3d.abs())
+
+ if dtype == torch.float64:
+ # scaling the input must not change the fit (the old absolute 1e-8 vertical test
+ # crossed at 1e-5); below float64 the scaled input itself is not representable
+ scaled = fit_line((points * 1e-5)[None]).direction
+ self.assert_close(scaled.abs(), fit_2d.abs())
+
+ def test_fit_line_2d_symmetric_in_coordinates_5040(self, device, dtype):
+ # #5040: swapping x and y must mirror the direction, not rotate it
+ points = _near_vertical_points_5040(device, dtype)
+
+ fit_2d = fit_line(points[None]).direction
+ fit_swapped = fit_line(points.flip(-1)[None]).direction
+ self.assert_close(fit_swapped, fit_2d.flip(-1))
+
+ def test_fit_line_weighted_2d_total_least_squares_5040(self, device, dtype):
+ # #5040: the weighted 2-D branch used to fit a weighted y-on-x slope; it must instead
+ # use the weighted centroid and weighted second moments like the weighted D >= 3 branch.
+ points = _near_vertical_points_5040(device, dtype)
+ weights = torch.tensor([1.0, 2.0, 0.5, 1.5, 1.0, 2.0, 1.0], device=device, dtype=dtype)
+
+ line = fit_line(points[None], weights[None])
+
+ w = weights
+ x_mean = (w * points[:, 0]).sum() / w.sum()
+ y_mean = (w * points[:, 1]).sum() / w.sum()
+ dx = points[:, 0] - x_mean
+ dy = points[:, 1] - y_mean
+ sxx = (w * dx * dx).sum()
+ syy = (w * dy * dy).sum()
+ sxy = (w * dx * dy).sum()
+ theta = 0.5 * torch.atan2(2 * sxy, sxx - syy)
+ expected_direction = torch.stack([theta.cos(), theta.sin()])[None]
+
+ self.assert_close(line.direction, expected_direction)
+ self.assert_close(line.origin, torch.stack([x_mean, y_mean])[None])
+
+ @pytest.mark.parametrize("weighted", [False, True])
+ def test_fit_line_2d_exactly_vertical_is_0_1_5040(self, device, dtype, weighted):
+ # #5040: the direction of an exactly vertical line is (0, 1). Rounding in the mean used to leave a tiny
+ # nonzero sxy of either sign, which gave (0, -1) for x = 0.7 or 7.7 in float64; and float32 atan2 returned
+ # the float nearest to pi, whose half has a cosine of -4.4e-8 (vectorised CPU kernels for 8 rows or more,
+ # and MPS). Eight rows, each vertical at its own x.
+ x0 = torch.tensor([0.0, 0.1, 0.3, 0.7, -0.1, 7.7, 13.1, 100.3], device=device, dtype=dtype)
+ y = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], device=device, dtype=dtype)
+ points = torch.stack([x0[:, None].expand(8, 7), y.expand(8, 7)], -1)
+ weights = torch.tensor([0.5, 2.0, 1.0, 1.5, 0.25, 1.0, 3.0], device=device, dtype=dtype).expand(8, 7)
+
+ line = fit_line(points, weights if weighted else None)
+ assert (line.direction[:, 0] >= 0).all(), line.direction
+ self.assert_close(line.direction, torch.tensor([0.0, 1.0], device=device, dtype=dtype).expand(8, 2))
+ self.assert_close(line.origin[:, 0], x0)
+
+ # A row leaning left of vertical by far less than the rounding of pi / 2 gets (0, -1): its x component stays
+ # non-negative, although float32 atan2 returns the float nearest to pi for it.
+ leaning = points.clone()
+ leaning[:, -1, 0] = leaning[:, -1, 0] - 1e-30 * (x0 == 0)
+ line = fit_line(leaning, weights if weighted else None)
+ assert (line.direction[:, 0] >= 0).all(), line.direction
+ self.assert_close(line.direction.abs(), torch.tensor([0.0, 1.0], device=device, dtype=dtype).expand(8, 2))
+
+ def test_fit_line_2d_vertical_compiled_half_5040(self, device, torch_optimizer):
+ # Compiled half-precision kernels keep intermediates in float32 but round Python constants to the input
+ # dtype: while theta was computed in the input dtype, an exactly vertical line got x = -4.8e-4 under
+ # torch.compile.
+ y = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
+ points = torch.stack([torch.full((7,), 0.7), y], -1)[None].to(device=device, dtype=torch.float16)
+ direction = torch_optimizer(lambda p: fit_line(p).direction)(points)
+ assert (direction[:, 0] >= 0).all(), direction
+ self.assert_close(direction, torch.tensor([[0.0, 1.0]], device=device, dtype=torch.float16))
+
+ def test_fit_line_2d_power_of_two_scale_5040(self, device, dtype):
+ # #5040: the fit does not depend on the unit of the coordinates. Scaling by a power of two is exact in every
+ # dtype; the scale is the square root of the dtype's range (256 in float16), where the second moments of the
+ # scaled points used to overflow or underflow, and the direction came out vertical or NaN.
+ points = _near_vertical_points_5040(device, dtype)[None]
+ weights = torch.tensor([[1.0, 2.0, 0.5, 1.5, 1.0, 2.0, 1.0]], device=device, dtype=dtype)
+ scale = 2.0 ** (math.frexp(torch.finfo(dtype).max)[1] // 2)
+ scales = torch.tensor([scale, 1.0 / scale], device=device, dtype=dtype)[:, None, None]
+ for w in (None, weights):
+ line = fit_line(points, w)
+ # Both scales in one batch: each row is rescaled on its own.
+ scaled = fit_line(points * scales, None if w is None else w.expand(2, 7))
+ self.assert_close(scaled.direction, line.direction.expand(2, 2))
+ self.assert_close(scaled.origin / scales[..., 0], line.origin.expand(2, 2))
+
+ def test_fit_line_2d_degenerate_row_with_checks_disabled(self, device, dtype):
+ # With checks disabled, as under torch.compile, identical 2-D points are not rejected: their scatter is 0,
+ # and they get the direction (1, 0) rather than NaN, without touching the other rows.
+ points = torch.tensor([[[0.0, 0.0], [1.0, 3.0], [2.0, 5.0]], [[1.0, 2.0]] * 3], device=device, dtype=dtype)
+ weights = torch.tensor([[1.0, 2.0, 1.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype)
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ for w in (None, weights):
+ line = fit_line(points, w)
+ expected = fit_line(points[:1], None if w is None else w[:1])
+ self.assert_close(line.direction[:1], expected.direction)
+ self.assert_close(line.direction[1], torch.tensor([1.0, 0.0], device=device, dtype=dtype))
+ self.assert_close(line.origin[1], points[1, 0])
+ finally:
+ if checks_were_enabled:
+ enable_checks()
+
+ def test_fit_line_2d_steep_float16_5040(self, device, dtype):
+ # #5040 (comment): a slope of 1e5 overflowed the float16 slope, giving NaN, or (1, 0) with weights.
+ x = torch.linspace(0, 1e-3, 20, dtype=torch.float64)
+ y = torch.linspace(0, 100, 20, dtype=torch.float64)
+ points = torch.stack([x, y], -1)[None].to(device=device, dtype=dtype)
+ expected = torch.tensor([[1e-5, 1.0]], device=device, dtype=dtype)
+ for w in (None, torch.ones(1, 20, device=device, dtype=dtype)):
+ self.assert_close(fit_line(points, w).direction, expected)
+
def test_fit_line_degenerate_raises_5041(self, device, dtype):
# #5041: a single point, identical points, or all-zero weights used to return an
# arbitrary-looking line ((0, 1) / (1, 0, 0) directions, a NaN origin for zero weights).
@@ -534,7 +670,8 @@ class TestFitLine(BaseTester):
p = torch.tensor([[[1.0, 2.0, 3.0]] * 4], device=device, dtype=dtype)
def op(points):
- return ParametrizedLine.through(points[0, 0], points[0, 1]).direction, fit_line(points).direction
+ through = ParametrizedLine.through(points[0, 0], points[0, 1]).direction
+ return through, fit_line(points).direction, fit_line(points[..., :2]).direction
actual = torch_optimizer(op)(p)
checks_were_enabled = are_checks_enabled()
@@ -546,6 +683,7 @@ class TestFitLine(BaseTester):
enable_checks()
self.assert_close(actual[0], expected[0])
self.assert_close(actual[1], expected[1])
+ self.assert_close(actual[2], expected[2])
def test_fit_line_small_valid_set_still_fits(self, device, dtype):
# The degeneracy test is relative, not absolute: a small-but-distinct set still fits.
diff --git a/tests/onnx/test_export_coverage.py b/tests/onnx/test_export_coverage.py
index 6ea58b947..dd1106074 100644
--- a/tests/onnx/test_export_coverage.py
+++ b/tests/onnx/test_export_coverage.py
@@ -33,6 +33,7 @@ import kornia
from kornia.core._compat import torch_version_lt
from kornia.core.utils import _torch_inverse_cast
from kornia.geometry.epipolar.numeric import matrix_cofactor_tensor
+from kornia.geometry.line import fit_line
# Every tensor here is created device-free and fed to onnxruntime as numpy: the work is CPU-bound
# whatever ``--device`` says, so the accelerator legs must not repeat it.
@@ -147,6 +148,26 @@ def _cases():
),
id="depth_from_plane_equation_grazing",
),
+ pytest.param(
+ # An exactly vertical row: the exported atan2 returns -pi for atan2(+0, negative), where eager returns
+ # +pi, so the fit computes theta from atan2(-0, negative), which both return as -pi (#5040). The eager
+ # line stores its origin and direction as parameters, hence the detach.
+ _Fn(
+ lambda p, w: tuple(
+ t.detach() for line in (fit_line(p), fit_line(p, w)) for t in (line.origin, line.direction)
+ )
+ ),
+ (
+ torch.stack(
+ [
+ torch.stack([torch.full((7,), 0.7), torch.linspace(0.1, 0.7, 7)], -1),
+ torch.stack([torch.linspace(0.0, 3.0, 7), torch.linspace(1.0, -1.0, 7) ** 2], -1),
+ ]
+ ),
+ torch.rand(2, 7) + 0.5,
+ ),
+ id="fit_line_2d_vertical",
+ ),
]