TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Image Filtering: Convolution, Blur and Denoising

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 II and a (2k+1)×(2k+1)(2k+1) \times (2k+1) kernel KK indexed from −k-k to kk, cross-correlation and convolution are

(I⋆K)[r,c]=∑i=−kk∑j=−kkK[i,j] I[r+i,c+j],(I∗K)[r,c]=∑i=−kk∑j=−kkK[i,j] I[r−i,c−j](I \star K)[r, c] = \sum_{i=-k}^{k} \sum_{j=-k}^{k} K[i, j]\, I[r + i, c + j], \qquad (I * K)[r, c] = \sum_{i=-k}^{k} \sum_{j=-k}^{k} K[i, j]\, I[r - i, c - j]

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 3×33 \times 3 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):

Input image (0–9)111111111111111111115511188881115511188881115511188881115511188881115511111111115511111911111111111191111111111119111111111111911111111111191111Kernel111111111all × 1/9productsdoneFeature map 10 × 102.63.33.32.61.811.92.82.81.94.15.75.74.12.612.33.73.72.35.7885.73.312.33.73.72.35.7885.73.312.33.73.72.34.15.75.74.12.612.33.73.72.32.64.24.23.41.811.92.82.81.911.92.82.81.911.41.91.91.411.92.83.72.81.91111111.92.83.72.81.91111111.92.83.72.81.911red > 0, blue < 0; max |value| 8

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.

python · try it yourself
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 k×kk \times k 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.

python · try it yourself
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 k×kk \times k window. The Gaussian weights neighbours by distance:

Gσ(x,y)=12πσ2exp⁡ ⁣(−x2+y22σ2)=gσ(x) gσ(y)G_\sigma(x, y) = \frac{1}{2\pi\sigma^2} \exp\!\left(-\frac{x^2 + y^2}{2\sigma^2}\right) = g_\sigma(x)\, g_\sigma(y)

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 k×kk \times k kernel costs k2k^2 multiplications per pixel; two passes cost 2k2k. (The box filter is separable too, and with running sums it costs the same for any size.)

5 x 5 kernel = 5 x 1 x 1 x 5 cost per pixel: one 2-D pass: 25 two 1-D passes: 10 same result
python · try it yourself
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 31×3131 \times 31 that is 62 multiplications instead of 961. When you pass sigma=0, OpenCV derives σ\sigma from the size with 0.3((k−1)/2−1)+0.80.3((k - 1)/2 - 1) + 0.8, and for k≤9k \le 9 it uses fixed binomial-like tables instead ([1,2,1]/4[1, 2, 1]/4 for k=3k = 3; 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 6σ+16\sigma + 1 wide (three σ\sigma 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 ff (cycles per pixel) by its frequency response. For a box of width 5 that is sin⁡(5πf)/(5sin⁡πf)\sin(5\pi f) / (5 \sin \pi f), which is −0.247-0.247 at f=0.3f = 0.3: stripes with a 3.33-pixel period come out inverted at a quarter of their contrast, a fake pattern. The Gaussian's response e−2π2σ2f2=0.077e^{-2\pi^2\sigma^2 f^2} = 0.077 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:

J(p)=1Wp∑q∈Ω(p)Gσs(∥p−q∥)  Gσr(∣I(p)−I(q)∣)  I(q)J(p) = \frac{1}{W_p} \sum_{q \in \Omega(p)} G_{\sigma_s}(\lVert p - q \rVert)\; G_{\sigma_r}(\lvert I(p) - I(q) \rvert)\; I(q)

so pixels across an edge (very different value) get almost no weight, and edges survive the smoothing. The experiment adds Gaussian noise (σ=20\sigma = 20) 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:

python · try it yourself
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 3×33 \times 3 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 (5×55 \times 5) 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 [1,0,−1][1, 0, -1]), applied with filter2D, gives the gradient with the opposite sign. Flip it or check with an impulse.
  • The border. Zero padding darkens borders, REFLECT_101 does not; a model that saw one at training and the other at inference sees different border statistics.
  • uint8 output. cv2.filter2D(img_u8, -1, k) keeps uint8 and clips negative results to 0: half of a derivative filter disappears. Use ddepth=cv2.CV_32F (or float input) for kernels with negative weights.
  • Kernel size against σ\sigma. A 3×33 \times 3 kernel with σ=3\sigma = 3 is almost a box filter; keep the size near 6σ+16\sigma + 1.
  • 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

  1. Apply the box filter [1, 1, 1] / 3 to the row [0, 0, 0, 9, 9, 9] with REPLICATE borders. 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.

  1. How many multiplications per pixel does a 9×99 \times 9 Gaussian need as a 2-D kernel, and as two passes? For a 1920 x 1080 image?
Answer

8181 against 1818 per pixel. The image has 2,073,600 pixels: about 168 million against 37 million multiplications.

  1. 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 346346, mean ≈38.4\approx 38.4; 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.

  1. 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?

  1. None
  2. filter2D computes correlation, convolve flips the kernel first
  3. convolve only works on float images
  4. filter2D uses the FFT

Why is a Gaussian blur usually computed as two 1-D passes?

  1. It is more accurate
  2. The 2-D Gaussian is the outer product of two 1-D Gaussians, so two passes give the same result with 2k2k instead of k2k^2 multiplications
  3. OpenCV cannot do 2-D filters
  4. To avoid border effects

Which filter scored best on the 5 % salt-and-pepper noise in the lesson?

  1. Box 5 x 5
  2. Gaussian 5 x 5
  3. Median 3 x 3
  4. Bilateral

A box filter of width 5 applied to stripes with a period of 3.33 pixels gave a gain of −0.247-0.247. What does the negative sign mean?

  1. The image got darker
  2. The stripes come out inverted: bright where they were dark
  3. The filter is unstable
  4. The stripes were removed completely