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 TT, and classify each pixel by comparing its intensity to TT. 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.

Key takeaways
  • Thresholding converts a grayscale image into a binary image by comparing each pixel to a cutoff value TT.
  • Global thresholding uses one TT for the whole image; adaptive thresholding uses a spatially varying T(x,y)T(x,y).
  • Otsu's method picks TT automatically by maximizing between-class variance of a bimodal histogram.
  • Otsu's algorithm runs in O(L)O(L) time after an O(N)O(N) histogram pass, where LL is the number of gray levels and NN 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.
The core insight

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 I(x,y)I(x,y) to a binary image B(x,y)∈{0,1}B(x,y) \in \{0, 1\} using a decision rule based on intensity alone:

B(x,y)={1if I(x,y)≥T0otherwiseB(x,y) = \begin{cases} 1 & \text{if } I(x,y) \ge T \\ 0 & \text{otherwise} \end{cases}

Here TT is the threshold. When TT is a single scalar applied uniformly across the image, this is global thresholding. When TT becomes a function T(x,y)T(x,y) 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 TT 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 CC 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 L=256L = 256 possible intensities, compute h[i]h[i], the count of pixels with intensity ii, for i=0,…,L−1i = 0, \dots, L-1. This requires one pass over all NN 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 O(N)O(N) and needs no histogram. It is fragile: if lighting shifts, TT 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 TT toward the midpoint of two means that themselves depend on TT — 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 t∈{0,…,L−1}t \in \{0, \dots, L-1\} as a candidate split of the histogram into class C0C_0 (intensities ≤t\le t) and class C1C_1 (intensities >t> t), and picks the tt that maximizes the between-class variance:

σB2(t)=ω0(t) ω1(t) (μ0(t)−μ1(t))2\sigma_B^2(t) = \omega_0(t)\,\omega_1(t)\,\big(\mu_0(t) - \mu_1(t)\big)^2

where ω0(t),ω1(t)\omega_0(t), \omega_1(t) are the class probabilities (fraction of pixels in each class) and μ0(t),μ1(t)\mu_0(t), \mu_1(t) are the class means. The key algorithmic trick is that all four quantities can be updated incrementally as tt sweeps from 00 to L−1L-1, using cumulative sums, so the entire search is a single linear pass over LL gray levels rather than LL independent full passes over NN 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 TT (fixed, isodata, or Otsu) is known, apply `GLOBAL_THRESHOLD` above — an O(N)O(N) pass.

Step 6: Adaptive thresholding for uneven illumination. Instead of one global TT, compute a local threshold per pixel from a window WW centered at (x,y)(x,y): ``` 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 O(N)O(N) pass lets any rectangular window sum be fetched in O(1)O(1) via four array lookups, so the whole adaptive pass remains O(N)O(N) 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 O(N)O(N) for fixed kernel support) for smoother, less blocky thresholds.

Figure
From histogram to binary map: two paths through the thresholding pipeline
Thresholding Pipeline Grayscale Image I(x,y) Histogram h[i] choose strategy Global: Otsu / Isodata one scalar T for whole image O(L) search after O(N) histogram Adaptive: local mean − C T(x,y) per window O(N) via integral image Compare I(x,y) to T pixelwise, O(N) Binary map B(x,y)

Complexity & correctness

Time complexity. Building the histogram requires one pass over all NN pixels: O(N)O(N). Otsu's search sweeps the LL possible thresholds once, maintaining running sums w0w_0 and sum0\text{sum}_0 incrementally in constant time per level, giving O(L)O(L) for the search. Since LL is a small fixed constant (256 for 8-bit images, independent of image size), the dominant cost is O(N)O(N) for the histogram build plus O(N)O(N) for the final pixelwise apply, so total time is O(N+L)=O(N)O(N + L) = O(N) for any practical image where N≫LN \gg L. This is the same asymptotic class as simply reading the image once — thresholding is essentially free beyond I/O. A naive implementation that recomputes ω0,ω1,μ0,μ1\omega_0, \omega_1, \mu_0, \mu_1 from scratch for every candidate tt costs O(L2)O(L^2) or O(L⋅N)O(L \cdot N); the incremental cumulative-sum formulation is what brings this down to O(L)O(L), and is the reason Otsu's method is practical for real-time use.

Space complexity. The histogram needs O(L)O(L) space. The output binary image needs O(N)O(N) space (or O(N/8)O(N/8) 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 O(N)O(N) time and O(N)O(N) space, and after that every window-mean query is O(1)O(1) regardless of window size ww, so the total remains O(N)O(N) rather than the naive O(Nw2)O(N w^2) 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 σT2\sigma_T^2 fixed (a property of the image, independent of tt), it is a standard fact from statistics that

σT2=σW2(t)+σB2(t)\sigma_T^2 = \sigma_W^2(t) + \sigma_B^2(t)

where σW2(t)\sigma_W^2(t) is the within-class variance (weighted average of each class's internal variance) and σB2(t)\sigma_B^2(t) is the between-class variance defined above. Because σT2\sigma_T^2 does not depend on tt, maximizing σB2(t)\sigma_B^2(t) over tt is exactly equivalent to minimizing σW2(t)\sigma_W^2(t) over tt. 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 ω0(t)=∑i≤th[i]/N\omega_0(t) = \sum_{i \le t} h[i]/N and weighted sum sum0(t)=∑i≤ti⋅h[i]\text{sum}_0(t) = \sum_{i \le t} i \cdot h[i] both satisfy simple recurrences,

ω0(t)=ω0(t−1)+h[t]/N,sum0(t)=sum0(t−1)+t⋅h[t],\omega_0(t) = \omega_0(t-1) + h[t]/N, \qquad \text{sum}_0(t) = \text{sum}_0(t-1) + t \cdot h[t],

so each can be updated in O(1)O(1) from the previous value, which is exactly what the pseudocode does; this is why the LL-level sweep costs O(L)O(L) total rather than O(L)O(L) 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 O(L)O(L) 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 CC 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, L=8L=8) over N=20N=20 pixels is:

level ii01234567
h[i]h[i]25300244

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. sum_total=∑i⋅h[i]=0(2)+1(5)+2(3)+3(0)+4(0)+5(2)+6(4)+7(4)=0+5+6+0+0+10+24+28=73\text{sum\_total} = \sum i \cdot h[i] = 0(2)+1(5)+2(3)+3(0)+4(0)+5(2)+6(4)+7(4) = 0+5+6+0+0+10+24+28 = 73 Trace `OTSU_THRESHOLD`, tracking w0w_0, μ0\mu_0, μ1\mu_1, and σB2(t)\sigma_B^2(t) at each candidate tt:

ttw0=ω0w_0=\omega_0sum0\text{sum}_0μ0\mu_0w1w_1μ1\mu_1σB2(t)=w0w1(μ0−μ1)2\sigma_B^2(t)=w_0 w_1(\mu_0-\mu_1)^2
02/20=0.1000.000.9073/18=4.0673/18=4.060.10⋅0.90⋅(4.06)2=1.4820.10\cdot0.90\cdot(4.06)^2 = 1.482
17/20=0.3550.7140.6568/13=5.2368/13=5.230.35⋅0.65⋅(4.52)2=4.6290.35\cdot0.65\cdot(4.52)^2 = 4.629
210/20=0.50111.100.5062/10=6.2062/10=6.200.50⋅0.50⋅(5.10)2=6.5030.50\cdot0.50\cdot(5.10)^2 = 6.503
310/20=0.50111.100.506.206.206.5036.503 (unchanged, h[3]=0h[3]=0)
410/20=0.50111.100.506.206.206.5036.503 (unchanged, h[4]=0h[4]=0)
512/20=0.60211.750.4052/8=6.5052/8=6.500.60⋅0.40⋅(4.75)2=5.4150.60\cdot0.40\cdot(4.75)^2 = 5.415
616/20=0.80452.810.2028/4=7.0028/4=7.000.80⋅0.20⋅(4.19)2=2.8080.80\cdot0.20\cdot(4.19)^2 = 2.808

The loop stops before t=7t=7 since w1w_1 would hit 0. The maximum σB2(t)=6.503\sigma_B^2(t) = 6.503 occurs at both t=2t=2 and t=3t=3 (a tie, since h[3]=0h[3]=0 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 tt in {2,3,4}\{2, 3, 4\} 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 T=2.5T=2.5 (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 CC) recovers the correct local decision boundary that a single global TT cannot express.

Common pitfalls & traps

PitfallWhy it happensFix
Assuming Otsu implies bimodalityOtsu always returns some threshold, even on a unimodal or noisy histogramInspect the histogram; consider multi-level Otsu or a different segmentation method for non-bimodal data
Ignoring illumination gradientsGlobal TT cannot express a spatially varying decision surfaceUse adaptive thresholding with window size matched to the illumination scale
Window size mismatch in adaptive methodsToo small a window is noisy per-pixel; too large approximates global thresholding and reintroduces the same failureChoose window size larger than texture/noise scale but smaller than the illumination gradient's scale
Off-by-one at histogram boundariesUsing `>` vs `>=` inconsistently between binarization and Otsu search changes which class boundary pixels land inFix and document a single convention (e.g., ≥T\ge T is foreground) and use it everywhere
Treating the binary map as final outputThresholding alone leaves speckle noise and holesFollow 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
NO
Nobuyuki Otsu
b. 1948 · Electrical Engineering Laboratory, Japan; foundational contribution to automatic image thresholding

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.

History
1962
— Rosenfeld and others formalize early histogram-based binarization for document image analysis.
1975
— Adaptive and locally-computed threshold techniques emerge for scanned text under uneven illumination.
1979
— Nobuyuki Otsu publishes the between-class variance maximization method for automatic threshold selection.
1985
— Sauvola-style and integral-image-friendly local thresholding techniques mature for document binarization.
2000
s — Integral images (popularized alongside Viola-Jones face detection) make adaptive thresholding practical in real time.

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 O(N)O(N) 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 L−1L-1 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 k−1k-1 thresholds separating kk classes, searched via nested sums or dynamic programming, at a higher but still polynomial cost in LL. 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 σB2(t)=ω0(t)ω1(t)(μ0(t)−μ1(t))2\sigma_B^2(t) = \omega_0(t)\omega_1(t)(\mu_0(t)-\mu_1(t))^2 contains the product ω0ω1\omega_0 \omega_1, 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.

Before this

Where this leads