QuiddityML

Image blurring and denoising: box, Gaussian, and median filters

Which kind of noise each filter removes, what the box, Gaussian and median filters compute on a 3 by 3 patch, how sigma decides what a Gaussian blur erases, and the SciPy and PyTorch code for each.

Computer VisionBy · 3 December 2026 · 9 min read

Blurring an image replaces each pixel with a combination of the pixels around it, and denoising uses that to remove random changes the camera added to the pixel values. The box blur takes a plain average of a window, the Gaussian blur takes a weighted average and the median filter takes the middle value of the sorted window. Each one removes a different kind of noise well. Each one also erases some real detail, so picking a filter starts with knowing what the noise looks like.

Noise models

Real images arrive corrupted by sensor noise, low light and compression. Before filtering the corruption out, you have to say what it looks like. That assumption is the noise model. It might be a small value added to every pixel, corruption that grows with brightness or a few pixels knocked to extreme values. It is a choice you make about the images, not a quantity you measure.

A clean line drawing of mountains and a sun turned into a speckled observed image by the noise model.

There are three common noise models:

  • Gaussian noise adds a small random value to every pixel, usually close to zero and centered on it.
  • Shot noise depends on how much light each pixel collected. Bright regions vary more in raw value, but the noise is largest compared with the signal in dark regions, which is why shadows look grainy.
  • Impulse noise sets a scattering of pixels to extreme values, pure black or pure white. It is also called salt-and-pepper noise.

The same mountain scene with Gaussian noise (even fine grain everywhere), shot noise (grain heavier in the dark) and impulse noise (a few scattered black and white dots).

For example, start with a clean pixel value of 0.40 on a scale from 0 to 1:

  • Gaussian noise with a standard deviation of 0.05: one sample comes out at 0.43 and the next at 0.34, small and centered on the true value.
  • Shot noise: the spread grows with the signal. A bright 0.9 pixel varies more than this one, and a near-black 0.02 pixel is dominated by noise.
  • Impulse noise: with a probability of about 0.01 the pixel is forced to 0.0 or 1.0, and otherwise it is untouched.

The pixel value 0.4 under each model: Gaussian samples at 0.34 and 0.43, shot noise error bars that grow from near-black to bright, and impulse noise jumping to 0.0 or 1.0 about 1 percent of the time.

Real camera noise is a mix of all three, and it changes with the ISO setting, the temperature and the sensor. The clean models are approximations that are easy to reason about. The model you assume decides the filter: a median filter suits impulse noise, and a Gaussian blur suits small added noise. A wrong guess picks a filter for noise the images do not have.

The assumed noise model branching to the filter: impulse noise to the median filter, small added noise to the Gaussian blur.

Box blur

Small random noise is centered on the true value, so averaging a pixel with its neighbors cancels most of it. A box blur replaces each pixel with the plain average of a square window around it. As a kernel, a small grid of weights slid over the image, it has equal weights that sum to 1. A 5 by 5 box blur averages 25 pixels.

A 5 by 5 window of pixel values whose plain average, the mean of 25 values, is 13.00.

A 3 by 3 box blur on a noisy pixel

Take a patch with one noise spike:

$$\begin{bmatrix} 48 & 52 & 50 \\ 51 & 240 & 49 \\ 50 & 47 & 53 \end{bmatrix}$$

A box blur replaces the center with the mean of all nine values:

$$48 + 52 + 50 + 51 + 240$$

$$+\ 49 + 50 + 47 + 53 = 640$$

$$\frac{640}{9} \approx 71.1$$

The 240 spike is pulled down to about 71. That is still well above the real background of about 50, because a single outlier moves the mean.

The 3 by 3 neighborhood with 240 in the center averaged to 71.1, with the note that the background is about 50.

Box blur as two passes

A 2D box blur gives the same result as two 1D box blurs, one across the rows and one down the columns. That drops the cost of a k by k blur from $k^2$ multiplications per pixel to $2k$. This code uses SciPy's ready-made filters, where uniform_filter is a box blur and uniform_filter1d blurs along one axis:

import numpy as np
from scipy.ndimage import uniform_filter, uniform_filter1d

img = np.random.rand(64, 64).astype(np.float32)

# direct 2D
a = uniform_filter(img, size=3)
# two 1D passes
b = uniform_filter1d(img, size=3, axis=0)
b = uniform_filter1d(b,   size=3, axis=1)
print(np.allclose(a, b))   # True

