Image Filtering: Convolution, Blur and Denoising
Every camera image is noisy: photon counts fluctuate, sensors add read noise, transmission flips bits. Many vision steps also need a smoother image than the camera gives, because edges, corners and thresholds react to every noisy pixel. Filtering replaces each pixel by a combination of its neighbours. A linear filter is a weighted sum with fixed weights, the kernel, slid over the image; the same operation, with learned kernels, is the convolutional layer of a CNN (convolution layers covers that side, convolution the maths). Non-linear filters (median, bilateral) do things no kernel can, such as removing salt-and-pepper noise or smoothing without blurring edges. This lesson builds a filter from scratch, checks it against OpenCV, and measures each filter's effect on a noisy photo with PSNR.
Correlation, convolution and the kernel
For an image and a kernel indexed from to , cross-correlation and convolution are
Convolution is correlation with the kernel flipped in both directions. For symmetric kernels (box, Gaussian, Laplacian) they are identical; for asymmetric ones (Sobel, any learned kernel) the sign or direction flips. OpenCV's filter2D and deep-learning "convolutions" compute correlation; scipy.ndimage.convolve and the textbook definition flip.
Watch a kernel slide over a small image of integers. Pick box blur (each output is the mean of the 9 pixels under the window) or sharpen (5 times the centre minus the four neighbours), and switch between "valid" (no padding, the output shrinks by 2) and "same" (zero padding, the size is kept):
The blur turns the bright square's sharp border into a ramp, the sharpen kernel overshoots on both sides of it (values below 0 and above 9). With zero padding, the pixels along the border are averaged with zeros that are not in the image, so the blurred border gets darker: the border problem the next example treats.
import numpy as np
import cv2
from scipy import ndimage
cv2.setLogLevel(0)
impulse = np.zeros((5, 5), np.float32); impulse[2, 2] = 1 # a single bright pixel
k = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], np.float32)
corr = cv2.filter2D(impulse, -1, k)
conv = ndimage.convolve(impulse, k)
print("cv2.filter2D (correlation) of an impulse:"); print(corr[1:4, 1:4].astype(int))
print("scipy.ndimage.convolve (convolution):"); print(conv[1:4, 1:4].astype(int))
print("filter2D with the flipped kernel equals convolution:", np.allclose(cv2.filter2D(impulse, -1, k[::-1, ::-1]), conv))
row = np.array([[1, 2, 3, 4, 5]], np.uint8)
for name, mode in [("BORDER_CONSTANT (0)", cv2.BORDER_CONSTANT), ("BORDER_REPLICATE", cv2.BORDER_REPLICATE),
("BORDER_REFLECT", cv2.BORDER_REFLECT), ("BORDER_REFLECT_101", cv2.BORDER_REFLECT_101),
("BORDER_WRAP", cv2.BORDER_WRAP)]:
padded = cv2.copyMakeBorder(row, 0, 0, 3, 3, mode, value=0)[0].tolist()
blurred = "n/a" if mode == cv2.BORDER_WRAP else [round(float(v), 2) for v in cv2.blur(row.astype(np.float32), (5, 1), borderType=mode)[0]]
print(f"{name:20s} {padded} box-5 blur: {blurred}")cv2.filter2D (correlation) of an impulse:
[[9 8 7]
[6 5 4]
[3 2 1]]
scipy.ndimage.convolve (convolution):
[[1 2 3]
[4 5 6]
[7 8 9]]
filter2D with the flipped kernel equals convolution: True
BORDER_CONSTANT (0) [0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0] box-5 blur: [1.2, 2.0, 3.0, 2.8, 2.4]
BORDER_REPLICATE [1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 5] box-5 blur: [1.6, 2.2, 3.0, 3.8, 4.4]
BORDER_REFLECT [3, 2, 1, 1, 2, 3, 4, 5, 5, 4, 3] box-5 blur: [1.8, 2.2, 3.0, 3.8, 4.2]
BORDER_REFLECT_101 [4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2] box-5 blur: [2.2, 2.4, 3.0, 3.6, 3.8]
BORDER_WRAP [3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3] box-5 blur: n/a
The response of a filter to a single bright pixel is its impulse response: correlation stamps the kernel upside down, convolution stamps it as written. The border modes decide what the kernel sees beyond the edge. Zeros (CONSTANT) darken the border (the ramp 1–5 blurs to 2.4 at its bright end); REPLICATE repeats the edge pixel; REFLECT mirrors including the edge pixel (3 2 1 | 1 2 3), REFLECT_101 mirrors around it (4 3 2 | 1 2 3), which is OpenCV's default for filters; WRAP treats the image as periodic, as an FFT does. CNNs use zero padding, which is one reason their feature maps behave differently near the border.
From scratch, checked against OpenCV
NumPy's sliding_window_view gives every window as a 4-D view without copying; one einsum multiplies each window by the kernel and sums. np.pad(..., mode="reflect") is OpenCV's REFLECT_101.
import numpy as np
import cv2
from numpy.lib.stride_tricks import sliding_window_view
from skimage import data
cv2.setLogLevel(0)
def filter2d(img, k):
"""Cross-correlation with BORDER_REFLECT_101, like cv2.filter2D."""
kh, kw = k.shape
pad = np.pad(img.astype(np.float64), ((kh // 2, kh // 2), (kw // 2, kw // 2)), mode="reflect")
win = sliding_window_view(pad, (kh, kw)) # (H, W, kh, kw), no copy
return np.einsum("ijkl,kl->ij", win, k)
img = data.camera().astype(np.float32)
rng = np.random.default_rng(0)
for size in [3, 5]:
k = rng.normal(size=(size, size)).astype(np.float32) # an arbitrary, asymmetric kernel
ours, ref = filter2d(img, k), cv2.filter2D(img, -1, k)
print(f"{size}x{size} random kernel: max |ours - cv2| = {np.abs(ours - ref).max():.5f} (values up to {np.abs(ref).max():.0f})")
box = np.ones((3, 3)) / 9
print("box 3x3 from scratch vs cv2.blur:", round(float(np.abs(filter2d(img, box) - cv2.blur(img, (3, 3))).max()), 5))
print("corner pixel: image", img[:2, :2].tolist(), "-> box", round(float(filter2d(img, box)[0, 0]), 2))3x3 random kernel: max |ours - cv2| = 0.00009 (values up to 611)
5x5 random kernel: max |ours - cv2| = 0.00067 (values up to 1860)
box 3x3 from scratch vs cv2.blur: 1e-05
corner pixel: image [[200.0, 200.0], [200.0, 199.0]] -> box 199.56
The two agree to within float32 rounding (OpenCV computes in float32, our version in float64), for asymmetric random kernels too, so the orientation and the border handling are the same. The corner value shows the mirror at work: the window at (0, 0) contains the reflected pixels, never zeros.
Box and Gaussian blur
The box filter averages a window. The Gaussian weights neighbours by distance:
The factorisation is the important part: the 2-D kernel is the outer product of two 1-D kernels, so the filter can run as a vertical pass and then a horizontal pass. A kernel costs multiplications per pixel; two passes cost . (The box filter is separable too, and with running sums it costs the same for any size.)
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
g1 = cv2.getGaussianKernel(7, 1.5) # (7, 1) column vector
print("1-D Gaussian, size 7, sigma 1.5:", g1.ravel().round(4).tolist(), "sum", round(float(g1.sum()), 4))
g2 = g1 @ g1.T # outer product: the 2-D kernel
print("2-D kernel = outer product, rank", np.linalg.matrix_rank(g2), "| centre", round(float(g2[3, 3]), 4))
img = data.camera().astype(np.float32)
a = cv2.sepFilter2D(img, -1, g1, g1) # column pass, row pass
b = cv2.filter2D(img, -1, g2.astype(np.float32)) # one 2-D pass
c = cv2.GaussianBlur(img, (7, 7), 1.5)
print(f"two 1-D passes vs one 2-D pass: {np.abs(a - b).max():.5f} | vs GaussianBlur: {np.abs(a - c).max():.5f}")
for k in [3, 7, 15, 31]:
print(f"kernel {k:2d}x{k:<2d}: {k * k:4d} multiplies per pixel as 2-D, {2 * k:3d} as two 1-D passes")
for ksize in [3, 5, 7, 9, 15]: # sigma = 0: OpenCV picks sigma from the size
g = cv2.getGaussianKernel(ksize, 0).ravel()
x = np.arange(ksize) - ksize // 2
print(f"ksize {ksize:2d}, sigma=0 -> std of the kernel {np.sqrt((g * x * x).sum()):.3f} "
f"(formula 0.3((k-1)/2-1)+0.8 = {0.3 * ((ksize - 1) * 0.5 - 1) + 0.8:.3f})" + (f", weights {g.round(4).tolist()}" if ksize <= 5 else ""))
x = np.arange(240)
stripes = np.tile((128 + 100 * np.cos(2 * np.pi * x / (10 / 3))).astype(np.float32), (8, 1)) # period 3.33 px
for name, f in [("box 5", lambda s: cv2.blur(s, (5, 1))), ("Gaussian sigma 1.2", lambda s: cv2.GaussianBlur(s, (7, 1), 1.2))]:
out = f(stripes)[4, 20:220] - 128
ref = stripes[4, 20:220] - 128
print(f"{name:18s} on stripes of period 3.33: gain {np.dot(out, ref) / np.dot(ref, ref):+.3f}")1-D Gaussian, size 7, sigma 1.5: [0.0366, 0.1113, 0.2167, 0.2707, 0.2167, 0.1113, 0.0366] sum 1.0
2-D kernel = outer product, rank 1 | centre 0.0733
two 1-D passes vs one 2-D pass: 0.00011 | vs GaussianBlur: 0.00000
kernel 3x3 : 9 multiplies per pixel as 2-D, 6 as two 1-D passes
kernel 7x7 : 49 multiplies per pixel as 2-D, 14 as two 1-D passes
kernel 15x15: 225 multiplies per pixel as 2-D, 30 as two 1-D passes
kernel 31x31: 961 multiplies per pixel as 2-D, 62 as two 1-D passes
ksize 3, sigma=0 -> std of the kernel 0.707 (formula 0.3((k-1)/2-1)+0.8 = 0.800), weights [0.25, 0.5, 0.25]
ksize 5, sigma=0 -> std of the kernel 1.000 (formula 0.3((k-1)/2-1)+0.8 = 1.100), weights [0.0625, 0.25, 0.375, 0.25, 0.0625]
ksize 7, sigma=0 -> std of the kernel 1.369 (formula 0.3((k-1)/2-1)+0.8 = 1.400)
ksize 9, sigma=0 -> std of the kernel 1.658 (formula 0.3((k-1)/2-1)+0.8 = 1.700)
ksize 15, sigma=0 -> std of the kernel 2.554 (formula 0.3((k-1)/2-1)+0.8 = 2.600)
box 5 on stripes of period 3.33: gain -0.247
Gaussian sigma 1.2 on stripes of period 3.33: gain +0.077
Two passes and one 2-D pass agree to float rounding, and GaussianBlur is exactly the two-pass version: at that is 62 multiplications instead of 961. When you pass sigma=0, OpenCV derives from the size with , and for it uses fixed binomial-like tables instead ( for ; OpenCV 4.11); either way the kernel's real standard deviation is a little smaller than the formula's, because the tails are cut off. The rule of thumb in the other direction: a kernel should be about wide (three on each side), or the cut-off tails make it boxy.
The last two lines show why the Gaussian is the default blur. A filter multiplies each spatial frequency (cycles per pixel) by its frequency response. For a box of width 5 that is , which is at : stripes with a 3.33-pixel period come out inverted at a quarter of their contrast, a fake pattern. The Gaussian's response is never negative; it only attenuates. Both measured gains match the formulas.
Denoising: Gaussian, median and bilateral
Different noise needs different filters. Gaussian noise (every pixel off by a small random amount) is reduced by averaging. Salt-and-pepper noise (a few pixels set to 0 or 255) is not: one 255 in a 3 x 3 window drags the mean up by 28 levels. The median of the window ignores such outliers and keeps step edges sharp, as long as fewer than half the pixels in the window are corrupted. The bilateral filter is a Gaussian blur whose weights also fall off with the difference in value:
so pixels across an edge (very different value) get almost no weight, and edges survive the smoothing. The experiment adds Gaussian noise () and 5 % salt-and-pepper to camera, filters each version, and measures PSNR (defined in digital images) against the clean image, once over all pixels and once over the 5 % of pixels on strong edges:
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
rng = np.random.default_rng(0)
clean = data.camera()
gauss = (clean + rng.normal(0, 20, clean.shape)).clip(0, 255).astype(np.uint8)
sp = clean.copy(); u = rng.random(clean.shape); sp[u < 0.025] = 0; sp[u > 0.975] = 255
def psnr(a, b, where=None):
d = (a.astype(np.float64) - b) ** 2
mse = d.mean() if where is None else d[where].mean()
return 10 * np.log10(255 ** 2 / mse)
gx = cv2.Sobel(clean, cv2.CV_32F, 1, 0); gy = cv2.Sobel(clean, cv2.CV_32F, 0, 1)
edges = np.hypot(gx, gy) > 200 # strong edges of the clean image
print("own PSNR vs cv2.PSNR:", round(psnr(gauss, clean), 3), round(cv2.PSNR(gauss, clean), 3), "| edge pixels:", round(float(edges.mean() * 100), 1), "%")
filters = {"none": lambda x: x,
"box 5x5": lambda x: cv2.blur(x, (5, 5)),
"Gaussian 5x5, s=1": lambda x: cv2.GaussianBlur(x, (5, 5), 1),
"median 3x3": lambda x: cv2.medianBlur(x, 3),
"median 5x5": lambda x: cv2.medianBlur(x, 5),
"bilateral 9, 40, 5": lambda x: cv2.bilateralFilter(x, 9, 40, 5)}
print("filter | Gaussian noise s=20: all edges | salt & pepper 5 %: all edges")
for name, f in filters.items():
a, b = f(gauss), f(sp)
print(f"{name:19s} | {psnr(a, clean):24.1f} {psnr(a, clean, edges):6.1f} | {psnr(b, clean):22.1f} {psnr(b, clean, edges):6.1f}")own PSNR vs cv2.PSNR: 22.41 22.41 | edge pixels: 5.0 %
filter | Gaussian noise s=20: all edges | salt & pepper 5 %: all edges
none | 22.4 22.2 | 17.8 18.0
box 5x5 | 26.2 17.8 | 25.1 17.5
Gaussian 5x5, s=1 | 28.0 20.8 | 25.6 20.1
median 3x3 | 27.0 22.8 | 30.1 24.4
median 5x5 | 26.8 19.6 | 27.9 19.9
bilateral 9, 40, 5 | 29.1 23.7 | 18.1 18.9
For Gaussian noise the bilateral filter wins on both counts (29.1 dB overall, 23.7 dB on edges), the Gaussian blur comes second overall but loses on edges (20.8 dB, below the unfiltered 22.2), and the box blur is worse on both: it smears edges the most. For salt and pepper the ranking turns over: the median reaches 30.1 dB, linear blurs only spread each outlier over its neighbours, and the bilateral filter does almost nothing (18.1 dB), because an outlier differs so much from its neighbours that the range term gives them no weight. A bigger median () removes more noise but erodes fine detail, and scores lower. The bilateral parameters are d = 9 (window diameter), sigmaColor = 40 (about twice the noise level, so noise is smoothed but real edges are not) and sigmaSpace = 5.
Two cautions about the numbers: PSNR is one image and one noise draw (seed 0), and PSNR is not perceived quality, which is why SSIM and learned metrics exist. Learned denoisers (DnCNN, and the diffusion models behind modern image generation) beat all of these, at much higher cost.
Pitfalls
- Correlation versus convolution. A derivative kernel written for true convolution (some textbooks print Sobel as ), applied with
filter2D, gives the gradient with the opposite sign. Flip it or check with an impulse. - The border. Zero padding darkens borders,
REFLECT_101does not; a model that saw one at training and the other at inference sees different border statistics. uint8output.cv2.filter2D(img_u8, -1, k)keepsuint8and clips negative results to 0: half of a derivative filter disappears. Useddepth=cv2.CV_32F(or float input) for kernels with negative weights.- Kernel size against . A kernel with is almost a box filter; keep the size near .
- Wrong filter for the noise. Medians for impulse noise, Gaussians or bilateral filters for sensor noise. Measure on your own images instead of trusting a table from one photo.
- Blurring before a model that needs detail. Denoising is a trade between noise and detail; small objects and textures suffer first.
Practice
- Apply the box filter
[1, 1, 1] / 3to the row[0, 0, 0, 9, 9, 9]withREPLICATEborders. What is the output?
Answer
Padded row [0, 0, 0, 0, 9, 9, 9, 9]; window means: [0, 0, 3, 6, 9, 9]. The step becomes a ramp over two pixels.
- How many multiplications per pixel does a Gaussian need as a 2-D kernel, and as two passes? For a 1920 x 1080 image?
Answer
against per pixel. The image has 2,073,600 pixels: about 168 million against 37 million multiplications.
- A 3 x 3 window contains
[10, 12, 11, 255, 13, 12, 11, 10, 12]. Compute the mean and the median. Which is the better estimate of the true value?
Answer
Sum , mean ; sorted [10, 10, 11, 11, 12, 12, 12, 13, 255], median 12. The 255 is an impulse (salt); the median, 12, is close to the true value, the mean is not.
- Why does the bilateral filter fail on salt-and-pepper noise?
Answer
Its weights depend on the value difference to the centre pixel. When the centre is an outlier (0 or 255), every neighbour differs from it by a lot, so all neighbours get tiny weights and the outlier mostly keeps its own value. The range term treats the outlier as an edge to preserve.
Test yourself
What is the difference between cv2.filter2D and scipy.ndimage.convolve with the same asymmetric kernel?
- None
filter2Dcomputes correlation,convolveflips the kernel firstconvolveonly works on float imagesfilter2Duses the FFT
Why is a Gaussian blur usually computed as two 1-D passes?
- It is more accurate
- The 2-D Gaussian is the outer product of two 1-D Gaussians, so two passes give the same result with instead of multiplications
- OpenCV cannot do 2-D filters
- To avoid border effects
Which filter scored best on the 5 % salt-and-pepper noise in the lesson?
- Box 5 x 5
- Gaussian 5 x 5
- Median 3 x 3
- Bilateral
A box filter of width 5 applied to stripes with a period of 3.33 pixels gave a gain of . What does the negative sign mean?
- The image got darker
- The stripes come out inverted: bright where they were dark
- The filter is unstable
- The stripes were removed completely