Sub topic 1
Preparing a Binary Image: Grayscale, Blur and Thresholding
Prerequisites
This chapter assumes you can do the following:
- Write basic Python and index NumPy arrays.
- Load, display and save images with
cv2.imread,cv2.imshowandcv2.imwrite. - Explain pixel values, color channels and grayscale images. An 8-bit grayscale pixel is an integer from 0 (black) to 255 (white).
The examples use the Python API of OpenCV 4 and a file named shapes.png. Any image with dark shapes on a light background works.
Why contours need a binary image
A contour is a curve that follows the boundary of a connected region of pixels that share a value. cv2.findContours works on a single-channel image and treats every nonzero pixel as foreground and every zero pixel as background. The function does not know about color, shading or texture. You have to reduce the picture to a mask first.
A binary image holds only two values, normally 0 and 255. Getting this mask right matters more than any later step. A bad mask gives broken, merged or spurious contours, and no amount of filtering afterward fully repairs it.
The preparation has three steps.
- Convert the color image to grayscale.
- Blur it slightly to suppress noise.
- Threshold it to produce the binary mask.
Step 1: Grayscale conversion
cv2.imread returns color images in BGR order (blue, green, red), not RGB. Pass the matching conversion code, or the weights are applied to the wrong channels.
import cv2
img = cv2.imread("shapes.png")
if img is None:
raise FileNotFoundError("shapes.png could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(img.shape, gray.shape, gray.dtype)For a 400 by 600 image, this prints (400, 600, 3) (400, 600) uint8. The color array has three channels and the gray array has none.
The conversion computes a weighted sum of the channels: about 0.299 R + 0.587 G + 0.114 B. Green gets the most weight because human vision is most sensitive to it.
You can also load the file directly as grayscale:
gray = cv2.imread("shapes.png", cv2.IMREAD_GRAYSCALE)Keep the color image as well if you want to draw colored outlines later. Drawing a green contour on a single-channel image shows up as gray.
Grayscale has one weakness. Two regions with different hues but similar brightness, such as a red shape on a green background, can end up with almost the same gray value. In that case, threshold a single channel (img[:, :, 2] for red) or work in HSV with cv2.inRange. This tutorial uses grayscale throughout.
Step 2: Blur before you threshold
Real images contain sensor noise and compression artifacts. A threshold decides each pixel independently, so isolated noisy pixels land on the wrong side of the cutoff. The result is a speckled mask with ragged edges, which produces many tiny contours and jagged outlines.
A Gaussian blur averages each pixel with its neighbors, weighted by distance. It removes noise at the cost of slightly softening edges.
blur = cv2.GaussianBlur(gray, (5, 5), 0)The second argument is the kernel size. It must be positive and odd, so (5, 5) works and (4, 4) does not. The third argument is the standard deviation in X. A value of 0 tells OpenCV to derive it from the kernel size.
| Kernel size | Effect | Typical use |
|---|---|---|
| (3, 3) | Light smoothing | Clean images, small details |
| (5, 5) | Moderate smoothing | General starting point |
| (9, 9) or larger | Strong smoothing | Noisy photos, large shapes |
Larger kernels round off sharp corners and can merge shapes that sit close together. Use the smallest kernel that gives a clean mask. If the image has salt-and-pepper noise (isolated black and white pixels), cv2.medianBlur(gray, 5) removes it better than a Gaussian blur.
Step 3: Thresholding
Thresholding compares each pixel to a cutoff value and assigns one of two outputs. cv2.threshold has this signature:
retval, dst = cv2.threshold(src, thresh, maxval, type)It returns two values. retval is the threshold actually used, which matters when OpenCV computes it for you. dst is the output image.
Fixed threshold and polarity
With cv2.THRESH_BINARY, pixels above thresh become maxval and all others become 0. With cv2.THRESH_BINARY_INV, the result is reversed.
_, white_bright = cv2.threshold(blur, 127, 255, cv2.THRESH_BINARY)
_, white_dark = cv2.threshold(blur, 127, 255, cv2.THRESH_BINARY_INV)This choice is called polarity, and it is the most common source of bad contour results. findContours traces white regions on a black background. If your shapes are dark on a light page, you want THRESH_BINARY_INV so the shapes become white. If you use the wrong one, the shapes become the background. You then get one huge contour around the whole image border, or contours of the gaps between shapes.
Otsu's method
A fixed value like 127 only works when lighting is consistent. Otsu's method picks the threshold automatically. It assumes the histogram has two peaks, one for the background and one for the foreground, and chooses the value that best separates them.
Add cv2.THRESH_OTSU to the type flag. The thresh argument is then ignored, so pass 0.
t, binary = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
print("Otsu threshold:", t)Otsu works on single-channel 8-bit images only. It tends to work better after blurring, because noise spreads the histogram peaks and makes them harder to separate.
This is the combination used in the full example below. It is a good default for dark shapes on a light, evenly lit background.
Adaptive thresholding
When lighting varies across the image, for example a page photographed with a shadow on one side, no single global cutoff works. Adaptive thresholding computes a separate cutoff for each pixel from its local neighborhood.
adaptive = cv2.adaptiveThreshold(
gray, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,
11, 2,
)The arguments after the image and maxval are:
- The method:
ADAPTIVE_THRESH_MEAN_CorADAPTIVE_THRESH_GAUSSIAN_C. - The type: only
THRESH_BINARYorTHRESH_BINARY_INVare allowed. blockSize: the neighborhood size, which must be odd and greater than 1.C: a constant subtracted from the local mean. Larger values suppress more noise.
Adaptive thresholding responds to local edges and texture. On a flat region, such as the inside of a large filled shape, it can produce a hollow outline or noise, because each pixel resembles its neighbors. Choose blockSize larger than the thickness of the features you want to keep.
| Method | Cutoff | Best for | Weakness |
|---|---|---|---|
| Fixed (`THRESH_BINARY`) | One chosen value | Controlled lighting | Fails when lighting changes |
| Otsu | One computed value | Two-peak histograms | Fails with uneven light or three or more tones |
| Adaptive | One per pixel | Uneven illumination | Hollow fills, noise in flat areas |
A complete example
This script runs the whole pipeline, finds the outer contours, and draws them. It is the first code example for the chapters that follow.
import cv2
img = cv2.imread("shapes.png")
if img is None:
raise FileNotFoundError("shapes.png could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
print("contours found:", len(contours))
out = img.copy()
cv2.drawContours(out, contours, -1, (0, 255, 0), 2)
cv2.imwrite("contours.png", out)
cv2.imwrite("binary.png", binary)The line contours, hierarchy = cv2.findContours(...) assumes OpenCV 4. OpenCV 3 returned three values (image, contours, hierarchy). If you get an unpacking error, check cv2.__version__. Later chapters cover findContours itself in detail.
Check the mask before going further
Always look at the binary image. Save it or display it, and confirm three things.
- The shapes you care about are white and the background is black.
- Shapes are solid, without large holes or broken edges.
- There is no large amount of isolated white specks.
A quick numeric check also helps:
white_fraction = (binary == 255).mean()
print(f"white pixels: {white_fraction:.1%}")If the white fraction is above about 50 percent for an image of small shapes, the polarity is probably inverted. Specks and small holes in the mask are cleaned with morphological operations, which the chapter after next covers.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| One contour around the whole image | Inverted polarity | Switch between `THRESH_BINARY` and `THRESH_BINARY_INV` |
| Hundreds of tiny contours | Noise, or too little blur | Increase blur, or filter by area later |
| Shape outlines are broken or hollow | Threshold too strict, or adaptive threshold on flat areas | Use Otsu, or lower `C`, or enlarge `blockSize` |
| Two nearby shapes become one contour | Blur too strong, or threshold too loose | Use a smaller kernel, or raise the cutoff |
| Otsu gives a poor result | Uneven lighting or more than two tones | Use adaptive thresholding |
| `cv2.cvtColor` raises an error | Image is already grayscale, or `imread` returned `None` | Check `img is None` and `img.ndim` |
Exercises
Exercise
You threshold a photo of black bolts on a white table with cv2.THRESH_BINARY and Otsu. findContours returns one contour that follows the border of the whole image. What went wrong, and how do you fix it?
Show answer
The polarity is inverted. THRESH_BINARY makes the bright table white and the dark bolts black, so findContours traces the table region instead of the bolts. Use cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU so the bolts become white on a black background.
Exercise
A page photo has a shadow across the left third. A global Otsu threshold turns the shadowed area entirely black. Which thresholding method should you try, and which parameter controls the size of the neighborhood it uses?
Show answer
Use cv2.adaptiveThreshold, which computes a cutoff per pixel from its local neighborhood. The blockSize parameter sets the neighborhood size and must be odd and greater than 1.
Exercise
Why does the call cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) pass 0 as the threshold, and how can you find the value Otsu actually chose?
Show answer
With THRESH_OTSU, OpenCV ignores the thresh argument and computes the cutoff itself, so 0 is only a placeholder. The first return value of cv2.threshold is the computed threshold, for example t, binary = cv2.threshold(...).