The two-pass result matches the direct 2D filter, and a Gaussian blur splits into two passes the same way. The box kernel itself, shaped for PyTorch's F.conv2d:

import torch

def box_kernel(k):
    w = torch.ones(k, k)
    w = w / (k * k)
    return w.view(1, 1, k, k)

A 5 by 5 kernel with 25 taps next to a horizontal 1 by 5 pass and a vertical 5 by 1 pass with 10 taps in total.

The cost: softer detail

Averaging pulls every pixel toward its neighborhood mean, which shrinks noise. It also shrinks real detail, because a blur cannot tell noise from signal. Edges spread over the width of the window, fine texture flattens and small objects can disappear. A larger window gives a stronger effect in both directions. Because every pixel in the window counts equally, a box blur can also leave blocky artifacts.

A noisy scene with a star, letters and stripes: a 3 by 3 box blur cuts the noise on a flat patch from 0.115 to 0.037 with the text still readable, and an 11 by 11 box blur cuts it to 0.009 while the letters become unreadable.

Gaussian blur

A Gaussian blur is a weighted average where the center pixel counts most and the weights fall off with distance along a bell curve. Nearby pixels contribute a lot and far pixels a little. The smooth falloff avoids the blocky look of a box blur. It removes random noise while keeping edges and larger structures more intact than a plain average of the same width, which makes it the usual choice for general smoothing.

A 5 by 5 grid of weights, brightest in the center and fading outward, next to the bell curve they follow.

A 3 by 3 Gaussian kernel

The standard small Gaussian kernel, before dividing, is:

$$\begin{bmatrix} 1 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 1 \end{bmatrix}$$

The weights sum to 16, so divide each by 16. The center weight becomes 0.25, a neighbor that shares an edge with the center 0.125 and a corner 0.0625. As a tensor shaped for F.conv2d:

def gauss3x3():
    w = torch.tensor([[1., 2., 1.], [2., 4., 2.], [1., 2., 1.]])
    w = w / 16
    return w.view(1, 1, 3, 3)

On the noisy patch with 240 in the center and everything else near 50:

$$0.25 \cdot 240$$

$$+\ 0.125 \cdot (51 + 52 + 49 + 47)$$

$$+\ 0.0625 \cdot (48 + 50 + 50 + 53)$$

$$\approx 97.4$$

That is higher than the plain average of about 71, because the Gaussian trusts the center most and the center is the spike. Gaussian blur handles spread-out noise well and single spikes badly.

The 3 by 3 Gaussian kernel as fractions of 16, with the center weight 4/16 = 0.25.

A Gaussian in two passes

A 2D Gaussian blur gives the same result as a 1D Gaussian across the rows followed by the same 1D Gaussian down the columns:

import numpy as np
from scipy.ndimage import (
    gaussian_filter, gaussian_filter1d)

img = np.random.rand(128, 128).astype(np.float32)

direct = gaussian_filter(img, sigma=2.0)

sep = gaussian_filter1d(img, sigma=2.0, axis=0)
sep = gaussian_filter1d(sep, sigma=2.0, axis=1)

print(np.allclose(direct, sep, atol=1e-5))   # True

gaussian_filter runs this two-pass version internally. The weights become negligible beyond about $4\sigma$ from the center, where $\sigma$ is the width of the bell curve described next. So sigma=2 uses a kernel roughly 17 values wide on each axis.

sigma 2.0, radius about 4 times sigma = 8, about 17 taps per axis, a horizontal pass then a vertical pass, and the blurred result.

Sigma sets the scale

Sigma, written $\sigma$, is the width of the Gaussian's bell curve. It sets how much of the neighborhood each output averages. A small sigma keeps edges sharp and texture intact, but it removes only a little noise. A large sigma removes noise strongly and also blurs away small objects, thin lines and fine texture.

Gaussian weights for sigma 1, 2 and 4, each summing to 1, and the same noisy image blurred at each sigma, with the thin line and dots fading as sigma grows.

A Gaussian mostly averages over about $2\sigma$ on each side of a pixel, so structures smaller than roughly $\sigma$ get blended away. For example, take a 2-pixel crack in a concrete surface:

  • $\sigma = 0.8$: about 1.6 pixels on each side, and the crack survives with less contrast
  • $\sigma = 2$: about 4 pixels on each side, and the crack is smeared into the background
  • $\sigma = 5$: about 10 pixels on each side, and the crack is gone along with most fine texture

If the crack is what you are inspecting for, $\sigma = 5$ erased it before the detector ran.

