Chapter 4: Model Fitting and Optimization
Techniques for fitting models to data, handling outliers with RANSAC, and using regularization methods like Total Variation for robust computer vision.
- Topics
- 3
- Videos
- 3
- Min read
- 19
Chapter Overview
Computer vision often requires finding mathematical models that explain observed data—whether it's a line through detected edge points, a transformation between images, or a surface representing an object. But real-world data is messy: sensors are noisy, features are misdetected, and outliers corrupt our measurements.
What is this chapter about? We study model fitting: given noisy, imperfect observations, how do we find the underlying model? This is fundamental to nearly every computer vision pipeline.
Why does this matter? Without robust fitting techniques, a single bad measurement can completely ruin your results. Imagine fitting a line to detected lane markers—one misdetection shouldn't send your self-driving car off the road.
How the topics connect: We start with Least Squares—the classic approach that works great when data is clean. Then we learn RANSAC, which elegantly handles outliers by finding consensus among the data. Finally, Total Variation shows how regularization can guide solutions toward realistic, edge-preserving results.
Chapter Roadmap
Click any topic to jump in
Least Squares
Linear regression, normal equations, and residuals — fitting models to data by minimizing error.
Outlier robustness and regularization
RANSAC
Random sampling for robust fitting — handling outliers that break least squares.
Regularization
Total variation, ROF model, and edge preservation — adding priors to prevent overfitting.
Topics
3 topics in this chapter
Every measurement a camera or sensor hands you is corrupted a little: a detected edge point sits a pixel off, a matched feature drifts, a depth reading jitters. Yet you still need a single clean model — a line, a plane, a curve — that explains all those noisy points at once. How do you choose the one model that best balances every conflicting observation? That is the model-fitting problem, and least squares is the oldest and most important answer. The image-processing tools from the previous chapter gave you edges and features; now we must turn those scattered detections into geometry. Least squares picks the parameters that make the total squared error as small as possible, and because that error is quadratic, the best model has a clean closed-form solution you can compute directly. We start here because the method is exact, fast, and provably optimal when the noise is Gaussian. Its one great weakness — a single wild outlier can drag the whole fit off course, since squaring shows no mercy to large errors — is exactly what motivates RANSAC in the next topic, so understanding least squares first makes both its power and its limits clear.
Definition
Least squares fits a model to data by choosing the parameters that minimize the sum of the squared residuals — the vertical gaps between each observation and the model's prediction. When the model is linear in its parameters, this minimization has a unique closed-form solution given by the normal equations.
In this topic
- 1Least Squares Criterion
- 2Normal Equations
- 3Residuals
Least Squares Criterion
The least squares criterion minimizes the sum of squared residuals—the vertical distances from data points to the fitted curve, squared and summed. Here:
- is the observed value at point
- is the model's prediction at that point
- The squaring penalizes large errors more heavily than small ones
This is the optimal solution when errors are normally distributed (Gaussian noise). However, it's sensitive to outliers because squaring amplifies large deviations. A single outlier can dramatically shift the fitted line.
The least squares objective minimizes the squared norm of the residual vector. Setting the gradient yields the normal equations. The quadratic form defines a paraboloid in parameter space with a unique minimum when is positive definite. Squaring penalizes large residuals disproportionately — a single outlier at distance contributes to the cost, giving it leverage proportional to on the solution.
Points (1,2), (2,3), (3,5) are fit with line y=x+1. Calculate the sum of squared errors.
Normal Equations
The normal equations provide a closed-form solution to the least squares problem:
- is the design matrix, where each row contains features for one data point (e.g., for linear regression)
- is the vector of parameters we're solving for (e.g., slope and intercept)
- is the vector of observed outputs (y values)
- is the transpose of
The solution is , which can be computed directly using matrix operations. This is efficient for small to medium datasets but can be numerically unstable for ill-conditioned problems.
The normal equations project the observation vector onto the column space of . Geometrically, is the point in closest to , and the residual is orthogonal to every column of — hence the name "normal" equations. The condition number means numerical errors are amplified quadratically; for ill-conditioned problems, the SVD-based pseudoinverse or QR decomposition is preferred.
For points (0,1), (1,3), write the design matrix A for fitting y=ax+b.
Residuals
Residuals are the differences between observed values () and predictions (). Analyzing residuals helps validate your model:
- Random scatter around zero: Good fit, model captures the pattern
- Curved pattern: Model is missing nonlinear structure
- Increasing spread: Heteroscedasticity—variance changes with
- Clustering: Possible outliers or model inadequacy
The sum of residuals in linear regression always equals zero, but the sum of squared residuals (RSS) measures overall fit quality.
The residual vector lies in the left null space of (orthogonal complement of the column space). For a correctly specified linear model with i.i.d. Gaussian noise , the residuals follow where is the hat matrix. The unbiased estimator uses degrees of freedom because the projection consumes of the original dimensions.
Fitted line predicts [10, 20, 30] but actual values are [12, 19, 32]. Compute residuals and RSS.
Theory Exercise
Problem:
Given 3 data points: (1, 2), (2, 4), (3, 5), fit a line y = ax + b using least squares. Calculate the optimal values of a and b.
Hints:
- Set up the sums: Σx, Σy, Σxy, Σx²
- Use the formulas: a = (nΣxy - ΣxΣy)/(nΣx² - (Σx)²)
- Then: b = (Σy - aΣx)/n
You have just seen that least squares gives the optimal fit when noise is gentle and Gaussian. But real vision data is not so kind: a feature matcher will happily return dozens of correct correspondences alongside a handful of completely wrong ones, and least squares, which squares every residual, lets even one gross outlier drag the entire fit off course. A single mismatched point can rotate your fitted line or warp your estimated transformation into nonsense. We need an estimator that ignores the bad points instead of averaging them in. RANSAC — Random Sample Consensus — is that estimator, and it is one of the most widely used algorithms in all of computer vision. Its idea is disarmingly simple: rather than fit all the data at once, repeatedly grab the minimum number of points needed to define a model, fit that tiny sample, and count how many other points agree. Outliers rarely conspire to agree on a wrong model, so the sample drawn entirely from inliers wins. This topic builds that loop, then derives how many iterations it takes to trust the result.
Definition
RANSAC (Random Sample Consensus) is an iterative robust-estimation method. It repeatedly draws the smallest sample of points that determines a model, fits the model, and counts the inliers whose error falls below a threshold. The model with the largest consensus set is kept, letting RANSAC recover the correct fit even when a large fraction of the data are outliers.
In this topic
- 1RANSAC Algorithm
- 2Inlier Threshold
- 3Number of Iterations
RANSAC Algorithm
RANSAC (Random Sample Consensus) is a robust estimation method that handles data with outliers:
- Sample: Randomly select the minimum points needed (2 for a line)
- Fit: Compute model from just these points
- Score: Count how many points agree with this model (inliers)
- Update: Keep the model with the most support
RANSAC works because outliers are unlikely to agree with the true model. With enough iterations, we'll sample only inliers and find the correct fit. Unlike least squares, a few bad points don't corrupt the result.
RANSAC is a probabilistic algorithm that draws minimal random subsets of size from data points. Each subset determines a unique model (e.g., 2 points define a line), and the consensus set is . The probability that a given sample contains only inliers is where is the inlier ratio. After iterations, the probability of never drawing an all-inlier sample is , which decreases exponentially in . RANSAC's expected complexity is where scales as — exponential in the sample size but independent of the total number of outliers.
You have 10 points: 8 on line y=x and 2 outliers. RANSAC samples points (1,1) and (5,5). How many inliers?
Inlier Threshold
The threshold (tau) determines which points are considered inliers:
- A point is an inlier if its distance to the model is less than
- Too small: Rejects valid data, underfits
- Too large: Includes outliers, corrupts the fit
How to choose : Typically set to 2-3× the expected noise standard deviation. For image features, this might be 1-3 pixels. For depth data, it depends on sensor noise characteristics.
The threshold defines the decision boundary between inliers and outliers. For zero-mean Gaussian noise with known standard deviation , the squared residual follows a distribution with degrees of freedom (1 for a line, 2 for a homography point). Setting at confidence level gives for and for . A threshold that is too tight reduces the effective inlier ratio , exponentially increasing the required iterations via the formula .
Feature detector has noise σ=0.5 pixels. What inlier threshold should RANSAC use?
Number of Iterations
This formula calculates the iterations needed for success probability :
- : Desired probability of success (typically 0.99)
- : Inlier ratio (fraction of good points, e.g., 0.7)
- : Minimum sample size (2 for lines, 4 for homographies)
- : Required iterations
Example: With 30% outliers () fitting a line (): iterations for 99% confidence.
More outliers or larger dramatically increase required iterations.
The iteration formula comes from requiring the failure probability . Taking logarithms (both sides negative, so the inequality flips) gives . For small , , so . This reveals the exponential dependence on : doubling the minimal sample size squares the required iterations. For a homography () with 50% outliers (), , while for the fundamental matrix (), — motivating the 5-point algorithm that reduces .
Fitting a homography (n=4) with 50% outliers. How many iterations for 99% success?
Theory Exercise
Problem:
You have 100 data points with 40% outliers. You're fitting a line (n=2). How many RANSAC iterations are needed for 99% success probability?
Hints:
- Inlier ratio w = 0.6
- Use k = log(1-p) / log(1-w^n)
- p = 0.99, n = 2
Related Problems on PixelBank
RANSAC taught us to fit a model when the data contains outliers, but sometimes the problem is not a few bad points — it is that the answer we want is underdetermined or swamped by noise. Denoising an image is exactly this case: countless pixels are each corrupted a little, and simply trusting the measurements reproduces the noise, while blindly smoothing them destroys the very edges that make the image meaningful. What we need is a way to encode a preference — a prior belief that real images are mostly smooth but punctuated by sharp boundaries — and let that belief guide the solution. This is regularization, and Total Variation is a particularly elegant instance of it. Where least squares only penalized how far a model strayed from the data, regularization adds a second penalty on how rough the solution itself is. Total Variation measures roughness as the summed magnitude of the gradient, and minimizing it while staying faithful to the input yields the famous ROF denoising model. This topic develops total variation, the ROF energy, and why its penalty preserves edges where quadratic smoothing would erase them.
Definition
Total variation is the integral of the gradient magnitude of a signal or image, a measure of its total oscillation. Total-variation regularization, embodied in the Rudin-Osher-Fatemi model, denoises by finding the image that minimizes total variation while staying close to the noisy input, using an penalty that suppresses noise yet preserves sharp edges.
In this topic
- 1Total Variation
- 2ROF Model
- 3Edge Preservation
Total Variation
Total Variation measures how much a signal oscillates — the total change accumulated across it. Here is the gradient and is its magnitude; the integral sums that magnitude over the whole image. A flat region contributes nothing because its gradient is zero, while every ramp or edge adds its height. This is the key to denoising: random noise inflates TV with countless tiny fluctuations, so shrinking TV removes them, yet a genuine edge is one large jump that TV barely penalizes. Building on the gradients from image processing, TV smooths noise while sharp boundaries survive.
Total variation measures the total arc length of the 1D signal graph, or equivalently the norm of the gradient field. For piecewise-constant signals, equals the sum of absolute jump heights. The space of bounded-variation functions is strictly larger than the Sobolev space , meaning TV is finite even for functions with jump discontinuities (edges), whereas the gradient norm diverges at discontinuities. This is precisely why TV regularization preserves edges.
Compare TV of u=[100,100,100] vs v=[100,110,100]. Which has higher TV?
ROF Model
The Rudin-Osher-Fatemi (ROF) model denoises by balancing two competing goals. The data-fidelity term keeps the output close to the noisy input , while the regularizer pushes toward smoothness by penalizing total variation. The weight sets the trade-off: a large smooths aggressively and can erase faint texture along with noise, while a small barely denoises and leaves the result close to . Because both terms are convex, the minimum is unique and solvable. This is regularization in action — adding a prior about what clean images look like, extending least squares' idea of penalizing bad fits to penalizing rough solutions.
The ROF (Rudin-Osher-Fatemi) functional is a convex optimization problem whose Euler-Lagrange equation involves the curvature operator . The parameter controls the bias-variance tradeoff: as , (data fit, high variance); as , converges to a constant (low variance, high bias). The solution forms a one-parameter family of piecewise-constant approximations to , and the "staircasing" effect — flat regions separated by sharp jumps — is a direct consequence of the penalty promoting sparsity in the gradient domain.
Noisy image f has high-frequency noise. What happens if is too large?
Edge Preservation
Why does TV preserve edges when ordinary Gaussian smoothing blurs them? The answer is the shape of the penalty. regularization penalizes the squared gradient , so a strong edge with a large gradient costs disproportionately much and gets flattened away along with the noise. TV uses the penalty , which grows only linearly, so a single sharp edge is comparatively cheap and is allowed to remain. The result is a piecewise-smooth image: flat regions with crisp boundaries, which is how natural scenes usually look. The failure mode is staircasing — gentle gradients get broken into flat steps — because the penalty prefers a few large jumps over many small ones.
The norm imposes a constant marginal penalty per unit of gradient magnitude, while the norm imposes an increasing marginal penalty. Formally, the proximal operator of the norm is soft-thresholding , which shrinks small gradients to zero while only slightly reducing large ones. In contrast, the proximal operator scales all gradients by , uniformly attenuating edges and noise alike. This soft-thresholding property is equivalent to sparsity promotion — minimization seeks solutions with few nonzero gradients (few edges), which matches natural image statistics.
An edge has gradient 100. Compare L1 vs L2 penalty. What if gradient doubles to 200?
Theory Exercise
Problem:
For a 1D signal u = [10, 10, 50, 50, 50, 20, 20], calculate the total variation TV(u).
Hints:
- TV = sum of |u[i+1] - u[i]|
- Only edges (changes) contribute
- Constant regions contribute zero