Build a normalised 2D Gaussian kernel
Why it matters Resize and blur ops in data loaders and diffusion VAEs use exactly this kernel.
Blurring, anti-aliasing before downsampling and many augmentations use a Gaussian kernel.
Write gaussian_kernel(size, sigma) for an odd size. Coordinates run from -(size // 2) to size // 2. Return the (size, size) kernel with entries exp(-(x^2 + y^2) / (2 sigma^2)), normalised to sum to 1.
def gaussian_kernel(size, sigma)Example
gaussian_kernel(1, 1.0) is [[1.0]].
Understand the idea
A Gaussian blur replaces each pixel with a weighted average of its neighbours, where nearby pixels get more weight following a bell curve. The weights form a small square kernel that must add up to 1, otherwise the image gets brighter or darker. Worked example: size 3, sigma 1. Coordinates are -1, 0, 1. The raw weight at (x, y) is exp(-(x^2 + y^2) / 2): centre 1, the four edge cells exp(-0.5) = 0.6065, the four corners exp(-1) = 0.3679. The sum is 1 + 4 * 0.6065 + 4 * 0.3679 = 4.898. After dividing, the centre is 0.2042, edges 0.1238 and corners 0.0751. Rule: for odd size, coordinates run from -(size // 2) to size // 2; entry = exp(-(x^2 + y^2) / (2 sigma^2)); divide by the sum over the whole 2D kernel. Because the 2D Gaussian is the outer product of two 1D Gaussians, you can build it that way, but normalise by the 2D sum. Used in: blurring before downsampling, data augmentation, and noise in diffusion style image pipelines.