TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Histograms, Contrast and Thresholding

Histograms, Contrast and Thresholding

Two images of the same scene can differ only in exposure: one dull and grey, one with deep blacks and bright whites. A histogram (how many pixels have each grey level) shows the difference at a glance, and simple functions of it fix a lot: stretching or equalising spreads a cramped histogram over the full range, and a threshold splits it into foreground and background. Thresholding is the oldest segmentation method and still the first thing to try on documents, microscopy, industrial inspection and any image where the object is clearly brighter or darker than its surroundings. This lesson builds each tool from the histogram in NumPy, checks it against OpenCV and scikit-image, and shows where a single global threshold breaks.

The histogram

For an 8-bit grey image with NN pixels, the histogram counts h(v)h(v) for every level v=0,…,255v = 0, \dots, 255. Divided by NN it is a probability distribution p(v)p(v), and its running sum is the cumulative distribution function:

p(v)=h(v)N,CDF(v)=∑u=0vp(u)p(v) = \frac{h(v)}{N}, \qquad \text{CDF}(v) = \sum_{u=0}^{v} p(u)

The histogram forgets where each pixel is: every rearrangement of the pixels has the same histogram. That makes it cheap and robust (rotation, flips and small shifts do not change it) and also limited (it cannot tell a face from a scrambled face).

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

img = data.camera()
h_np = np.bincount(img.ravel(), minlength=256)                       # from scratch
h_cv = cv2.calcHist([img], [0], None, [256], [0, 256]).ravel().astype(int)
print("bincount == calcHist:", np.array_equal(h_np, h_cv), "| pixels:", int(h_np.sum()))
used = np.nonzero(h_np)[0]
print("darkest", int(used[0]), "brightest", int(used[-1]), "| mean", round(float(img.mean()), 1), "std", round(float(img.std()), 1), "median", float(np.median(img)))
print("most common value", int(h_np.argmax()), "with", int(h_np.max()), "pixels")
coarse = h_np.reshape(8, 32).sum(1)                                  # 8 bins of 32 levels
for i, c in enumerate(coarse):
    print(f"{i * 32:3d}-{i * 32 + 31:3d} {'#' * int(round(40 * c / coarse.max())):40s} {int(c)}")

