Image Thresholding
Imagine a scanner turning a printed page into a clean black-and-white document. Every pixel must become either ink or paper, with nothing in between. This is the essence of image thresholding, the simplest and oldest technique in Image Segmentation. A single number, or a slowly varying surface of numbers, decides the fate of every pixel. Each one becomes foreground or background, object or void, signal or noise. Thresholding matters because it is the cheapest possible segmentation algorithm. Cheap operations that run in a single pass over pixels are the backbone of real-time systems. Barcode readers, document scanners, fingerprint preprocessors, cell counters in microscopy, and lane-marking detectors in early automotive vision pipelines all lean on thresholding as a first or final stage. It converts a continuous grayscale image, described by its histogram of intensities, into a binary map. Downstream algorithms like Region Growing Segmentation and Morphological Operations can consume this map directly. The big picture is a spectrum of sophistication built on one idea. Pick a cutoff value , and classify each pixel by comparing its intensity to . The spectrum runs from a single global constant, through data-driven global choices like Otsu's method, to spatially varying adaptive thresholds that track local illumination. Each rung on this ladder trades simplicity for robustness against uneven lighting, noise, and multimodal scenes. This article builds thresholding from first principles. It explains how a histogram becomes a decision rule. It shows how Otsu's method derives an optimal cutoff from variance statistics. It covers how adaptive and local thresholding survive shadows and gradients, and where the technique quietly fails. Every claim about complexity and optimality is derived, not asserted.
- Thresholding converts a grayscale image into a binary image by comparing each pixel to a cutoff value .
- Global thresholding uses one for the whole image; adaptive thresholding uses a spatially varying .
- Otsu's method picks automatically by maximizing between-class variance of a bimodal histogram.
- Otsu's algorithm runs in time after an histogram pass, where is the number of gray levels and the pixel count.
- Adaptive (local) thresholding, e.g. mean- or Gaussian-weighted windows, handles uneven illumination that defeats global methods.
- Thresholding is the on-ramp to Region Growing Segmentation and Morphological Operations, which clean up and interpret the binary map.
Thresholding reduces segmentation to a single decision rule — compare each pixel's intensity to a cutoff — and the art lies entirely in choosing that cutoff well, globally or locally.
The idea
Image thresholding is a pointwise transformation that maps a grayscale image to a binary image using a decision rule based on intensity alone:
Here is the threshold. When is a single scalar applied uniformly across the image, this is global thresholding. When becomes a function that varies with position — typically computed from statistics of a local neighborhood around each pixel — this is adaptive or local thresholding. The central assumption behind global thresholding is that the image's histogram is bimodal: pixels cluster into two populations (say, dark text and light paper), each forming a peak, separated by a valley. The threshold should sit in that valley. Otsu's method, introduced by Nobuyuki Otsu in 1979, formalizes "sitting in the valley" as an optimization problem: choose to maximize the separation between the two resulting pixel classes, measured by between-class variance, without needing to know the true distributions in advance. Global thresholding fails when illumination is uneven — a single valley in the histogram does not exist, or worse, the same object intensity appears bright in one image region and dark in another due to a shadow or gradient light source. Adaptive thresholding solves this by computing a local threshold from a window around each pixel, most commonly the local mean or a Gaussian-weighted local mean, minus a constant offset to bias toward the darker class. This lets the decision surface bend and follow illumination changes across the image, at the cost of more computation and new tunable parameters (window size, offset).
How it works
Step 1: Build the histogram. For an 8-bit grayscale image with possible intensities, compute , the count of pixels with intensity , for . This requires one pass over all pixels.
Step 2: Global fixed threshold (simplest case). If a threshold is known in advance — from calibration, a fixed scanner setting, or domain knowledge — apply it directly: ``` function GLOBAL_THRESHOLD(image, T): for each pixel (x, y) in image: output(x, y) = 1 if image(x, y) >= T else 0 return output ``` This is and needs no histogram. It is fragile: if lighting shifts, must be re-tuned by hand.
Step 3: Iterative (isodata) threshold selection. A simple automatic method starts with a guess and refines it by alternately splitting the histogram and recomputing the midpoint of the two class means: ``` function ISODATA_THRESHOLD(histogram, levels): T = mean intensity of entire histogram # initial guess repeat:
# split pixels into two classes by current T mu_low = mean intensity of pixels with value < T mu_high = mean intensity of pixels with value >= T T_new = (mu_low + mu_high) / 2 if |T_new - T| < epsilon: break T = T_new return T ``` This converges because each iteration moves toward the midpoint of two means that themselves depend on — a fixed-point iteration that is monotone and bounded, hence convergent for well-behaved (bimodal) histograms.
Step 4: Otsu's method — the standard automatic global threshold. Otsu's method treats every possible threshold as a candidate split of the histogram into class (intensities ) and class (intensities ), and picks the that maximizes the between-class variance:
where are the class probabilities (fraction of pixels in each class) and are the class means. The key algorithmic trick is that all four quantities can be updated incrementally as sweeps from to , using cumulative sums, so the entire search is a single linear pass over gray levels rather than independent full passes over pixels. ``` function OTSU_THRESHOLD(histogram, L): N = sum(histogram) # total pixel count sum_total = Σ_{i=0}^{L-1} i histogram[i] w0 = 0.0 # running weight (probability) of class 0 sum0 = 0.0 # running weighted intensity sum of class 0 best_var = -infinity best_t = 0 for t = 0 to L - 1: w0 += histogram[t] / N if w0 == 0: continue w1 = 1 - w0 if w1 == 0: break # no pixels left in class 1 sum0 += t histogram[t] mu0 = sum0 / (w0 N) mu1 = (sum_total - sum0) / (w1 N) between_var = w0 w1 (mu0 - mu1)^2 if between_var > best_var: best_var = between_var best_t = t return best_t ```
Step 5: Apply the chosen threshold. Once (fixed, isodata, or Otsu) is known, apply `GLOBAL_THRESHOLD` above — an pass.
Step 6: Adaptive thresholding for uneven illumination. Instead of one global , compute a local threshold per pixel from a window centered at : ``` function ADAPTIVE_THRESHOLD(image, window_size, C): integral = COMPUTE_INTEGRAL_IMAGE(image) # for O(1) window sums half = window_size / 2 for each pixel (x, y) in image: local_mean = WINDOW_MEAN(integral, x, y, half) T_local = local_mean - C output(x, y) = 1 if image(x, y) >= T_local else 0 return output ``` The integral image (summed-area table) is what keeps this efficient: precomputing it in one pass lets any rectangular window sum be fetched in via four array lookups, so the whole adaptive pass remains regardless of window size. A Gaussian-weighted variant replaces the box mean with a weighted local mean, trading a small constant-factor slowdown (or a separable convolution, still for fixed kernel support) for smoother, less blocky thresholds.
Complexity & correctness
Time complexity. Building the histogram requires one pass over all pixels: . Otsu's search sweeps the possible thresholds once, maintaining running sums and incrementally in constant time per level, giving for the search. Since is a small fixed constant (256 for 8-bit images, independent of image size), the dominant cost is for the histogram build plus for the final pixelwise apply, so total time is for any practical image where . This is the same asymptotic class as simply reading the image once — thresholding is essentially free beyond I/O. A naive implementation that recomputes from scratch for every candidate costs or ; the incremental cumulative-sum formulation is what brings this down to , and is the reason Otsu's method is practical for real-time use.
Space complexity. The histogram needs space. The output binary image needs space (or if packed as bits). No auxiliary structures beyond a few running scalars are needed for Otsu's search itself. For adaptive thresholding, computing the integral image costs time and space, and after that every window-mean query is regardless of window size , so the total remains rather than the naive of recomputing each window sum from scratch.
Correctness of Otsu's method. The argument rests on a classical variance decomposition. For any split of the pixel population into two classes with the global variance fixed (a property of the image, independent of ), it is a standard fact from statistics that
where is the within-class variance (weighted average of each class's internal variance) and is the between-class variance defined above. Because does not depend on , maximizing over is exactly equivalent to minimizing over . So Otsu's method, though phrased as "maximize between-class separation," is simultaneously performing the more intuitive operation "minimize the spread inside each class" — the threshold that makes each class as internally homogeneous as possible. This equivalence is not a heuristic approximation; it follows algebraically from the total-variance decomposition and holds for every histogram, bimodal or not.
Correctness of the incremental update. The class weight and weighted sum both satisfy simple recurrences,
so each can be updated in from the previous value, which is exactly what the pseudocode does; this is why the -level sweep costs total rather than per level.
Honesty about tradeoffs. Otsu's method is optimal only under its own objective — it finds the global optimum of between-class variance in time, which is provably correct as a maximization, but that objective is a good proxy for "correct segmentation" only when the histogram is genuinely (or approximately) bimodal with comparable class sizes and variances. It can pick poor thresholds when one class vastly outnumbers the other, when noise creates spurious peaks, or when the true separation is not variance-based (e.g., textured regions with same mean, different texture). Adaptive thresholding trades this global optimality for local robustness: it has no single "correct" objective being maximized, and its quality depends entirely on choosing window size and offset appropriately for the spatial scale of both the object and the illumination gradient.
Worked example
Consider a small 8-level (toy) grayscale image so histogram counts are easy to track by hand. Suppose the histogram (gray levels 0–7, ) over pixels is:
| level | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 2 | 5 | 3 | 0 | 0 | 2 | 4 | 4 |
This is bimodal: a dark cluster around levels 0–2 (10 pixels) and a bright cluster around levels 5–7 (10 pixels), separated by an empty valley at levels 3–4. Trace `OTSU_THRESHOLD`, tracking , , , and at each candidate :
| 0 | 2/20=0.10 | 0 | 0.00 | 0.90 | ||
| 1 | 7/20=0.35 | 5 | 0.714 | 0.65 | ||
| 2 | 10/20=0.50 | 11 | 1.10 | 0.50 | ||
| 3 | 10/20=0.50 | 11 | 1.10 | 0.50 | (unchanged, ) | |
| 4 | 10/20=0.50 | 11 | 1.10 | 0.50 | (unchanged, ) | |
| 5 | 12/20=0.60 | 21 | 1.75 | 0.40 | ||
| 6 | 16/20=0.80 | 45 | 2.81 | 0.20 |
The loop stops before since would hit 0. The maximum occurs at both and (a tie, since contributes nothing); the algorithm as written keeps the first maximum found (strict `>` comparison), so `best_t = 2`. This correctly lands the threshold in the empty valley between the two clusters, at the boundary of the dark class — exactly where a human would draw the line. Any in produces an identical binary segmentation here, since no pixels exist at levels 3 or 4; the tie is a harmless artifact of the empty valley, not an error. For contrast, imagine a second scene: the same object but photographed with a light gradient, so the left half of the image is globally brighter by +2 levels. A single global (roughly the Otsu cutoff above) would now misclassify part of the left-half background as foreground, because "bright due to lighting" and "bright due to being foreground" become indistinguishable to a global rule. This is precisely the scenario adaptive thresholding is designed for: a local window mean on the left half would sit near the local background level even though it is elevated, and subtracting the local mean (minus ) recovers the correct local decision boundary that a single global cannot express.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Assuming Otsu implies bimodality | Otsu always returns some threshold, even on a unimodal or noisy histogram | Inspect the histogram; consider multi-level Otsu or a different segmentation method for non-bimodal data |
| Ignoring illumination gradients | Global cannot express a spatially varying decision surface | Use adaptive thresholding with window size matched to the illumination scale |
| Window size mismatch in adaptive methods | Too small a window is noisy per-pixel; too large approximates global thresholding and reintroduces the same failure | Choose window size larger than texture/noise scale but smaller than the illumination gradient's scale |
| Off-by-one at histogram boundaries | Using `>` vs `>=` inconsistently between binarization and Otsu search changes which class boundary pixels land in | Fix and document a single convention (e.g., is foreground) and use it everywhere |
| Treating the binary map as final output | Thresholding alone leaves speckle noise and holes | Follow with Morphological Operations (opening/closing) before feeding into Region Growing Segmentation or connected-component labeling |
Pioneers & history
Otsu's method is named for the Japanese electrical engineer who formalized the variance-maximization criterion still taught as the default automatic threshold selector today.
Origins · 1 minNobuyuki Otsu and how this was discovered
Otsu's 1979 paper, "A Threshold Selection Method from Gray-Level Histograms," derived the between-class variance criterion and its equivalence to within-class variance minimization via the total variance decomposition, and showed the search could be computed in a single linear pass — a result still cited as the standard baseline in segmentation research and implemented in essentially every computer vision library.
Where this matters
Document scanning and OCR pipelines use adaptive thresholding as a mandatory first stage: scanned pages rarely have uniform illumination, and OCR accuracy depends heavily on clean binarization before character segmentation. Barcode and QR code readers apply Otsu-style or adaptive thresholding to convert camera frames into clean black-and-white modules under variable lighting from phone flashes or ambient light. Medical and microscopy imaging pipelines use thresholding to isolate cells, nuclei, or tissue regions from background stain, often as a preprocessing step before connected-component counting. Industrial machine vision systems on assembly lines threshold parts against a controlled background for fast defect detection, exploiting the speed of thresholding for high-throughput inspection. Thresholding is also embedded inside larger pipelines: it commonly feeds directly into Region Growing Segmentation as a seed-selection or homogeneity criterion, and its binary output is almost always cleaned with Morphological Operations like erosion, dilation, opening, and closing before any downstream shape or contour analysis. Even modern deep-learning segmentation systems sometimes use adaptive thresholding on network confidence maps to convert soft probability outputs into hard binary masks.
Ask the tutor: How would you extend Otsu's method to automatically choose two thresholds for a three-class (dark/mid/bright) image?
Is Otsu's method guaranteed to find the globally optimal threshold?
Yes, but only with respect to its own objective. The algorithm exhaustively evaluates every possible integer threshold from 0 to and keeps the one maximizing between-class variance, so within that discrete search space it is exact, not approximate — there is no local-optimum trap the way there can be with iterative or gradient-based methods. The caveat is that "maximizes between-class variance" is not the same as "produces the visually or semantically correct segmentation." On a histogram that is not close to bimodal, the globally optimal Otsu threshold by this criterion can still be a poor segmentation boundary in practice.
When should I use global thresholding instead of adaptive thresholding?
Use global thresholding when illumination is controlled and roughly uniform across the image — for example, a fixed industrial inspection camera with stable lighting, or a scanner with a calibrated light source. Global methods are cheaper (no window computation needed beyond the histogram), easier to reason about, and produce a single interpretable cutoff value. Reach for adaptive thresholding as soon as you observe a shadow, vignette, gradient light source, or any scenario where the "same" object surface produces different absolute intensities in different parts of the frame; in these cases a single global cutoff cannot separate foreground from background everywhere at once.
Can thresholding handle color images directly?
Not directly in its classic form, since it is defined on a single scalar intensity per pixel. The usual approach converts the color image to grayscale first, or thresholds each channel independently and combines the results with logical operations, or thresholds a single meaningful channel such as saturation or hue in HSV space when color, not brightness, is the discriminating feature. More sophisticated color segmentation typically moves beyond simple per-channel thresholding into clustering methods like k-means in color space, which thresholding can be seen as a one-dimensional, two-cluster special case of.
What happens if the histogram has three or more peaks instead of two?
Standard Otsu thresholding still returns a single cutoff that best separates the histogram into two groups by variance, which may crudely lump two of the three populations together on one side of the split. A direct extension, multi-level Otsu, generalizes the same between-class variance objective to thresholds separating classes, searched via nested sums or dynamic programming, at a higher but still polynomial cost in . Alternatively, multi-peaked histograms are often better handled by clustering methods or by first isolating regions of interest so that each region's local histogram becomes closer to bimodal.
How does thresholding relate to region growing and morphological operations?
Thresholding produces a raw binary map, which is rarely clean enough to use as a final segmentation: it typically contains speckle noise, small holes, and jagged boundaries from per-pixel decisions made independently of their neighbors. Morphological Operations such as erosion, dilation, opening, and closing are applied immediately afterward to remove small noise blobs and fill small gaps, using purely local shape-based rules on the binary map. Region Growing Segmentation can either consume the cleaned binary map as seed regions, or replace thresholding entirely when connectivity and neighborhood similarity, not a single global intensity cutoff, are the right criteria for grouping pixels.
Why does Otsu's method break down when one class is much smaller than the other?
The between-class variance term contains the product , which is maximized when class sizes are balanced (near 0.5 each) and shrinks toward zero as one class's weight approaches 0 or 1. If the true foreground object occupies only a tiny fraction of the image — a small tumor in a large scan, a thin scratch on a large clean surface — the variance-maximizing split can be pulled away from the true object boundary toward a more "balanced" but semantically wrong split, because the objective inherently rewards balanced partitions over correct but lopsided ones.
Is thresholding still relevant given modern deep learning segmentation networks?
Yes, for several concrete reasons. Thresholding remains the cheapest possible baseline, useful for real-time embedded systems, quick prototyping, and preprocessing steps that reduce the burden on heavier downstream models. It is also embedded inside modern pipelines: a semantic segmentation network typically outputs a per-pixel probability map, which still must be converted to a hard binary or multi-class mask, and that final step is frequently an adaptive or Otsu-style threshold applied to the network's confidence scores. Thresholding and deep segmentation are complementary tools operating at different points along the same pipeline, not competitors.