Sub topic 12
Choosing the Threshold Automatically with Otsu
This chapter assumes basic Python, NumPy arrays, grayscale images, and an OpenCV installation that can read images. You should also know that a grayscale image stores each pixel as an intensity from 0 to 255.
Why choose a threshold automatically?
Thresholding converts a grayscale image into a binary image, usually containing only black pixels (0) and white pixels (255). A threshold separates pixels into two groups:
- Pixels at or below the threshold become black.
- Pixels above the threshold become white.
A fixed threshold works when lighting and object intensity stay consistent. For example, you might choose 127 for an image with a dark background and a bright foreground. However, a threshold chosen by hand may fail when images come from different cameras or lighting conditions.
Otsu's method chooses the threshold from the image's histogram. A histogram counts how often each intensity appears. Otsu works best when the histogram has two clear groups, such as dark background pixels and bright object pixels.
How Otsu's method works
Otsu tests possible thresholds between intensity values. For each candidate, it divides the pixels into two classes:
- The background class.
- The foreground class.
It then measures how separate those classes are. The selected threshold maximizes the separation between the classes, which is equivalent to minimizing their weighted within-class variance.
The method does not understand the object or the scene. It only analyzes pixel intensities. This makes it simple and useful, but it also creates limits.
Applying Otsu in OpenCV
OpenCV combines Otsu's method with cv2.threshold. Pass 0 as the threshold value. OpenCV ignores that value and calculates a threshold from the image.
import cv2
image = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
if image is None:
raise FileNotFoundError("input.jpg could not be read")
threshold_value, mask = cv2.threshold(
image,
0,
255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU,
)
print("Chosen threshold:", threshold_value)
print("Mask values:", set(mask.ravel()))The first returned value is the threshold selected by Otsu. The second value is the binary mask. The mask should normally contain only 0 and 255.
Blur before Otsu
Small amounts of sensor noise can create extra intensity values and make the histogram less distinct. A Gaussian blur often improves the result:
blurred = cv2.GaussianBlur(image, (5, 5), 0)
threshold_value, mask = cv2.threshold(
blurred,
0,
255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU,
)Blur removes small variations, but it also removes detail. A large kernel can merge nearby objects or weaken thin structures.
Choosing the output polarity
THRESH_BINARY makes pixels above the threshold white. If the foreground is dark and the background is bright, use THRESH_BINARY_INV instead:
_, dark_foreground = cv2.threshold(
image,
0,
255,
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU,
)Inspect the mask before deciding which polarity is correct. You can also use morphology afterward to remove isolated specks or fill small holes.
| Image condition | Suitable approach |
|---|---|
| Two clear intensity groups | Otsu thresholding |
| Uneven lighting | Adaptive thresholding |
| Known, stable intensity range | Fixed threshold |
Exercise
Why is the threshold argument set to 0 when using cv2.THRESH_OTSU?
Show answer
OpenCV ignores the supplied threshold value and calculates the best global threshold from the image histogram.