Foundations
Least Squares
The method of fitting a model to more measurements than unknowns by minimizing the sum of squared residuals, the workhorse of estimation in computer vision.
beginner
Least squares is the method of choosing model parameters so that the sum of squared differences between the model’s predictions and the measurements is as small as possible. It is the standard way to solve an overdetermined system, one with more equations than unknowns, in which noise makes the equations mutually inconsistent. In computer vision it fits lines and curves to points, estimates motion in the Lucas–Kanade method, initializes homographies and camera matrices, and, in its nonlinear form, refines entire 3D reconstructions.
Adrien-Marie Legendre published the method in 1805, in an appendix to a book on computing the orbits of comets. Carl Friedrich Gauss published his own treatment in 1809, stating that he had used the principle since 1795 and deriving it as the most probable estimate under what is now called the Gaussian distribution of errors. Their priority dispute is the most famous in the history of statistics. Stigler (1981) weighed the documentary and numerical evidence and concluded, while stressing that it is not decisive, that Gauss probably did use the method before Legendre but failed to make it known to his contemporaries.
Definition
Given measurements and a model with unknown parameters that predicts each measurement, the least-squares estimate is the parameter vector that minimizes the sum of the squared residuals, the differences between measured and predicted values. When the predictions are linear in the parameters, the problem is linear least squares and has a closed-form solution; otherwise it is nonlinear least squares and is solved iteratively.
Intuition
Fitting a line to twenty noisy points gives twenty equations in two unknowns. No line passes through all the points, so the question is how to trade errors off against each other. Squaring makes every error count positively and produces a smooth, bowl-shaped objective whose minimum is found by setting the derivative to zero, which yields a linear system. The same squaring has a cost: a single point with a large error contributes so heavily to the sum that it can drag the whole fit toward itself.
Formal Definition
Write the linear model as , with design matrix , unknowns , measurements , and . The least-squares solution minimizes the squared norm of the residual :
where is the -th row of . Setting the gradient to zero gives the normal equations
If has full column rank, is invertible and the solution is unique, . If it does not, for example when the data cannot distinguish two parameters, infinitely many minimizers exist, and the pseudoinverse selects the one of smallest norm, .
Geometric view
The products for all form the column space of , an -dimensional subspace of . The measurement vector generally lies outside it, and the closest point of the subspace to is its orthogonal projection . The normal equations say exactly that the residual is orthogonal to every column of , . The projection onto the column space is .
Properties
Solving it in practice
Forming explicitly squares the condition number, , so on an ill-conditioned problem the normal equations can lose about twice as many significant digits as methods that work with directly, especially when the residual is small. Numerical libraries therefore factor itself:
- QR decomposition. Factor with orthonormal columns in and upper-triangular ; then solves the triangular system . This is the usual method for well-conditioned, full-rank problems.
- Singular value decomposition. Factor with the singular values on the diagonal of ; then , where inverts the nonzero singular values. The SVD is slower but reveals rank deficiency, and small singular values can be truncated to stabilize nearly singular problems.
The normal equations remain acceptable when is well conditioned and is tiny, as in the system of Lucas–Kanade, and are often used deliberately when is sparse and structured. Centering and scaling the data first, so that columns have similar magnitudes, is cheap and often improves conditioning decisively.
Weighted least squares
When measurements have different reliabilities, each squared residual is weighted:
With a diagonal , each equation is simply scaled by . The usual choice is the inverse of the noise covariance, , so that precise measurements count more. The Gaussian window in Lucas–Kanade is a weighting of this kind, by distance from the tracked point rather than by noise.
Regularized least squares
When is ill conditioned or the problem is underdetermined, adding a penalty on the solution makes it well posed:
With this is ridge regression; with a general , for example a derivative operator that penalizes rough solutions, it is Tikhonov regularization. The Horn–Schunck method has this structure: a quadratic data term from brightness constancy plus a quadratic smoothness term on the flow field.
Statistical view
Suppose the measurements are with independent Gaussian noise of equal variance . The likelihood of is proportional to , so maximizing it is the same as minimizing the sum of squares: least squares is the maximum-likelihood estimate under Gaussian noise. With correlated Gaussian noise of covariance , the maximum-likelihood estimate is weighted least squares with . The estimate’s covariance is , which is how the aperture problem article obtains the elongated uncertainty of flow estimated near an edge.
The Gauss–Markov theorem gives a weaker but distribution-free guarantee: if the noise has zero mean and is uncorrelated with equal variance, ordinary least squares has the smallest variance among all unbiased estimators that are linear in . No Gaussian assumption is needed, but a nonlinear or biased estimator can still do better.
Nonlinear least squares
Most geometric problems in vision, such as projecting 3D points through a camera, are nonlinear in their parameters. Minimizing then proceeds iteratively: the Gauss–Newton method linearizes the residuals around the current estimate and solves a linear least-squares problem for the update, and the Levenberg–Marquardt method adds a damping term that blends Gauss–Newton with gradient descent when the linearization is poor. Each iteration is a linear least-squares solve, so everything above applies inside the loop. Iterated Lucas–Kanade is a Gauss–Newton method.
Sensitivity to outliers
Because the penalty grows quadratically, least squares is fragile when some measurements are simply wrong, such as mismatched features or pixels that violate brightness constancy. Robust alternatives replace the square with a penalty that grows more slowly, solved by iteratively reweighted least squares, or separate inliers from outliers by random sampling (RANSAC) and fit only the inliers.
Examples
Line fitting
The code fits a line to twenty noisy points, once with NumPy’s SVD-based lstsq and once through the normal equations, then corrupts a single point.
import numpy as np
rng = np.random.default_rng(0)
# 20 noisy samples of the line y = 2x + 1.
x = np.linspace(0, 10, 20)
y = 2 * x + 1 + rng.normal(0, 0.5, size=x.size)
A = np.column_stack([x, np.ones_like(x)]) # one row [x_i, 1] per point
theta_lstsq, *_ = np.linalg.lstsq(A, y, rcond=None) # SVD-based solver
theta_normal = np.linalg.solve(A.T @ A, A.T @ y) # normal equations
print("lstsq slope, intercept:", np.round(theta_lstsq, 3))
print("normal equations slope, intercept:", np.round(theta_normal, 3))
print(f"cond(A) = {np.linalg.cond(A):.1f}, cond(A^T A) = {np.linalg.cond(A.T @ A):.1f}")
# Corrupt a single point with a gross error and refit.
y_bad = y.copy()
y_bad[-1] += 30
theta_bad, *_ = np.linalg.lstsq(A, y_bad, rcond=None)
print("with one outlier slope, intercept:", np.round(theta_bad, 3))
Output:
lstsq slope, intercept: [1.974 1.04 ]
normal equations slope, intercept: [1.974 1.04 ]
cond(A) = 11.5, cond(A^T A) = 132.6
with one outlier slope, intercept: [ 2.788 -1.531]
Both solvers agree on this well-conditioned problem, and the printed condition numbers confirm . One corrupted point out of twenty moves the slope by about 40% and the intercept by more than 2.5 units, which is why vision pipelines pair least squares with outlier rejection.
Motion of an image window
Lucas–Kanade collects one linearized brightness constancy equation per pixel of a window, giving an overdetermined system in the two unknowns . Its normal equations are a system whose matrix is the structure tensor of the window; when that matrix is singular or nearly so, as on an edge or in a flat region, the flow is undetermined, which is the aperture problem.
Homographies and camera matrices
Each point correspondence gives two equations that are linear in the nine entries of a homography. Stacking them yields a homogeneous system ; the direct linear transform (DLT) takes the unit vector that minimizes , the right singular vector of with the smallest singular value. The same construction estimates a camera projection matrix from 3D–2D correspondences. Hartley and Zisserman stress that normalizing the coordinates first is essential, and that the minimized quantity is an algebraic error without direct geometric meaning. The linear solution therefore usually initializes a nonlinear least-squares refinement of a geometric error. Camera calibration follows the same pattern: a closed-form estimate, then nonlinear refinement of the reprojection error.
Bundle adjustment
Bundle adjustment refines all camera parameters and 3D points of a reconstruction together by minimizing reprojection error, the distance between each observed image point and the projection of its 3D point. It is a large nonlinear least-squares problem, solved by Gauss–Newton or Levenberg–Marquardt iterations that exploit the sparsity of the normal equations, since each residual involves only one camera and one point. Triggs and colleagues’ survey covers these methods and the robust cost functions often used in place of the plain square.
Common Misconceptions
- “Least squares assumes Gaussian noise.” The method can be applied to any data; Gaussian noise is what makes it the maximum-likelihood estimate, and the Gauss–Markov theorem gives a guarantee without it. What it does assume implicitly is that large errors are rare, which outliers violate.
- “Solve it with the inverse of .” Mathematically correct, but numerically the most fragile choice; prefer a QR- or SVD-based solver.
- “The residual to minimize is given by the data.” It is a modeling choice. Algebraic residuals of a DLT, vertical distances in line fitting, and perpendicular distances (total least squares) give different answers when the noise is not where the model assumes it is.
- “A small residual means a good estimate.” A nearly rank-deficient , as on an edge in Lucas–Kanade, gives small residuals and poorly determined parameters; the covariance measures the latter.
Where It Is Used
- Motion estimation: Lucas–Kanade solves a small least-squares problem per window; variational methods such as Horn–Schunck minimize regularized quadratic energies over the whole image.
- State estimation: the Kalman filter update solves a weighted least-squares problem balancing prediction and measurement by their inverse covariances.
- Geometry: homography, fundamental-matrix, and camera-matrix estimation, calibration, triangulation, and bundle adjustment.
- Model fitting: lines, circles, conics, distortion models, and image alignment.
Related
- Gaussian Distribution
The bell-shaped probability distribution defined by a mean and a covariance, the default model for noise and uncertainty in estimation and tracking.
- Lucas–Kanade Method
A local, gradient-based method that estimates the displacement of an image window by assuming constant motion within it and solving a small least-squares problem, iterated with warping.
- Aperture Problem
Why motion seen through a small window is ambiguous along edges, so that only the component of motion across an edge can be measured locally.
- Kalman Filter
A recursive algorithm that estimates the hidden state of a linear dynamic system from a sequence of noisy measurements, widely used to smooth and predict object positions in tracking.
- Horn–Schunck Method
A global variational method that computes dense optical flow by minimizing brightness constancy errors together with a penalty on spatial variation of the flow, solved by a simple iterative averaging scheme.
References
- Legendre, A.-M. (1805). Nouvelles méthodes pour la détermination des orbites des comètes. Paris: Firmin Didot. Appendix: Sur la méthode des moindres quarrés.
- Stigler, S. M. (1981). Gauss and the Invention of Least Squares. The Annals of Statistics, 9(3), 465–474.
- Björck, Å. (1996). Numerical Methods for Least Squares Problems. Philadelphia: Society for Industrial and Applied Mathematics.
- Hartley, R. & Zisserman, A. (2004). Multiple View Geometry in Computer Vision (2nd ed.). Cambridge University Press.
- Triggs, B., McLauchlan, P. F., Hartley, R. I. & Fitzgibbon, A. W. (2000). Bundle Adjustment — A Modern Synthesis. Vision Algorithms: Theory and Practice, Lecture Notes in Computer Science 1883, 298–372.