📘
Gaussian Kernel Generation
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 σ, 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) is determined by its distance from the center (c,c), where c=size//2.
- Compute the distance of each position from the center.
- Calculate the Gaussian value at each position using the formula. The main equation for the Gaussian value G(i,j) is
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:
- The center of the kernel c is calculated as size//2=3//2=1, so the kernel is centered at (1,1).
- For each position (i,j), the Gaussian value G(i,j) is computed using the formula: G(i,j)=exp(−2⋅1.02(i−1)2+(j−1)2), resulting in a 3x3 matrix of unnormalized values.
- The unnormalized values are then normalized by dividing each value by the sum of all values in the matrix, so that the sum of all values equals 1.
- The normalized values are rounded to 6 decimal places, yielding the final output: [[0.075114, 0.123841, 0.075114], [0.123841, 0.20418, 0.123841], [0.075114, 0.123841, 0.075114]].
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
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.