Blur an image with a separable Gaussian filter and reflect padding

Why it matters Image preprocessing, data augmentation and edge detectors all start with a separable Gaussian blur.

A 2D Gaussian blur equals two 1D blurs, one along rows and one along columns. That turns k^2 work per pixel into 2k.

Write gaussian_blur(img, sigma, radius). img is a 2D float array. Build the 1D kernel g[i] = exp(-i^2 / (2 * sigma^2)) for i = -radius..radius and normalise it to sum 1. Pad the image by radius with mode "reflect" (mirror without repeating the edge pixel), filter every row with g, then every column with g. Return an array with the same shape as img.

Signaturedef gaussian_blur(img, sigma, radius)

Example

gaussian_blur([[0, 0, 4, 0], [0, 0, 4, 0]], 1.0, 1) is about [[0, 1.0963, 1.8075, 2.1925], [0, 1.0963, 1.8075, 2.1925]]: the last column mirrors the 4 next to it, so it gets 4 * 0.274 from both sides.

Understand the idea

Blurring replaces each pixel with a weighted average of its neighbours, with nearer pixels counting more, following a bell curve. The 2D bell curve is the product of a horizontal one and a vertical one, so you can blur across first and then down, which is much cheaper. At the border there are no neighbours, so we mirror the image, like seeing a reflection past the edge of a pond.

Tiny example: sigma 1, radius 1. Weights exp(-0.5), 1, exp(-0.5) are 0.607, 1, 0.607; normalised to 0.274, 0.452, 0.274. In the row [0, 0, 4, 0], the third pixel becomes 4 * 0.452 = 1.81, and the last becomes 4 * 0.274 + 4 * 0.274 = 2.19 because its mirrored neighbour is also 4.

Rule: g[i] = exp(-i^2 / (2 sigma^2)) / sum; blur = rows(g) then cols(g), with reflect padding.

Every image library offers this, and it appears in augmentation pipelines and in Canny edge detection.

Shapes and data flow

img (H,W) -> pad (H+2r, W+2r) -> rows (H+2r, W) -> out (H, W)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplegaussian_blur([[0.0, 0.0, 4.0, 0.0], [0.0, 0.0, 4.0, 0.0]], 1.0, 1)
  • Sample 2: flat stays flatgaussian_blur(np.full((3, 4), 5.0), 2.0, 2)