28. Gaussian Blur medium
Implement a program that applies a Gaussian blur filter to a 2D image. Given an input image represented as a floating-point array and a Gaussian kernel, the program should compute the convolution of the image with the kernel. All inputs and outputs are stored in row-major order.
The Gaussian blur is performed by convolving each pixel with a weighted average of its neighbors, where the weights are determined by the Gaussian kernel. For each output pixel at position (i, j), the value is calculated as: where and are the kernel height and width.
Implementation Requirements
- External libraries are not permitted
- The
solvefunction signature must remain unchanged - The final result must be stored in the
outputarray - Handle boundary conditions by using zero-padding (treat values outside the image boundary as zeros)
Example 1:
Input:
image (5, 5) = [
[1.0, 2.0, 3.0, 4.0, 5.0],
[6.0, 7.0, 8.0, 9.0, 10.0],
[11.0, 12.0, 13.0, 14.0, 15.0],
[16.0, 17.0, 18.0, 19.0, 20.0],
[21.0, 22.0, 23.0, 24.0, 25.0]
]
kernel (3, 3) = [
[0.0625, 0.125, 0.0625],
[0.125, 0.25, 0.125],
[0.0625, 0.125, 0.0625]
]
Output:
output (5, 5) = [
[1.6875, 2.75, 3.5, 4.25, 3.5625],
[4.75, 7.0, 8.0, 9.0, 7.25],
[8.5, 12.0, 13.0, 14.0, 11.0],
[12.25, 17.0, 18.0, 19.0, 14.75],
[11.0625, 15.25, 16.0, 16.75, 12.9375]
]
Example 2:
Input:
image (3, 3) = [
[10.0, 20.0, 30.0],
[40.0, 50.0, 60.0],
[70.0, 80.0, 90.0]
]
kernel (3, 3) = [
[0.1, 0.1, 0.1],
[0.1, 0.2, 0.1],
[0.1, 0.1, 0.1]
]
Output:
output (3, 3) = [
[13.0, 23.0, 19.0],
[31.0, 50.0, 39.0],
[31.0, 47.0, 37.0]
]
Constraints
- 1 ≤
input_rows,input_cols≤ 4096 - 3 ≤
kernel_rows,kernel_cols≤ 21 - Both
kernel_rowsandkernel_colswill be odd numbers - All kernel values will be non-negative and sum to 1.0 (normalized)
- Performance is measured with
input_cols= 512,input_rows= 512,kernel_cols= 7,kernel_rows= 7
Starter code (CUDA)
#include <cuda_runtime.h>
// input, kernel, output are device pointers
extern "C" void solve(const float* input, const float* kernel, float* output, int input_rows,
int input_cols, int kernel_rows, int kernel_cols) {}
From LeetGPU, CC BY-NC-ND 4.0.