Sub topic 3
Choosing the threshold automatically with Otsu
This chapter assumes you know Python, NumPy array indexing, and how to read and write images with cv2. You should also know that a blur reduces noise before edge or threshold steps.
Choosing the threshold automatically with Otsu
A global threshold splits pixels into foreground and background at one fixed intensity. Otsu's method picks that value from the image histogram by maximizing the separation between the two groups. Pass 0 as the threshold and add cv2.THRESH_OTSU.
import cv2
gray = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
t, mask = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("Otsu threshold:", t)Adaptive thresholding for uneven lighting
Otsu uses one value for the whole image, so a shadow can break it. Adaptive thresholding computes a separate threshold for each pixel from its neighborhood. The block size must be odd.
adaptive = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 10
)Cleaning masks with erosion, dilation, opening and closing
Opening removes small white specks. Closing fills small black holes. Both use a structuring element, a small shape that the operation slides across the mask.
Putting it together: a filter, edge and threshold pipeline
The function below blurs once, builds a cleaned mask, and computes edges from the same blurred image.
import cv2
def segment(path):
gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError(path)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, mask = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, se)
edges = cv2.Canny(blur, 50, 150)
return mask, edges
if __name__ == "__main__":
mask, edges = segment("input.jpg")
cv2.imwrite("mask.png", mask)
cv2.imwrite("edges.png", edges)Tuning parameters and avoiding common mistakes
- Blur size controls noise. Larger kernels remove more noise but also erase thin edges.
- Canny's low threshold links weak edges, and its high threshold starts them. Keep the high value about two to three times the low value.
- Adaptive block size should be larger than the objects you want to keep.
- Mistake: passing a nonzero threshold together with
THRESH_OTSU. The supplied value is ignored. - Mistake: running Canny on an unblurred image, which produces edges from noise.
Exercise
Why does Otsu's method fail when one side of the image is in shadow, and which function would you use instead?
Show answer
A single global threshold cannot separate the shadowed foreground from the background, so use cv2.adaptiveThreshold, which computes a threshold per neighborhood.