v9.1.1
Menu

Gaussian Kernel Generation

easyPROConvolution and FilteringComputer Vision 2

Implement a function to generate a normalized 2D Gaussian kernel, a fundamental component in image processing and computer vision. Given a kernel size, an odd integer, and standard deviation σ\sigma, create a 2D kernel where each element is computed based on its distance from the center.

The Gaussian distribution is a continuous probability distribution, commonly used to model noise in images. In the context of a 2D Gaussian kernel, the value at each position (i,j)(i, j) is determined by its distance from the center (c,c)(c, c), where c=size//2c = \text{size} // 2.

  1. Compute the distance of each position from the center.
  2. Calculate the Gaussian value at each position using the formula. The main equation for the Gaussian value G(i,j)G(i, j) is
G(i,j)=exp⁡(−(i−c)2+(j−c)22σ2)G(i, j) = \exp\left(-\frac{(i - c)^2 + (j - c)^2}{2\sigma^2}\right)

This technique is widely used in image filtering.

Example

Input
kernel_size = 3, sigma = 1.0
Output
[[0.075114, 0.123841, 0.075114], [0.123841, 0.20418, 0.123841], [0.075114, 0.123841, 0.075114]]
Reasoning
  • Inputs: size =3= 3 means a 3×33 \times 3 grid, and sigma =1.0= 1.0 sets how fast weights fall off from the middle. The center is c=⌊3/2⌋=1c = \lfloor 3/2 \rfloor = 1, so position (1,1)(1, 1) sits in the middle.
  • Squared distances: the center has 00, the four edge cells have 11, and the four corners have 12+12=21^2 + 1^2 = 2.
  • Unnormalized weights: with 2σ2=22\sigma^2 = 2, the center gets e0=1e^{0} = 1, the edges get e−1/2≈0.606531e^{-1/2} \approx 0.606531, and the corners get e−1≈0.367879e^{-1} \approx 0.367879.
  • Normalize: the total is 1+4(0.606531)+4(0.367879)≈4.8976401 + 4(0.606531) + 4(0.367879) \approx 4.897640. Dividing every weight by it gives 1/4.897640≈0.204181/4.897640 \approx 0.20418 in the middle, 0.1238410.123841 on the edges and 0.0751140.075114 in the corners, each rounded to 6 decimal places.
  • Output: a 3×33 \times 3 nested list whose values add up to 1. Notice that it is symmetric under flips and rotations, because only the distance from the center matters. A smaller σ\sigma piles more weight onto the middle: with σ=0.5\sigma = 0.5 the center rises to 0.6193470.619347.

Constraints

  • kernel_size is a positive odd integer
  • sigma is a positive float
  • Return 2D list normalized to sum to 1, rounded to 6 decimal places

Learn this in

More from Computer Vision 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.