Sub topic 13
Adaptive thresholding for uneven lighting
Prerequisites
This chapter assumes you can read a grayscale image with cv2.imread, that you know NumPy dtypes (uint8), and that you have seen cv2.threshold with a fixed value and with Otsu's method. It also assumes you know what a Gaussian blur does. If a global threshold is new to you, review that chapter first.
Why one threshold fails
A global threshold compares every pixel to the same number T. That works when the foreground and background intensities are separated everywhere in the image by the same gap. Real scenes often break this rule. A page photographed under a desk lamp is bright near the lamp and dim at the far corner. The ink in the bright area may be brighter than the paper in the dim area. No single T can separate ink from paper in both places.
Otsu's method does not fix this. It picks the best single T for the whole histogram, so it still applies one number everywhere.
Adaptive thresholding replaces the single T with a different threshold for every pixel. The threshold is computed from the pixel's neighborhood, so it follows the local lighting.
The working model
For each pixel at position (x, y), OpenCV does this:
- Take a square window of
blockSizebyblockSizepixels centered on the pixel. - Compute a local reference value,
m(x, y), from that window. This is either the plain mean or a Gaussian-weighted mean. - Subtract the constant
C: the local threshold isT(x, y) = m(x, y) - C. - Compare the pixel to
T(x, y)and write 0 ormaxValueto the output.
With THRESH_BINARY, a pixel becomes maxValue if it is greater than T(x, y), and 0 otherwise. With THRESH_BINARY_INV the two outcomes are swapped.
Step 2 is a smoothing filter, the same kind you met in the smoothing chapters. Adaptive thresholding is "blur the image, then compare the original to the blurred copy, with an offset".
The function and its parameters
import cv2
gray = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("input.jpg could not be read")
adaptive = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 10
)The signature is cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C).
| Parameter | Meaning | Constraints |
|---|---|---|
| `src` | Input image | Must be single-channel `uint8` |
| `maxValue` | Value written for pixels that pass | Usually 255 |
| `adaptiveMethod` | How `m` is computed | `ADAPTIVE_THRESH_MEAN_C` or `ADAPTIVE_THRESH_GAUSSIAN_C` |
| `thresholdType` | Output polarity | Only `THRESH_BINARY` or `THRESH_BINARY_INV` |
| `blockSize` | Window side length in pixels | Odd, and greater than 1 |
| `C` | Constant subtracted from `m` | Can be positive, zero or negative |
Two differences from cv2.threshold matter in practice:
- The function returns only the output image.
cv2.thresholdreturns a pair,(value, image), because there is one value to report. Adaptive thresholding has a different threshold at each pixel, so it has nothing to return. THRESH_OTSU,THRESH_TRIANGLE,THRESH_TRUNCand the other types are not allowed. Passing one raises an error.
Mean versus Gaussian
ADAPTIVE_THRESH_MEAN_C gives every pixel in the window the same weight. It is a box filter. ADAPTIVE_THRESH_GAUSSIAN_C weights pixels near the center more than pixels near the edge of the window, as a Gaussian blur does.
The Gaussian version is usually the better default. A box average changes abruptly as the window slides past a bright or dark pixel, which can produce blocky artifacts. The Gaussian version changes smoothly. The mean version is slightly faster, and it is a reasonable choice when speed matters and the image is clean.
Choosing blockSize
blockSize controls how local "local" is. The rule of thumb is that the window must be larger than the foreground features you want to keep, and small enough that the lighting inside it is roughly constant.
- If the window is too small, it fits inside a thick stroke or a large dark region. The local mean there equals the pixel's own value, so the interior of the feature falls below
Tand turns into background. Thick letters become hollow outlines. - If the window is too large, the local mean approaches the global mean and the method behaves like a global threshold again. Shadow gradients return.
For document text, a window roughly two to three times the stroke height is a good starting point. For a 1000 pixel wide photo of a page, values between 21 and 51 are typical. Because the window must be odd, try 11, 21, 31, 41 and compare the results side by side.
Choosing C
C shifts the threshold relative to the local mean. In THRESH_BINARY mode with a positive C, the threshold is lower than the local mean, so a pixel must be at least C levels brighter than its surroundings to count as foreground. That suppresses noise in flat regions.
Consider a flat, uniformly gray patch of paper with slight sensor noise. Without C, about half the pixels would be brighter than the local mean and about half darker. The output would be salt-and-pepper speckle. A positive C in THRESH_BINARY mode pushes the threshold below nearly all the noise, so those pixels come out as white background. For dark text on light paper, this is the setup you want: paper is white, ink is black.
If your foreground is bright on a darker background, use THRESH_BINARY_INV or a negative C, depending on which polarity you need.
A full comparison
The next script runs a fixed threshold, Otsu and the adaptive method on an image with a lighting gradient. It builds its own test image so it runs without any input file.
import cv2
import numpy as np
# Synthetic page: dark text on paper, with a strong left-to-right lighting ramp.
h, w = 240, 480
page = np.full((h, w), 200, np.uint8)
for i, word in enumerate(["Adaptive", "threshold", "uneven", "light"]):
cv2.putText(page, word, (15, 45 + i * 55),
cv2.FONT_HERSHEY_SIMPLEX, 1.4, 70, 3, cv2.LINE_AA)
ramp = np.linspace(1.0, 0.35, w, dtype=np.float32)[None, :]
lit = np.clip(page.astype(np.float32) * ramp, 0, 255).astype(np.uint8)
blur = cv2.GaussianBlur(lit, (5, 5), 0)
_, fixed = cv2.threshold(blur, 127, 255, cv2.THRESH_BINARY)
otsu_value, otsu = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
adaptive = cv2.adaptiveThreshold(
blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 10
)
print("Otsu threshold:", otsu_value)
for name, img in [("fixed", fixed), ("otsu", otsu), ("adaptive", adaptive)]:
white_right = np.mean(img[:, w * 3 // 4:] == 255)
print(f"{name:8s} white fraction in darkest quarter: {white_right:.2f}")
cv2.imwrite("compare.png", np.hstack([lit, fixed, otsu, adaptive]))On the dim right side, the paper has intensity near 70 to 90, below the fixed threshold of 127. The fixed result turns that whole region black, and the text disappears into it. The printed white fraction for the darkest quarter shows this: it is near 0 for the fixed and Otsu results, and well above that for the adaptive result, because the adaptive method treats the dim paper as background. Open compare.png to see the four panels side by side.
Edge cases and failure modes
- Large uniform regions turn noisy. In a flat area with no features, pixel values hover around the local mean. If
Cis too small, you get speckle. RaiseC, or blur first. - Large dark blobs get hollow. As described above, a window smaller than the blob puts the blob's interior below its own local mean offset. Increase
blockSize. - Borders. Windows near the image edge extend past the image. OpenCV fills the missing pixels using border replication, so edge pixels use a slightly biased local mean. The effect is usually small.
- Wrong dtype or channel count. Passing a color image or a
float32array raises an error. Convert withcv2.cvtColorand keepuint8. - Even
blockSize. An even value raises an error. Always use an odd number. - Colored shadows and glare. Adaptive thresholding handles smooth brightness changes. A sharp shadow edge or a specular highlight is a real intensity step, and the method will draw it as an edge-like artifact.
When to choose which method
| Situation | Method |
|---|---|
| Even lighting, known contrast | Fixed threshold |
| Even lighting, unknown contrast, bimodal histogram | Otsu |
| Smooth lighting gradient or shadow across the image | Adaptive threshold |
| Uneven lighting and heavy noise | Blur or median filter, then adaptive threshold |
| Output still has small specks or holes | Add morphological opening and closing |
Adaptive thresholding often leaves small isolated white or black pixels. The morphology chapter shows how to remove them with opening and closing.
Exercise
You run cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 2) on a scan of a page with large bold headline letters, each stroke about 40 pixels thick. The headlines come out as hollow outlines. What is the cause, and what two changes could you try?
Show answer
The 5 by 5 window is much smaller than the stroke width. Inside a thick stroke, the local mean equals the pixel's own value, so after subtracting C the interior pixels are not clearly brighter than the threshold and are classed inconsistently, which leaves only the edges. Increase blockSize to a value larger than the stroke thickness, such as 81 or more, and adjust C if the background becomes noisy. Using THRESH_BINARY_INV is also needed if you want the dark letters to come out white.
Exercise
Why does cv2.adaptiveThreshold return only an image, while cv2.threshold returns a value and an image?
Show answer
cv2.threshold uses one threshold for the whole image, so it can report which value it used, which is especially useful with Otsu. cv2.adaptiveThreshold computes a different threshold at every pixel, so there is no single value to return.
Exercise
A photo of a whiteboard has a bright glare on the upper left and a shadow on the lower right. Otsu leaves the shadow area completely black. Describe a pipeline that should fix this, with parameter choices and one check to verify the result.
Show answer
Convert to grayscale, apply cv2.GaussianBlur(gray, (5, 5), 0) or cv2.medianBlur(gray, 5) to reduce noise, then call cv2.adaptiveThreshold with ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY (or THRESH_BINARY_INV for dark marker on a light board with white output), an odd blockSize such as 41 or more that exceeds the marker stroke width, and a C of about 8 to 12. Verify by checking that the white fraction of the output is similar in the glare region and the shadow region, or by viewing both regions side by side. Clean any remaining specks with morphological opening.