Sub topic 12
Choosing the threshold automatically with Otsu
This chapter assumes you can read an image with cv2.imread, know that a grayscale image is a 2-D uint8 array, and have seen cv2.threshold with a fixed value. You also need the smoothing filters from earlier chapters, because Otsu's method works best on a pre-blurred image.
The problem with a fixed threshold
A fixed threshold such as 127 is a guess. It works only when the foreground and background happen to fall on opposite sides of that value. If the photo is darker or brighter than you expected, the guess cuts through the wrong place and the mask is mostly black or mostly white.
Otsu's method removes the guess. It reads the image's histogram and picks the threshold itself. The histogram is a count of how many pixels have each gray level from 0 to 255.
The idea behind Otsu
Otsu's method assumes the histogram has two groups of pixels, a darker group and a brighter group. These are often called classes. For every candidate threshold t from 0 to 255, the method splits the pixels into two classes: pixels at or below t, and pixels above t. It then scores the split. It keeps the t with the best score.
The score is the between-class variance. Variance measures spread. The between-class variance measures how far apart the two class means are, weighted by the class sizes:
sigma_b^2(t) = w0(t) * w1(t) * (mean0(t) - mean1(t))^2Here w0 and w1 are the fractions of pixels in each class, and mean0 and mean1 are their average gray levels. A large value means the classes are far apart and each is a tight cluster. Maximizing this is equivalent to minimizing the spread inside each class, so the chosen threshold gives the cleanest two-way split.
The method checks all 256 levels, so it is fast and has no tunable parameter.
Using Otsu in OpenCV
You request Otsu by adding cv2.THRESH_OTSU to a threshold type. OpenCV then ignores the threshold value you pass, so convention is to pass 0. The function returns two things: the threshold it chose, and the thresholded image.
import cv2
import numpy as np
img = cv2.imread("input.jpg")
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, fixed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
otsu_value, otsu = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
print("Otsu threshold:", otsu_value)Points to notice:
- The first return value, which earlier code discarded with
_, is now useful. It is afloat, for example118.0. THRESH_BINARY + THRESH_OTSUcombines two flags. You can also writecv2.THRESH_BINARY | cv2.THRESH_OTSU. Both give the same result.- You can combine Otsu with other types, such as
THRESH_BINARY_INVto flip foreground and background, orTHRESH_TOZERO.
Why blur first
Image noise spreads each class across more gray levels. The two peaks of the histogram get wider and the valley between them fills in, so the variance score becomes less decisive. A light Gaussian blur narrows the peaks and makes the choice more stable.
You can compare the two directly.
otsu_raw_value, otsu_raw = cv2.threshold(
gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
otsu_blur_value, otsu_blur = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
print(otsu_raw_value, otsu_blur_value)
# Count pixels that differ between the two masks.
diff = np.count_nonzero(otsu_raw != otsu_blur)
print("Differing pixels:", diff)On a clean image the two values are close. On a noisy image the blurred version usually has fewer isolated white or black pixels.
Reading the histogram yourself
Otsu is only as good as the histogram it sees. Plotting or printing it tells you whether the method is appropriate.
hist = cv2.calcHist([blur], [0], None, [256], [0, 256]).ravel()
peak_low = int(np.argmax(hist[:128]))
peak_high = 128 + int(np.argmax(hist[128:]))
print("Peaks near gray levels:", peak_low, peak_high)
print("Otsu chose:", otsu_value)For a bimodal histogram (two peaks), the Otsu value should fall in the valley between them. If the printed value sits on top of a peak, the image does not match the method's assumption.
In this example the valley is around 100 to 150, so Otsu would choose a value in that range.
Edge cases and failure modes
Otsu fails in predictable ways. Check for these before you trust it.
| Situation | What happens | What to do |
|---|---|---|
| Uneven lighting, such as a shadow across a page | One global value cannot fit both bright and dark regions, so part of the foreground is lost | Use adaptive thresholding (next chapter) |
| Very small foreground, such as a few dark pixels on a large white area | The histogram is dominated by one class, and the threshold drifts toward it | Crop to a region of interest, or set the threshold by hand |
| Histogram with three or more groups | Otsu forces a two-class split, so it may merge two real groups | Use multi-level thresholding or clustering such as k-means |
| Heavy noise | Peaks overlap and the value becomes unstable | Blur first; use median filtering for salt-and-pepper noise |
| Constant or near-constant image | All pixels fall in one class, and the result is arbitrary | Check the image range before thresholding |
| Input is not 8-bit | `cv2.threshold` with Otsu supports only 8-bit single-channel images, so other types raise an error | Convert with `cv2.normalize` and `astype(np.uint8)` |
The last row matters in practice. A float32 gradient magnitude cannot go straight into Otsu. Rescale it first.
gx = cv2.Sobel(blur, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(blur, cv2.CV_32F, 0, 1, ksize=3)
mag = cv2.magnitude(gx, gy)
mag8 = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
t, strong_edges = cv2.threshold(
mag8, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
print("Edge strength threshold:", t)This gives a data-driven cutoff for edge strength, which can be a starting point when you tune Canny thresholds.
Masks and a region of interest
If a large irrelevant area, such as a black border, distorts the histogram, you can compute the threshold on part of the image and apply it to the whole image. Run Otsu on the crop to get the value, then use that value as a fixed threshold.
h, w = blur.shape
roi = blur[h // 4 : 3 * h // 4, w // 4 : 3 * w // 4]
t_roi, _ = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
_, full_mask = cv2.threshold(blur, t_roi, 255, cv2.THRESH_BINARY)
print("Threshold from ROI:", t_roi)The second call uses a plain THRESH_BINARY with the computed value. That is the correct pattern, because adding THRESH_OTSU again would discard t_roi and recompute it on the full image.
Cleaning the result
Otsu masks usually contain small specks and holes. The morphology chapter covers the details, but here is the standard follow-up.
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(otsu, cv2.MORPH_OPEN, se)
cleaned = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, se)Opening removes small white specks, and closing fills small black holes.
Choosing between methods
- Use a fixed threshold when lighting is controlled and identical across images, such as an inspection station.
- Use Otsu when lighting varies between images but is even within each image, and the histogram has two clear groups.
- Use adaptive thresholding when lighting varies within a single image.
Exercises
Exercise
You call cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU). What threshold is used, and what does the first return value contain?
Show answer
The 200 is ignored. Otsu computes its own threshold from the histogram, and the first return value is that computed value as a float.
Exercise
Otsu on a photo of a page with a shadow over one corner removes the text in the shadow. Why does this happen, and what should you use instead?
Show answer
Otsu picks one global value, but shadowed text is darker than the page elsewhere, so a single cutoff cannot separate text from paper in both regions. Use adaptive thresholding, which computes a separate threshold for each neighborhood.
Exercise
You computed t_roi with Otsu on a crop and want to apply it to the full image. Which call is correct, and why?
Show answer
cv2.threshold(blur, t_roi, 255, cv2.THRESH_BINARY). Adding THRESH_OTSU would make OpenCV ignore t_roi and recompute a threshold from the full image.