low = (img // 4 + 90).astype(np.uint8)                               # a dull copy: levels 90..153
print("low contrast:", int(low.min()), "to", int(low.max()), "std", round(float(low.std()), 1))
mm = cv2.normalize(low, None, 0, 255, cv2.NORM_MINMAX)               # min-max stretch
lo, hi = np.percentile(low, [2, 98])
pct = np.clip((low.astype(np.float64) - lo) / (hi - lo) * 255, 0, 255).astype(np.uint8)
print("min-max stretch:", int(mm.min()), "to", int(mm.max()), "std", round(float(mm.std()), 1), "levels", len(np.unique(mm)))
print(f"2-98 percentile stretch ({lo:.0f}, {hi:.0f}):", "std", round(float(pct.std()), 1), "clipped", round(float(((low < lo) | (low > hi)).mean() * 100), 1), "%")
bincount == calcHist: True | pixels: 262144
darkest 0 brightest 255 | mean 129.1 std 73.6 median 152.0
most common value 27 with 4957 pixels
  0- 31 ################################         60262
 32- 63 #########                                17308
 64- 95 ###                                      5237
 96-127 ######                                   10778
128-159 ###############################          57337
160-191 #################                        32446
192-223 ######################################## 74928
224-255 ##                                       3848
low contrast: 90 to 153 std 18.4
min-max stretch: 0 to 255 std 74.6 levels 64
2-98 percentile stretch (91, 145): std 86.5 clipped 1.7 %

The camera image is bimodal: a dark mode (the photographer's coat, around level 27) and a bright one (the sky, 192–223). The dull copy squeezes everything into levels 90–153, a standard deviation of 18.4 instead of 73.6. A contrast stretch is a linear map v′=255(v−a)/(b−a)v' = 255 (v - a) / (b - a):

  • with a,ba, b = the minimum and maximum (cv2.normalize(..., NORM_MINMAX)), it restores the full range, but one hot pixel can spoil it;
  • with a,ba, b = the 2nd and 98th percentiles, it ignores outliers at the cost of clipping a few pixels (1.7 % here) and gives more contrast (std 86.5).

Neither creates information: the stretched image still has only the 64 distinct levels it started with, now spread 4 apart.

Histogram equalisation

Stretching is linear. Equalisation maps each level through the CDF itself, so that the output levels are used about equally often:

v′=round⁡ ⁣(255⋅CDF(v)−CDF(vmin⁡)1−CDF(vmin⁡))v' = \operatorname{round}\!\left(255 \cdot \frac{\text{CDF}(v) - \text{CDF}(v_{\min})}{1 - \text{CDF}(v_{\min})}\right)

where vmin⁡v_{\min} is the darkest level present, so it maps to 0. Crowded parts of the histogram (steep CDF) get spread out, empty parts compressed.

in 118out 69 0255255 input level -> CDF -> output level before: one narrow bump after: spread over 0..255
python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

img = data.camera()
low = (img // 4 + 90).astype(np.uint8)
hist = np.bincount(low.ravel(), minlength=256)
cdf = hist.cumsum()
cdf_min = cdf[hist > 0][0]                                           # pixels at the darkest level present
lut = np.round((cdf - cdf_min) / (low.size - cdf_min) * 255).clip(0, 255).astype(np.uint8)
eq = lut[low]                                                        # apply the look-up table
eq_cv = cv2.equalizeHist(low)
print("from scratch vs cv2.equalizeHist: max diff", int(np.abs(eq.astype(int) - eq_cv).max()), "| pixels that differ", int((eq != eq_cv).sum()))
print("levels used: before", len(np.unique(low)), "after", len(np.unique(eq)))
print("std before", round(float(low.std()), 1), "after", round(float(eq.std()), 1))
print("lut for 90..100:", lut[90:101].tolist())
c2 = np.bincount(eq.ravel(), minlength=256).cumsum() / eq.size
print("CDF after at 64/128/192:", [round(float(c2[v]), 3) for v in (64, 128, 192)])

def local_contrast(x, k=15):
    """Mean of the standard deviation in every k x k window."""
    x = x.astype(np.float32)
    m = cv2.blur(x, (k, k)); m2 = cv2.blur(x * x, (k, k))
    return float(np.sqrt(np.maximum(m2 - m * m, 0)).mean())

clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
for name, x in [("original", img), ("equalizeHist", cv2.equalizeHist(img)), ("CLAHE clip 2", clahe.apply(img)),
                ("CLAHE clip 4", cv2.createCLAHE(clipLimit=4.0, tileGridSize=(8, 8)).apply(img))]:
    print(f"{name:13s} global std {x.std():5.1f}  mean local std (15x15) {local_contrast(x):5.1f}  mean {x.mean():6.1f}")
from scratch vs cv2.equalizeHist: max diff 0 | pixels that differ 0
levels used: before 64 after 56
std before 18.4 after 73.9
lut for 90..100: [0, 9, 12, 15, 19, 27, 43, 58, 64, 67, 69]
CDF after at 64/128/192: [0.254, 0.494, 0.725]
original      global std  73.6  mean local std (15x15)  14.9  mean  129.1
equalizeHist  global std  73.7  mean local std (15x15)  19.2  mean  128.6
CLAHE clip 2  global std  67.6  mean local std (15x15)  22.9  mean  132.8
CLAHE clip 4  global std  66.3  mean local std (15x15)  29.2  mean  133.3

The ten-line version matches cv2.equalizeHist on every pixel. After equalisation the CDF is close to a straight line (0.254 at level 64, 0.494 at 128, 0.725 at 192, against the ideal 0.25, 0.50, 0.75), and the dull image has its contrast back (std 73.9). The look-up table shows how: level 96, where many pixels are, jumps from 43 to 58 to 64 in three steps, while sparse levels are squeezed together. Equalisation can merge levels (64 became 56) but never splits one, so it cannot invent detail, and it amplifies noise in flat regions just as much as detail.

CLAHE (contrast-limited adaptive histogram equalisation) equalises each tile of an 8×88 \times 8 grid separately, interpolating between tiles to avoid seams, and clips each tile's histogram at clipLimit times the average bin count before building its CDF, which caps how much it can amplify noise. It barely changes the global spread (std 67.6 against 73.6) but raises the local contrast measured in 15 x 15 windows from 14.9 to 22.9 (clip 2) or 29.2 (clip 4). That is why CLAHE is the usual choice for X-rays, retina photos and night scenes, and one of the photometric augmentations in image augmentation.

Global thresholding and Otsu's method

A threshold tt turns a grey image into a binary mask, img > t. The question is which tt. Otsu's method (1979) picks the tt that makes the two classes, C0={v≤t}C_0 = \{v \le t\} and C1={v>t}C_1 = \{v > t\}, as separated as possible. With class weights ω0(t)=CDF(t)\omega_0(t) = \text{CDF}(t), ω1=1−ω0\omega_1 = 1 - \omega_0 and class means μ0,μ1\mu_0, \mu_1, the between-class variance is

σB2(t)=ω0ω1(μ0−μ1)2=(μT ω0(t)−μ(t))2ω0(t) (1−ω0(t)),μ(t)=∑v=0tv p(v)\sigma_B^2(t) = \omega_0 \omega_1 (\mu_0 - \mu_1)^2 = \frac{\big(\mu_T\,\omega_0(t) - \mu(t)\big)^2}{\omega_0(t)\,\big(1 - \omega_0(t)\big)}, \qquad \mu(t) = \sum_{v=0}^{t} v\,p(v)

where μT\mu_T is the overall mean. Because the total variance is fixed, maximising σB2\sigma_B^2 is the same as minimising the variance within the two classes: it is 1-D k-means with k=2k = 2, solved exactly by trying all 256 thresholds with two cumulative sums.

python · try it yourself
import numpy as np
import cv2
from skimage import data
from skimage.filters import threshold_otsu
cv2.setLogLevel(0)

img = data.coins()                                                   # (303, 384): coins on a darker background
hist = np.bincount(img.ravel(), minlength=256).astype(np.float64)
p = hist / hist.sum()
levels = np.arange(256)
omega = np.cumsum(p)                                                 # weight of the class v <= t
mu = np.cumsum(p * levels)                                           # its (unnormalised) mean
mu_t = mu[-1]
with np.errstate(divide="ignore", invalid="ignore"):
    sigma_b = (mu_t * omega - mu) ** 2 / (omega * (1 - omega))
t = int(np.nanargmax(sigma_b))
print("from scratch: t =", t, "between-class variance", round(float(sigma_b[t]), 1))
t_cv, bw = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("cv2 THRESH_OTSU: t =", t_cv, "| skimage threshold_otsu:", threshold_otsu(img))
print("foreground (> t) share:", round(float((img > t).mean()), 3), "| class means", round(float(img[img <= t].mean()), 1), round(float(img[img > t].mean()), 1))
for tt in [60, 80, 100, t, 120, 140]:
    print(f"  t={tt:3d} sigma_b^2={sigma_b[tt]:7.1f}")
print("total variance", round(float(img.var()), 1))
from scratch: t = 107 between-class variance 2115.1
cv2 THRESH_OTSU: t = 107.0 | skimage threshold_otsu: 107
foreground (> t) share: 0.388 | class means 60.3 154.6
  t= 60 sigma_b^2= 1508.8
  t= 80 sigma_b^2= 1920.3
  t=100 sigma_b^2= 2103.8
  t=107 sigma_b^2= 2115.1
  t=120 sigma_b^2= 2073.4
  t=140 sigma_b^2= 1871.7
total variance 2796.3

All three implementations choose 107, with 38.8 % of the pixels above it. The curve is flat near the top (2103.8 at 100, 2073.4 at 120), so Otsu's tt is stable against small changes of the histogram. The ratio σB2/σT2=2115.1/2796.3≈0.76\sigma_B^2 / \sigma_T^2 = 2115.1 / 2796.3 \approx 0.76 (Otsu's separability measure) says how bimodal the image is; near 1 the threshold is clear, near 0 no global threshold makes sense. cv2.threshold returns the threshold and the mask; the mask is 255 where img > t, so the coins are white.

Otsu assumes two classes that differ in brightness everywhere in the image. In coins the light is uneven, and morphology and contours shows that the Otsu mask merges the top row of coins with the bright background. Variants exist for more than two classes (skimage.filters.threshold_multiotsu) and for tiny foregrounds (the triangle method, THRESH_TRIANGLE), where Otsu's balance-seeking criterion fails.

Adaptive thresholds for uneven light

When the illumination changes across the image, a single tt cannot work: dark ink on the bright side and bright paper on the dark side may have the same grey level. An adaptive threshold compares each pixel with its own neighbourhood:

ink(x,y)=[ I(x,y)<mk(x,y)−C ]\text{ink}(x, y) = \big[\, I(x, y) < m_{k}(x, y) - C \,\big]

where mkm_k is the mean (or Gaussian-weighted mean) over a k×kk \times k window and CC a small margin that keeps flat paper from becoming noise. The window must be larger than the strokes, and small enough that the light is roughly constant inside it. The test below renders three lines of text, darkens the page from 100 % light on the left to 30 % on the right, adds noise, and scores each method against the known ink mask:

python · try it yourself
import numpy as np
import cv2
from skimage.filters import threshold_local
cv2.setLogLevel(0)

rng = np.random.default_rng(0)
h, w = 120, 240
ink = np.zeros((h, w), np.uint8)
for i, line in enumerate(["Uneven light", "fools a global", "threshold"]):
    cv2.putText(ink, line, (6, 30 + 36 * i), cv2.FONT_HERSHEY_SIMPLEX, 0.9, 1, 2)
truth = ink > 0
light = np.linspace(1.0, 0.3, w)[None, :]                            # the light fades to the right
img = (np.where(truth, 60.0, 220.0) * light + rng.normal(0, 6, (h, w))).clip(0, 255).astype(np.uint8)
print("ink pixels:", int(truth.sum()), "of", truth.size)

t, g = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
res = {"global Otsu (t=%d)" % t: g > 0}
res["adaptive mean 31, C=15"] = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 31, 15) > 0
res["adaptive Gaussian 31, C=15"] = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 15) > 0
res["skimage threshold_local 31"] = img < threshold_local(img, 31, offset=15)
for name, pred in res.items():
    err = (pred != truth).mean()
    rec = (pred & truth).sum() / truth.sum()
    prec = (pred & truth).sum() / max(pred.sum(), 1)
    print(f"{name:27s} pixel error {err * 100:5.1f} %  ink recall {rec:.3f}  precision {prec:.3f}")

