Gaussian Blur Weights That Sum to One

Computer VisionMedium+15 XP+15

Gaussian Blur Weights That Sum to One

A box blur averages every pixel in a window equally, which produces visible blockiness. A Gaussian blur weights the centre most and fades smoothly outward, which is why it looks natural. This problem builds the weights.

For a size × size kernel, with the centre at c = (size - 1) / 2:

wij=exp⁡(−(i−c)2+(j−c)22σ2)w_{ij} = \exp\left(-\frac{(i - c)^2 + (j - c)^2}{2\sigma^2}\right)wij​=exp(−2σ2(i−c)2+(j−c)2​)

Then divide every weight by the total, so they sum to 1.

Task: write gaussian_kernel(size, sigma) returning the normalised kernel as a list of rows, every weight rounded to 4 decimal places.

  • size is odd, so the centre falls exactly on a pixel. For size = 3, c = 1.0; for size = 5, c = 2.0.
  • Normalise after computing all the raw weights, using the unrounded total. Round only at the very end.
  • (i - c)² + (j - c)² is squared distance from the centre, so the kernel is symmetric in both directions and across both diagonals — a quick visual check.

The normalisation is what makes this a blur rather than a brightness change. Weights summing to 1 mean a flat grey region comes out exactly as grey as it went in; weights summing to 1.3 would brighten the whole image by 30%.

And notice what sigma controls: at sigma = 0.5 on a 3×3 kernel, the centre holds about 62% of the weight and the blur is barely perceptible. Raise it and the weight spreads outward until the kernel approaches a flat average. The useful rule is that size should be roughly 6 × sigma — any smaller and you're clipping off weight the formula wanted to give you.

Examples

size = 3
sigma = 1.0
returns [[0.0751, 0.1238, 0.0751], [0.1238, 0.2042, 0.1238], [0.0751, 0.1238, 0.0751]]
size = 3
sigma = 0.5
returns [[0.0113, 0.0838, 0.0113], [0.0838, 0.6193, 0.0838], [0.0113, 0.0838, 0.0113]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run