A cracked concrete surface and its brightness profile at the original and at sigma 0.8, 2 and 5, with the dip at the crack shrinking from 0.39 to 0.28, 0.14 and 0.05.

Blurring at many scales

Blurring an image with Gaussians of growing sigma gives a family of images from sharp to smooth. Fine detail vanishes first and larger structures later, which is the basis for looking at an image at several scales.

Gaussian blur is also the usual step before shrinking an image. It removes detail the smaller grid cannot hold, so that detail does not turn into false patterns.

A grid of dots, a square and a circle at sigma 0, 4 and 12, and fine stripes shrunk to a quarter size: without a blur they turn into false wide stripes, and with a Gaussian first they become close to even gray.

Median filter

A weighted average trusts the center pixel most, and when the center is a noise spike that trust gives the wrong answer. A spike of 240 among pixels near 50 comes out of a 3 by 3 Gaussian at about 97. A median filter replaces each pixel with the median of its neighborhood: sort the window's values and take the middle one.

A 3 by 3 neighborhood of values around 100, sorted into a row of nine with the 5th value, 100, as the output.

Median vs mean on the same window

The noisy 3 by 3 patch with the 240 spike has these nine values, sorted:

$$[47, 48, 49, 50, 50, 51, 52, 53, 240]$$

  • mean: $640 / 9 \approx 71.1$
  • median: the 5th value, 50

The median comes out at 50, the true background, because the single 240 is the last entry in the sorted list and does not move the middle. The mean was pulled up by 21.

The nine sorted values with the 5th one, 50, marked as the median, and the mean 640/9 = 71.1 pulled up by 21 from the background.

Median filter in code

import numpy as np
from scipy.ndimage import median_filter

patch = np.array([[ 48,  52,  50],
                  [ 51, 240,  49],
                  [ 50,  47,  53]], dtype=np.uint8)

out = median_filter(patch, size=3, mode='reflect')
# 50, the center is now the neighborhood median
print(out[1, 1])

median_filter sorts each 3 by 3 window and takes the middle value. It cannot be written as a kernel of weights, and it is slower than a Gaussian because every window needs a sort. On a plain list of values, the median is the middle of the sorted list:

def median_1d(vals):
    s = sorted(vals)
    mid = len(s) // 2
    return s[mid]

print(median_1d([48, 52, 50, 51, 240, 49, 50, 47, 53]))   # 50

The input window with the 240 spike, its nine values sorted and the middle value 50 becoming the new center pixel.

Salt-and-pepper noise and sharp edges

Salt-and-pepper noise is isolated pixels stuck at pure black or pure white. An average smears them into gray blotches. The median drops them, because they are the extremes in every window they touch.

Across a sharp edge, most of the window lies on one side. So the median stays at that side's value instead of blending across, and the edge stays crisp.

A shape covered in black and white specks, the same shape after an average with gray blotches, and after a median filter, clean with crisp edges.

Not a universal denoiser

Median filtering is slower than a Gaussian, rounds off corners and thin lines, and does little for small Gaussian noise. It is the right tool for impulse noise.

A 3 by 3 median filter removes impulse noise from a disc, leaves more Gaussian noise than a Gaussian blur (0.031 vs 0.023 on a flat patch), and erases a 1-pixel line while cutting a triangle's tip short.

Which filter to use, and common mistakes

Look at the noise first. Use a median filter for isolated black and white pixels, and a Gaussian blur for fine grain spread over the whole image. Pick the smallest window or sigma that removes enough noise, since every increase also removes detail.

  • Blurring with a sigma larger than the detail you need. A 2-pixel crack is gone at $\sigma = 5$. Size sigma to the smallest structure you want to keep.
  • Using a Gaussian or box blur on salt-and-pepper noise. Both smear each white or black pixel into a gray blotch. The median removes it.
  • Using a median filter on fine Gaussian grain. It leaves more noise than a Gaussian blur and rounds off thin lines and corners.
  • Picking a filter without a noise model. Look at a zoomed-in crop of the images before choosing.
  • Shrinking an image without blurring it first. Fine detail the smaller grid cannot hold turns into false patterns.

Box and Gaussian blurs are convolutions with fixed kernels. Image convolution explained covers the sliding window, kernel weights, padding at the border and stride. Classical image processing covers point operators, which change each pixel using only its own value.

QuiddityML teaches noise models and the box, Gaussian and median filters in the classical image processing unit of its Computer Vision track, where the exercises include building a box kernel from scratch and predicting what a median of an even-length window returns (QuiddityML).