Sub topic 15
Putting it together: a filter, edge and threshold pipeline
This chapter assumes you can read an image with cv2.imread, know that OpenCV stores color in BGR order with uint8 values, and have met the smoothing, Sobel, Canny, thresholding and morphology calls from earlier chapters. Here you will chain them into one tested function, and you will see where chained steps interact and fail.
Why a pipeline needs design
Each operation in this tutorial has a narrow job.
- Smoothing suppresses noise.
- Gradients and Canny find intensity changes.
- Thresholding turns intensities into a foreground mask.
- Morphology repairs that mask.
Run in the wrong order or with mismatched parameters, they undo each other. A threshold applied before smoothing turns every noisy pixel into a speck. Canny applied to an already binary mask finds only the outline of that mask. Morphology applied to a grayscale image does something quite different from what you intended.
The pipeline below has two branches that share one preprocessing stage.
Stage 1: Load and validate
cv2.imread returns None instead of raising an error when a path is wrong, so check for that first. Convert to grayscale once, and reuse the result in both branches.
import cv2
import numpy as np
img = cv2.imread("input.jpg") # BGR, uint8
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)Stage 2: Smooth once, and choose the filter deliberately
Both branches consume the same blurred image, so the blur choice affects everything downstream.
- Gaussian is the default before Canny and Otsu. It reduces mild sensor noise and costs little.
- Median is the better choice for salt-and-pepper noise, because it removes isolated extreme pixels without smearing them into neighbors.
- Bilateral keeps edges sharper while smoothing flat regions, but it is slower and its
sigmaColorandsigmaSpacevalues need tuning.
The kernel size trades noise removal against lost detail. A larger Gaussian kernel removes more noise, but it also moves and weakens thin edges and merges nearby objects in the mask.
blur = cv2.GaussianBlur(gray, (5, 5), 0)Stage 3: The edge branch
Canny does its own Sobel gradient computation, non-maximum suppression and hysteresis, so you pass it the blurred 8-bit image and two thresholds. A common starting rule is a high threshold two to three times the low one.
edges = cv2.Canny(blur, 50, 150)Canny's own preprocessing does not include a blur in OpenCV, so skipping the blur in Stage 2 gives noisy, broken edges. The output is a uint8 image containing only 0 and 255.
Stage 4: The mask branch
Choose the threshold method from the lighting, not from habit.
| Situation | Method | Why |
|---|---|---|
| Even lighting, bimodal histogram | Otsu | Picks the threshold that best separates two intensity groups |
| Gradual shading or shadows | Adaptive Gaussian | Computes a threshold per neighborhood |
| Known fixed brightness, such as a controlled light box | Fixed | Cheap and predictable across images |
Otsu ignores the threshold value you supply and returns the one it chose. Adaptive thresholding needs an odd block size and a constant subtracted from the local mean. A block size much smaller than the object makes the interior of large objects turn into holes, because the local average inside a uniform region equals the pixel values.
otsu_value, otsu = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
print("Otsu threshold:", otsu_value)
adaptive = cv2.adaptiveThreshold(
blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 10
)Both results are binary masks. Whether the foreground is white or black depends on the image, so decide that now. If the object is darker than the background, use cv2.THRESH_BINARY_INV so the object ends up as 255. Morphology treats white as the thing to grow or shrink.
Stage 5: Clean the mask
Opening (erosion then dilation) removes small white specks. Closing (dilation then erosion) fills small black holes. Order matters: opening first avoids closing together specks that are close to the real object.
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(otsu, cv2.MORPH_OPEN, se)
cleaned = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, se)The structuring element should be smaller than the smallest feature you want to keep and larger than the noise you want to remove. If real thin features vanish, the element is too big.
A complete, testable function
Wrapping the stages in one function makes the pipeline repeatable and lets you test it on synthetic images where you know the right answer. The function below accepts a grayscale or BGR image, so callers do not need to convert first.
import cv2
import numpy as np
def run_pipeline(
image,
blur_ksize=5,
canny_low=50,
canny_high=150,
use_adaptive=False,
dark_object=False,
morph_ksize=5,
):
if image is None:
raise ValueError("image is None")
if blur_ksize % 2 == 0:
raise ValueError("blur_ksize must be odd")
if image.ndim == 3:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
gray = image
blur = cv2.GaussianBlur(gray, (blur_ksize, blur_ksize), 0)
edges = cv2.Canny(blur, canny_low, canny_high)
mode = cv2.THRESH_BINARY_INV if dark_object else cv2.THRESH_BINARY
if use_adaptive:
mask = cv2.adaptiveThreshold(
blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, mode, 31, 10
)
else:
_, mask = cv2.threshold(blur, 0, 255, mode + cv2.THRESH_OTSU)
se = cv2.getStructuringElement(
cv2.MORPH_ELLIPSE, (morph_ksize, morph_ksize)
)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, se)
return blur, edges, maskTesting with a synthetic image
A synthetic image has a known answer: a white disc on a dark background with added noise. After the pipeline, the mask area should be close to the disc area, and the edge pixels should lie near the disc's circumference.
rng = np.random.default_rng(0)
clean = np.zeros((200, 200), np.uint8)
cv2.circle(clean, (100, 100), 50, 255, -1)
noisy = clean.astype(np.int16) + rng.normal(0, 25, clean.shape).astype(np.int16)
noisy = np.clip(noisy, 0, 255).astype(np.uint8)
blur, edges, mask = run_pipeline(noisy)
true_area = int(np.count_nonzero(clean))
mask_area = int(np.count_nonzero(mask))
overlap = int(np.count_nonzero((mask > 0) & (clean > 0)))
union = int(np.count_nonzero((mask > 0) | (clean > 0)))
print("true area:", true_area, "mask area:", mask_area)
print("IoU:", overlap / union)
assert overlap / union > 0.9, "mask does not match the known disc"The IoU (intersection over union) score is 1.0 for a perfect match. The assertion turns a visual impression into a pass or fail check, so a later parameter change that breaks the mask is caught immediately.
Common failure modes
- Wrong dtype or channels.
cv2.Canny,cv2.thresholdwith Otsu, andcv2.adaptiveThresholdrequire single-channel 8-bit input. Otsu in particular raises an error on a 3-channel image. - Inverted mask. A dark object on a light background yields a mask where the background is white. Morphology then cleans the background instead of the object.
- Over-blurring. Edges become thick and weak, so Canny's high threshold drops them. Lower the blur size before lowering the thresholds.
- Under-blurring. Canny returns many short edge fragments and the mask has salt-and-pepper speckle.
- Adaptive block size too small. Large uniform objects appear hollow, with only their boundaries white.
- Otsu on a non-bimodal histogram. With three or more intensity groups, or one group that is tiny, the chosen threshold falls in a poor place. Check the histogram, or switch to adaptive.
- Morphology element too large. Thin lines and small real objects vanish during opening.
Tuning order
Tune one stage at a time, and keep a record of the values that worked.
- Fix the blur first, by looking at the smoothed image.
- Tune the Canny thresholds on the blurred image. Raise the high threshold until background clutter disappears, then lower the low threshold until real edges connect.
- Choose between Otsu and adaptive thresholding by viewing the mask on a few images with different lighting.
- Set the morphology element size last, since it depends on how noisy the mask is.
- Save a few representative images with their expected output as regression tests.
Exercise
A pipeline produces a mask where a large, evenly lit dark object on a light background shows as a black region inside a white frame, and the morphological cleanup removes small bright specks from the background instead of the object. What two changes would you make, and why?
Show answer
First, switch to cv2.THRESH_BINARY_INV (combined with cv2.THRESH_OTSU if you use Otsu), so the dark object becomes 255 and the background 0. Morphology operates on white pixels, so the object is now the thing being cleaned. Second, re-check the structuring element size after the inversion, because the specks that matter are now small white regions inside or near the object, and an element that is too large would remove thin parts of the real object. Verify with a synthetic or known image and an IoU check.
Exercise
Your Canny output on a noisy photo is full of short, disconnected edge fragments. List the stage you would change first and the direction of the change, and name one side effect to watch for.
Show answer
Increase the Gaussian blur kernel (for example from 3 to 5) before changing the Canny thresholds, since noise gradients are being picked up as edges. The side effect is that real thin edges become weaker and shift slightly, so the high threshold may now need to be lowered a little, and fine detail can be lost.