Sub topic 1
Preparing a Binary Image: Grayscale, Blur and Thresholding
Prerequisites
Assume you know basic Python and NumPy array indexing. You should also know how to load and save images with OpenCV, and how color channels differ from grayscale pixels. The examples use OpenCV 4 and Python.
A contour is a curve that follows a boundary in an image. Before OpenCV can find contours reliably, prepare a binary image. A binary image has only two useful pixel values:
0, usually representing black or background255, usually representing white or foreground
The foreground is the object whose boundary you want to measure.
Convert to grayscale
A color image contains three channels: blue, green, and red. Thresholding normally works on one channel, so convert the image to grayscale first. A grayscale image stores one brightness value per pixel.
import cv2
image = cv2.imread("shapes.png")
if image is None:
raise FileNotFoundError("Could not read shapes.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray.png", gray)OpenCV reads color images in BGR order, not RGB order. Using cv2.cvtColor avoids manually combining channels and applies a standard brightness weighting.
Blur before thresholding
Small changes in brightness and sensor noise can create unwanted regions. A Gaussian blur reduces these changes by averaging nearby pixels. The kernel (5, 5) determines the neighborhood size. Larger kernels remove more detail but can also soften object boundaries.
blurred = cv2.GaussianBlur(gray, (5, 5), 0)Use a moderate kernel when object boundaries matter. If the blur is too strong, nearby objects can merge or narrow features can disappear.
Threshold the image
Thresholding compares each pixel with a cutoff value. Pixels above the cutoff become white, and the rest become black.
_, binary = cv2.threshold(
blurred,
127,
255,
cv2.THRESH_BINARY
)
cv2.imwrite("binary.png", binary)This uses a fixed threshold of 127. It works when lighting is consistent. For dark shapes on a light background, invert the result so the shapes become white:
_, binary = cv2.threshold(
blurred,
0,
255,
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)Otsu's method chooses the cutoff from the image histogram, so the threshold argument is 0. The THRESH_BINARY_INV flag reverses the polarity. This polarity matters because later processing often treats white regions as foreground.
| Method | Best use |
|---|---|
| Fixed threshold | Even lighting and predictable pixel values |
| Otsu threshold | A clear separation between two brightness groups |
| Adaptive threshold | Uneven lighting across the image |
Adaptive thresholding can help when one global cutoff fails:
binary = cv2.adaptiveThreshold(
blurred,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,
11,
2
)The block size must be odd and greater than one. The final value adjusts the local cutoff.
Exercise
Exercise
An image has dark objects on a bright background, but the threshold output shows bright background and dark objects. What change should you make?
Show answer
Use an inverted threshold, such as cv2.THRESHBINARYINV, so the objects become white foreground regions.