Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

optimized line fit for 2d case by upto 2665.96% by using closed form solution (#3219)

Siddbe5adbea94cf
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 7b58ff6d4..a903b1928 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -178,17 +178,72 @@ class ParametrizedLine(Module):
return res_lambda, res_point
+def _fit_line_ols_2d(points: Tensor) -> ParametrizedLine:
+ x = points[..., 0]
+ y = points[..., 1]
+ 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).expand(points.shape[0], 2),
+ )
+
+ direction = direction / direction.norm(dim=-1, keepdim=True)
+ origin = torch.cat([x_mean, y_mean], dim=-1)
+ return ParametrizedLine(origin, direction)
+
+
+def _fit_line_weighted_ols_2d(points: Tensor, weights: Tensor) -> ParametrizedLine:
+ x = points[..., 0] # (B, N)
+ y = points[..., 1] # (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 = 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)
+
+ return ParametrizedLine(origin, direction)
+
+
def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLine:
"""Fit a line from a set of points.
Args:
- points: tensor containing a batch of sets of n-dimensional points. The expected
+ points: tensor containing a batch of sets of n-dimensional points. The expected
shape of the tensor is :math:`(B, N, D)`.
- weights: weights to use to solve the equations system. The expected
+ weights: weights to use to solve the equations system. The expected
shape of the tensor is :math:`(B, N)`.
Return:
- A tensor containing the direction of the fited line of shape :math:`(B, D)`.
+ A tensor containing the direction of the fitted line of shape :math:`(B, D)`.
Example:
>>> points = torch.rand(2, 10, 3)
@@ -196,11 +251,22 @@ def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLi
>>> line = fit_line(points, weights)
>>> line.direction.shape
torch.Size([2, 3])
-
"""
KORNIA_CHECK_IS_TENSOR(points, "points must be a tensor")
KORNIA_CHECK_SHAPE(points, ["B", "N", "D"])
+ B, N, D = points.shape
+
+ # Fast path: use OLS for unweighted 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)
+ else:
+ return _fit_line_ols_2d(points)
+
mean = points.mean(-2, True)
A = points - mean
@@ -216,7 +282,7 @@ def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLi
_, _, V = _torch_svd_cast(A)
V = V.transpose(-2, -1)
- # the first left eigenvector is the direction on the fited line
+ # the first left eigenvector is the direction on the fitted line
direction = V[..., 0, :] # BxD
origin = mean[..., 0, :] # BxD
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index a9db8866a..dd981efe7 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -190,6 +190,31 @@ class TestFitLine(BaseTester):
angle_exp = torch.tensor([1.0], device=device, dtype=dtype)
self.assert_close(angle_est.abs(), angle_exp)
+ def test_fit_line_weighted(self, device, dtype):
+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)
+ p1 = torch.tensor([1.0, 1.0], device=device, dtype=dtype)
+ l1 = ParametrizedLine.through(p0, p1)
+
+ num_points = 20
+ ts = torch.linspace(-10, 10, num_points)
+ points = torch.stack([l1.point_at(t) for t in ts])
+
+ noise = torch.randn_like(points) * 0.05
+ points_noisy = points + noise
+
+ distances = torch.norm(points, dim=1)
+ weights = torch.exp(-distances * 0.2)
+ weights = weights / weights.max()
+
+ line_est = fit_line(points_noisy[None], weights=weights[None])
+
+ expected_dir = torch.tensor([0.7071, 0.7071], device=device, dtype=dtype)
+ expected_dir = expected_dir / expected_dir.norm()
+
+ angle_est = torch.nn.functional.cosine_similarity(line_est.direction, expected_dir, dim=-1)
+
+ assert angle_est.abs() > 0.998
+
@pytest.mark.skip(reason="numerical do not match with analytical")
def test_gradcheck(self, device):
def proxy_func(pts, weights):