def ascii(mask, rows=12, cols=60):
    H, W = mask.shape
    for r in range(rows):
        print("".join("#" if mask[r * H // rows:(r + 1) * H // rows, c * W // cols:(c + 1) * W // cols].mean() > 0.3 else "." for c in range(cols)))
print("global:"); ascii(res["global Otsu (t=%d)" % t])
print("adaptive:"); ascii(res["adaptive Gaussian 31, C=15"])
ink pixels: 3475 of 28800
global Otsu (t=128)         pixel error  38.1 %  ink recall 1.000  precision 0.241
adaptive mean 31, C=15      pixel error   0.3 %  ink recall 1.000  precision 0.976
adaptive Gaussian 31, C=15  pixel error   0.4 %  ink recall 1.000  precision 0.970
skimage threshold_local 31  pixel error   0.3 %  ink recall 1.000  precision 0.976
global:
...................................#########################
..#..#..##..##.................#.###########################
..#..#.#.#.#######.###.#.#.....#############################
..................................##########################
..................................##########################
..#..###.###.#.###.....###.....#############################
..#..#.#.#.#.#.###.....#.#....##############################
................................############################
..#..#..............#.......#...############################
..#..#.#.#..###.###.#.#.#.###.#.############################
.............#............#....#############################
...................................#########################
adaptive:
............................................................
..#..#..##..##.................#.#.....#...#................
..#..#.#.#.#######.###.#.#.....#.###.#.#.#.#................
...................................###......................
............................................................
..#..###.###.#.###.....###.....###.#.###.###.###.#..........
..#..#.#.#.#.#.###.....#.#....####.###.#.#.#.#.#.#..........
................................#...........................
..#..#..............#.......#....#..........................
..#..#.#.#..###.###.#.#.#.###.#.##..........................
.............#............#....##...........................
............................................................

Otsu picks t=128t = 128, and everything right of the middle, where the paper has faded below 128, becomes "ink": 38.1 % of the pixels are wrong and only 24.1 % of the pixels it calls ink are ink. All three adaptive methods find every ink pixel with about 0.3 % error; OpenCV's mean version and scikit-image's threshold_local (Gaussian-weighted by default, with offset playing the role of CC) give the same numbers here. Notice that the text is the same in both ASCII previews on the left: the global threshold was not wrong where its assumption held.

On the real scanned page that ships with scikit-image the same thing happens:

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

page = data.page()                                                   # (191, 384), a scan lit from the right
print("mean brightness by fifth of the width:", [int(page[:, i * 384 // 5:(i + 1) * 384 // 5].mean()) for i in range(5)])
tp, gp = cv2.threshold(page, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
ap = cv2.adaptiveThreshold(page, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 25, 10)
for name, m in [(f"Otsu, t={tp:.0f}", gp), ("adaptive Gaussian 25, C=10", ap)]:
    share = [round(float((m[:, i * 384 // 5:(i + 1) * 384 // 5] > 0).mean()), 2) for i in range(5)]
    print(f"{name:27s} dark share overall {(m > 0).mean():.3f}, by fifth {share}")
mean brightness by fifth of the width: [108, 145, 173, 205, 223]
Otsu, t=157                 dark share overall 0.362, by fifth [0.95, 0.53, 0.17, 0.1, 0.06]
adaptive Gaussian 25, C=10  dark share overall 0.137, by fifth [0.17, 0.17, 0.16, 0.12, 0.07]

The page is about twice as bright on the right (mean 223) as on the left (108). Otsu's t=157t = 157 calls 95 % of the leftmost fifth "ink" and only 6 % of the rightmost, while the adaptive threshold finds 7–17 % dark pixels in every fifth, the kind of share text on a page has. With no ground truth for this scan, that consistency is the evidence; the synthetic page above is where the error rates come from.

Pitfalls

  • Thresholding before fixing the light. Uneven illumination breaks every global method; use an adaptive threshold, or estimate the background (a large blur or a morphological opening) and subtract it first.
  • Window size. An adaptive window smaller than the object (a thick stroke, a coin) hollows it out; one much larger than the light gradient behaves like a global threshold.
  • Polarity. THRESH_BINARY makes bright pixels 255, THRESH_BINARY_INV dark ones. Check which class is white before counting objects.
  • Equalising everything. Equalisation and CLAHE change the statistics a model sees; apply the same preprocessing at training and inference, or use them as augmentations rather than fixed steps.
  • Otsu on unimodal histograms. When the foreground is tiny (a few defects on a wafer), Otsu still returns a threshold, just a meaningless one. Look at σB2/σT2\sigma_B^2 / \sigma_T^2 or the histogram first.
  • Tuning on the test image. A threshold, window and CC chosen by looking at the images you evaluate on is a fitted parameter; choose them on separate images (leakage rules).

Practice

  1. An image has only three levels: 20 % of the pixels at 50, 30 % at 100, 50 % at 200. Compute σB2\sigma_B^2 for t=50t = 50 and t=100t = 100. Which does Otsu choose?
Answer

μT=0.2⋅50+0.3⋅100+0.5⋅200=140\mu_T = 0.2 \cdot 50 + 0.3 \cdot 100 + 0.5 \cdot 200 = 140. For t=50t = 50: ω0=0.2\omega_0 = 0.2, μ0=50\mu_0 = 50, μ1=(30+100)/0.8=162.5\mu_1 = (30 + 100)/0.8 = 162.5, σB2=0.2⋅0.8⋅112.52=2025\sigma_B^2 = 0.2 \cdot 0.8 \cdot 112.5^2 = 2025. For t=100t = 100: ω0=0.5\omega_0 = 0.5, μ0=(10+30)/0.5=80\mu_0 = (10 + 30)/0.5 = 80, μ1=200\mu_1 = 200, σB2=0.25⋅1202=3600\sigma_B^2 = 0.25 \cdot 120^2 = 3600. Otsu chooses t=100t = 100 (any tt from 100 to 199 gives the same split).

  1. Why does histogram equalisation of an image with only 64 grey levels still produce at most 64 levels?
Answer

Equalisation is a look-up table: every pixel with input level vv gets the same output LUT(v)\text{LUT}(v). So it can map different inputs to the same output (merge levels) but never one input to two outputs. In the lesson 64 levels became 56.

  1. A document is photographed under a lamp, bright in the centre and dark at the corners. Strokes are about 4 pixels wide. Suggest an adaptive window size and explain the trade-off.
Answer

Something like 21 to 41 pixels: several stroke widths, so a window centred on a stroke still contains mostly paper and its mean is the paper level; and small compared with the distance over which the lamp's light changes noticeably. Much smaller windows turn the inside of thick letters into "paper"; much larger ones see the light gradient and fail like a global threshold.

Test yourself

What does Otsu's method maximise?

  1. The number of foreground pixels
  2. The between-class variance ω0ω1(μ0−μ1)2\omega_0 \omega_1 (\mu_0 - \mu_1)^2
  3. The entropy of the image
  4. The contrast after equalisation

In the lesson's synthetic page, global Otsu had 38.1 % pixel error and the adaptive thresholds about 0.3 %. What caused the difference?

  1. Otsu picked a threshold that was too low
  2. The illumination faded across the page, so no single threshold separates ink from paper everywhere
  3. The noise was too strong for Otsu
  4. Adaptive thresholds use colour

What does the clip limit in CLAHE do?

  1. It clips output values to 0..255
  2. It caps each tile's histogram bins before the CDF is built, which limits how much noise in flat regions is amplified
  3. It sets the number of tiles
  4. It removes the brightest 2 % of pixels

Two images contain the same pixels in a different arrangement. What is true of their histograms?

  1. They differ
  2. They are identical
  3. They differ unless the images are greyscale
  4. Only their CDFs are identical