Box Blur
Implement a box blur, also known as a mean filter, to an image by averaging neighboring pixels. This technique is a fundamental concept in Linear Filtering for image processing.
The box blur operates by convolving an image with a kernel, a small matrix that slides over the entire image, computing a weighted average of neighboring pixels at each position. For a given kernel size, the kernel is typically a square matrix with all elements being equal, resulting in a uniform average of the neighboring pixels.
Here are the steps to apply the box blur:
- Define the kernel size and compute the kernel elements as .
- Slide the kernel over the image, computing the average of neighboring pixels at each position.
- Assign the computed average to the corresponding pixel in the output image.
This technique is widely used in image processing applications to reduce noise.
Example
image = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
kernel_size = 3[[1, 2, 2], [3, 5, 4], [3, 4, 3]]
- Inputs:
imageis a grayscale grid with values 1 to 9, andkernel_size, so every kernel weight is . - The math: each output pixel is times the sum of the neighbourhood centred on it. Neighbours that fall outside the image are zeros, but the divisor stays 9.
- Centre pixel (value 5): all nine pixels are inside, .
- Top-left corner (value 1): only are inside, so . Top-middle (value 2): the top two rows count, . Right-middle (value 6): .
- Output: the remaining sums are , giving , which round to
[[1, 2, 2], [3, 5, 4], [3, 4, 3]], the same size as the input. - Notice the border pixels come out darker than the original: the zero padding contributes nothing to the sum but still counts in the divisor.
Constraints
- kernel_size is odd (3, 5, 7, etc.)
- Round output to nearest integer
- Use zero-padding