Sub topic 16
Tuning Parameters and Avoiding Common Mistakes
Prerequisites and the tuning loop
This chapter assumes Basic Python, NumPy array indexing and dtypes, and familiarity with grayscale images and OpenCV. You should also know how to read an image with cv2.imread.
Image processing parameters are not universal constants. They depend on image size, noise, lighting, contrast, and the object you want to measure. Tune a pipeline against representative images, then test it on images that were not used during tuning.
A useful loop is:
- Define the desired output, such as one clean object mask.
- Choose a small set of parameters to change.
- Save intermediate results, not only the final result.
- Check the result on bright, dark, noisy, and difficult examples.
- Measure errors when possible.
Parameters that interact
A large Gaussian kernel removes more noise but also removes small edges. A higher Canny threshold rejects more weak edges. A larger morphology kernel removes more small features, including real ones.
| Operation | Parameter | Common effect of increasing it |
|---|---|---|
| Gaussian blur | Kernel size or sigma | More smoothing and less fine detail |
| Canny | Low and high thresholds | Fewer accepted weak edges |
| Adaptive threshold | Block size | Uses a larger local lighting neighborhood |
| Morphology | Structuring-element size | Removes or fills larger features |
For Canny, the low threshold should usually be below the high threshold. Pixels above the high threshold become strong edges. Pixels between the thresholds survive only when connected to strong edges. This is hysteresis. A ratio such as 1:2 or 1:3 is a starting point, not a rule.
For adaptive thresholding, use an odd block size greater than one. A block that is too small follows noise. A block that is too large behaves more like a global threshold.
Common mistakes
- Applying grayscale functions to a three-channel BGR image without checking the input.
- Using
cv2.Sobel(..., cv2.CV_8U, ...). Negative gradients are clipped, so useCV_32ForCV_64F. - Treating a normalized display image as the original measurement. Normalization changes values for viewing.
- Choosing a threshold from one image and assuming another camera or lighting setup will match.
- Using opening when the goal is to fill holes. Opening removes small foreground objects; closing fills small background gaps.
- Using a morphology kernel larger than the smallest real object.
- Forgetting that
cv2.thresholdreturns both the selected threshold and the output image. - Reading a missing file.
cv2.imreadreturnsNoneinstead of raising an exception.
A small, testable pipeline
This example exposes the main parameters so they can be changed systematically.
import cv2
import numpy as np
def segment(path, blur_size=5, low=50, high=150,
block_size=31, constant=10, morph_size=5):
image = cv2.imread(path)
if image is None:
raise FileNotFoundError(path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (blur_size, blur_size), 0)
edges = cv2.Canny(blur, low, high)
_, mask = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
kernel = cv2.getStructuringElement(
cv2.MORPH_ELLIPSE, (morph_size, morph_size)
)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
return gray, blur, edges, mask
gray, blur, edges, mask = segment("input.jpg")
cv2.imwrite("edges.png", edges)
cv2.imwrite("mask.png", mask)Use odd values for blur_size and morph_size. Tune one stage at a time. If the mask loses object boundaries, reduce blur or morphology size before changing the threshold.
Exercise
An image has uneven illumination, isolated white specks, and broken foreground regions. Which changes should you try first?
Show answer
Try adaptive thresholding for uneven illumination, opening to remove isolated specks, and closing to join small breaks. Validate kernel sizes so real narrow features are not removed.