Python Master Course V2 — 163. Convolution, Smoothing and Edge Detection
Purpose and learning outcomes
Filtering can reduce noise or expose boundaries, but every filter changes the evidence in an image. You will generate a noisy rectangle, implement a small NumPy smoothing operation, and compare it with SciPy filtering and derivative-based edges. Known synthetic geometry provides a reference boundary, making false edges and missed edges measurable rather than merely visually impressive.
- Explain image kernels, boundaries and convolution behavior
- Compare smoothing and derivative filters
- Quantify the effect of noise and edge thresholds
Prerequisites
- 146: convolution concepts
- 161–162: image arrays
Environment and execution
Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy scipyUnderstand the model and its assumptions
A kernel is a small array of weights applied around each pixel. A normalized averaging kernel replaces each value with a local mean, reducing independent zero-mean noise while blurring sharp transitions. Mathematical convolution reverses the kernel before multiplying neighborhoods; correlation does not. Symmetric smoothing kernels give the same result either way, which can hide this distinction until an asymmetric derivative kernel is used.
Boundary handling supplies values beyond the image edge. Constant padding assumes a fixed outside intensity, reflection mirrors local content, and wrapping treats opposite edges as neighbors. There is no universally correct choice. Constant zero padding can create artificial dark borders in a bright image, while reflection may duplicate structures near the edge. Keep the policy fixed when comparing implementations.
Derivative filters respond to changes in intensity. A horizontal derivative detects changes along columns, while a vertical derivative detects changes along rows. Combining their magnitudes gives an edge-strength image. Noise also changes intensity rapidly, so smoothing before differentiation often helps. Too much smoothing broadens boundaries and can erase small objects.
A threshold converts a continuous edge strength into a binary decision. A low threshold often increases recall and false positives; a high threshold can suppress noise while losing weak boundaries. Exact pixel agreement is sensitive to whether a reference marks the inner boundary, outer boundary, or a band around both. We use an explicitly declared one-pixel reference band and measure exact overlap with it, acknowledging this metric's localization strictness.
Worked example: build it in stages
The NumPy helper uses sliding_window_view to expose three-by-three neighborhoods after symmetric padding. It computes correlation with an arbitrary kernel; for the symmetric mean kernel this equals convolution. The SciPy Gaussian filter and Sobel derivatives then operate on float arrays with reflected boundaries. A generated binary rectangle supplies its own boundary band, and precision-recall counts describe the chosen threshold.
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
from scipy import ndimage
rng = np.random.default_rng(7)
truth = np.zeros((40, 48), dtype=bool)
truth[10:30, 12:36] = True
clean = truth.astype(float)
noisy = np.clip(clean + rng.normal(0, 0.18, clean.shape), 0, 1)
def correlate3(image, kernel):
image = np.asarray(image, dtype=float)
kernel = np.asarray(kernel, dtype=float)
if image.ndim != 2 or kernel.shape != (3, 3):
raise ValueError("expected a 2D image and 3x3 kernel")
windows = sliding_window_view(np.pad(image, 1, mode="symmetric"), (3, 3))
return np.einsum("ijab,ab->ij", windows, kernel)
mean_kernel = np.ones((3, 3))/9
mean_image = correlate3(noisy, mean_kernel)
reference_mean = ndimage.correlate(noisy, mean_kernel, mode="reflect")
assert np.allclose(mean_image, reference_mean)
smoothed = ndimage.gaussian_filter(noisy, sigma=1.0, mode="reflect")
gx = ndimage.sobel(smoothed, axis=1, mode="reflect") / 8.0
gy = ndimage.sobel(smoothed, axis=0, mode="reflect") / 8.0
magnitude = np.hypot(gx, gy)
edge = magnitude > 0.15
structure = np.ones((3, 3), dtype=bool)
reference = (ndimage.binary_dilation(truth, structure=structure)
& ~ndimage.binary_erosion(truth, structure=structure))
tp = int(np.count_nonzero(edge & reference))
fp = int(np.count_nonzero(edge & ~reference))
fn = int(np.count_nonzero(~edge & reference))
precision = tp/(tp+fp) if tp+fp else None
recall = tp/(tp+fn) if tp+fn else None
print("edge counts:", tp, fp, fn)
print("precision/recall:", precision, recall)
print("noisy/smoothed MSE:", np.mean((noisy-clean)**2), np.mean((smoothed-clean)**2))What the output means
The NumPy and SciPy mean-filter outputs should agree within floating-point tolerance because their symmetric/reflected boundary conventions align for this case. Edge counts, precision, recall, and mean-squared errors are measured results and are not fixed claims here. A lower overall reconstruction error can coexist with blurrier boundaries, showing why a smoothing metric and an edge-localization metric answer different questions.
Guided lab and acceptance checks
Generate three development images with different noise seeds and compare thresholds 0.10, 0.15, and 0.20 using the same boundary definition. Choose one setting for a declared objective, such as high recall while limiting false positives. Then evaluate fresh noise seeds without retuning.
Acceptance requires float arithmetic, a documented padding rule, a reference-boundary definition, and both false-positive and false-negative counts. Include a bright constant image as a boundary test and a very thin rectangle as a small-feature test. Explain why smoothing that helps the large rectangle may remove the thin one.
Common mistakes and repairs
Applying derivative filters to uint8 may lose negative responses or wrap arithmetic. Dividing edge magnitude by its maximum separately for every image changes the threshold meaning and can amplify a nearly blank image's noise. Do not confuse a convolution implementation with correlation for asymmetric kernels. Avoid choosing an edge threshold solely because one displayed image looks clean.
Questions and answers
Why does averaging reduce independent noise?
Averaging combines several noise contributions that partly cancel when they are independent and centered. Real noise may be correlated or signal-dependent, so the reduction is not universal. The same averaging also mixes values across real boundaries, creating blur.
Why divide Sobel output by eight here?
The conventional Sobel weights have a scale factor relative to an intensity change. Dividing gives a more interpretable derivative scale for this example. Any threshold must be defined together with that scaling, the input range, and the smoothing settings.
Does a strong gradient identify an object boundary?
Not necessarily. Texture, shadows, reflections, and noise also produce intensity changes. An edge map is a low-level measurement. Object meaning requires additional assumptions or a separately evaluated model.
Why compare against a boundary band rather than the whole mask?
Edges describe transitions, while a segmentation mask describes object interiors. Comparing an edge map with the full filled rectangle would punish the algorithm for not marking interior pixels that it was never designed to detect.
Can lower MSE imply worse edge localization?
Yes. Smoothing many noisy background pixels can improve average squared error while moving or broadening a relatively small boundary. Choose metrics that match the downstream goal rather than assuming one image-quality number measures every useful property.
Exercises
1. Verify that the mean filter preserves a constant image under reflected boundaries. 2. Compare an asymmetric kernel with its reversed version. 3. Explain why an all-zero predicted edge map needs an explicit precision convention.
Worked solutions and reasoning
Kernel reversal changes the sign of this antisymmetric derivative response. With no predicted edges, precision has a zero denominator, so the example reports None. Recall is still zero when a nonempty reference boundary exists; report both denominators rather than masking the failure.
constant = np.full((6, 7), 0.4)
assert np.allclose(correlate3(constant, mean_kernel), constant)
ramp = np.tile(np.arange(7, dtype=float), (6, 1))
derivative = np.array([[0, 0, 0], [-1, 0, 1], [0, 0, 0]], dtype=float)
forward = correlate3(ramp, derivative)
reversed_response = correlate3(ramp, derivative[::-1, ::-1])
assert np.allclose(forward, -reversed_response)Recap
Filtering requires deliberate kernels, dtypes, boundaries, scales, and evaluation targets. Synthetic truth lets you separate noise reduction from boundary preservation. Measure the tradeoff and keep the threshold protocol fixed before interpreting a visually attractive edge map as a useful result.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.