Sub topic 16
Tuning parameters and avoiding common mistakes
This chapter assumes you have read the earlier chapters on smoothing, gradients, Canny, thresholding and morphology. It also assumes you can run Python with cv2 and numpy installed. It collects the parameters that most affect your results, the mistakes that most often cause silent failures, and a repeatable way to tune a pipeline.
Why tuning goes wrong
OpenCV filters rarely raise errors when parameters are poor. A bad kernel size or threshold still returns an image, just a useless one. Most debugging comes down to two questions: is the data what you think it is (shape, dtype, channel order, value range), and is each parameter matched to the scale of what you want to find?
Parameter reference
| Function | Parameter | What it controls | Starting point | Typical failure |
|---|---|---|---|---|
| `GaussianBlur` | `ksize`, `sigmaX` | Amount of smoothing. With sigma 0, OpenCV derives it from `ksize`. | `(5, 5)`, sigma 0 | Too large: small details and weak edges vanish. |
| `medianBlur` | `ksize` | Size of the neighborhood. It must be odd. | 3 or 5 | Large sizes erase thin lines and round off corners. |
| `bilateralFilter` | `d`, `sigmaColor`, `sigmaSpace` | Neighborhood size, and how different in intensity a neighbor may be and still be averaged. | 9, 75, 75 | Slow on large images. Very high sigmas behave like a plain blur. |
| `Sobel` | `ddepth`, `ksize` | Output type and derivative size. | `CV_32F`, 3 | `CV_8U` clips negative gradients. |
| `Canny` | `threshold1`, `threshold2` | Low and high hysteresis limits. | Ratio of 1:2 to 1:3 | Too low gives noisy edges. Too high gives broken contours. |
| `threshold` | `thresh`, `type` | Cut level and which side becomes white. | 127, or Otsu | Wrong polarity makes the object black. |
| `adaptiveThreshold` | `blockSize`, `C` | Size of the local window and an offset subtracted from the local mean. | 31, 10 | A window smaller than the object hollows it out. |
| `morphologyEx` | structuring element size | Size of the features removed or filled. | 3 to 5 | Too large: real structures are deleted or merged. |
Mistakes that corrupt data
Unsigned output depth in gradients
A Sobel output with depth CV_8U saturates. Rising edges clip to 255 and falling edges clip to 0, so you lose half of the edges. This example uses a bright bar, which has one rising and one falling edge:
import cv2
import numpy as np
gray = np.zeros((100, 100), np.uint8)
gray[:, 30:70] = 200 # bright vertical bar: rising edge at 30, falling at 70
bad = cv2.Sobel(gray, cv2.CV_8U, 1, 0, ksize=3)
good = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
print("8-bit range:", bad.min(), bad.max(),
"columns with response:", np.count_nonzero(bad.any(axis=0)))
print("float range:", good.min(), good.max(),
"columns with response:", np.count_nonzero(good.any(axis=0)))The 8-bit result responds on only two columns, because the falling edge became 0. The float result responds on four and keeps the sign. Use CV_32F or CV_16S, then take np.abs or cv2.cartToPolar before converting to 8 bits for display.
Unsigned arithmetic in NumPy
uint8 arrays wrap around when you use NumPy operators. For example, np.uint8(250) + np.uint8(10) gives 4. Use cv2.add, cv2.subtract and cv2.addWeighted, which saturate at 0 and 255. Or convert to a wider type first, compute, then np.clip(...).astype(np.uint8).
Channel order and unchecked reads
cv2.imread returns BGR and returns None on failure. Convert with cv2.cvtColor before passing the image to a library that expects RGB. Thresholds, Canny and Otsu all need a single-channel 8-bit image, so convert color to gray first.
Even or invalid kernel sizes
GaussianBlur, medianBlur and adaptiveThreshold need odd sizes. adaptiveThreshold also needs blockSize greater than 1. An even value raises an error, but a size one step too small or too large will not, and it changes the result a lot.
Mistakes that corrupt results
- Skipping the pre-blur. Canny contains its own 5×5 Sobel but no smoothing. Without a blur, sensor noise becomes dozens of tiny edges that survive hysteresis.
- Thresholds on the wrong scale. Canny's gradient values depend on image contrast, so
(50, 150)suits one image and not another. Keepthreshold2at two to three timesthreshold1. A low limit that is too close to the high limit removes the benefit of hysteresis. - Otsu on an unsuitable histogram. Otsu assumes two intensity populations. On a flat, unimodal, or three-class image it picks a number that splits nothing meaningful. It also needs 8-bit gray input. The value you pass is ignored, but you must still pass something.
- Global threshold under uneven lighting. If a shadow crosses the page, no single cut works. Switch to
adaptiveThreshold, withblockSizelarger than the thickest feature (such as a text stroke) so the local mean reflects background. - Wrong foreground polarity for morphology. Opening and closing treat white as foreground. If your object came out black, use
THRESH_BINARY_INVbefore cleaning up. Otherwise opening removes your background specks instead of your noise. - Morphology applied before thresholding. Opening and closing as described here are for binary masks. Use them after thresholding.
A workable tuning method
Tune in pipeline order and fix one stage before moving to the next. A downstream parameter can hide an upstream error, so changing everything at once tells you nothing.
Measure instead of eyeballing
A single scalar, such as the fraction of pixels marked as edges, gives you something to compare across settings. The next script builds a noisy synthetic image with one known circle. The circle's outline is roughly 300 pixels out of 40,000, so any fraction far above that is mostly noise.
import cv2
import numpy as np
rng = np.random.default_rng(0)
clean = np.full((200, 200), 60, np.uint8)
cv2.circle(clean, (100, 100), 50, 180, -1)
noisy = np.clip(clean + rng.normal(0, 15, clean.shape), 0, 255).astype(np.uint8)
def auto_canny(img, sigma=0.33):
"""Derive Canny limits from the median intensity."""
v = float(np.median(img))
low = int(max(0, (1.0 - sigma) * v))
high = int(min(255, (1.0 + sigma) * v))
return cv2.Canny(img, low, high)
for k in (1, 5, 9):
blur = cv2.GaussianBlur(noisy, (k, k), 0)
for low, high in ((50, 150), (100, 200)):
edges = cv2.Canny(blur, low, high)
frac = np.count_nonzero(edges) / edges.size
print(f"ksize={k} thresholds=({low},{high}) edge fraction={frac:.4f}")
print("auto_canny fraction:",
np.count_nonzero(auto_canny(cv2.GaussianBlur(noisy, (5, 5), 0))) / noisy.size)Run it and watch the fraction fall toward the true outline as the blur grows and the thresholds rise. The median heuristic in auto_canny is only a starting point. If the median is 0, as in a mostly black image, both limits become 0, so set the limits by hand in that case.
Know when parameters stop helping
If no setting works, the stage is probably the wrong tool. Salt-and-pepper noise needs medianBlur, not a larger Gaussian. Strong shadows need adaptiveThreshold or illumination correction, not a cleverer global value. A blurry source image needs a better capture, not smaller Canny thresholds.
Quick checklist
- Confirm
img is not None, then printshapeanddtype. - Convert to gray exactly once.
- Match the blur to the noise type and keep the kernel as small as works.
- Use
CV_32Ffor derivatives and convert for display only. - Keep Canny's high limit at 2 to 3 times the low limit.
- Check the foreground is white before morphology.
- Save intermediate images at each stage so you can see where the result goes wrong.
Exercise
A Sobel x-derivative of a photo shows only the left edges of objects, and the right edges are missing. The call is cv2.Sobel(gray, cv2.CV_8U, 1, 0). What is wrong, and what is the fix?
Show answer
The 8-bit unsigned output depth clips negative gradients to 0, and the right edges of bright objects are negative. Use cv2.CV_32F (or cv2.CV_16S) as the output depth, then take the absolute value or compute magnitude with cv2.cartToPolar and normalize to 8 bits for display.
Exercise
You threshold a scanned page with cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU). The left third of the page is in shadow and comes out entirely black. Name a better function and the one parameter you must size carefully.
Show answer
Use cv2.adaptiveThreshold, for example with ADAPTIVE_THRESH_GAUSSIAN_C. Set blockSize (odd, greater than 1) larger than the thickest feature, such as a text stroke, so the local mean reflects background rather than the stroke itself. The offset C then fine-tunes how much darker than the local mean a pixel must be to count as foreground.