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 1/(kernel_size2).
- 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[[5.0]]
Box blur (mean filter) averages all pixels in a neighborhood.
For a 3×3 box filter on a 3×3 image:
output[i,j]=k21∑m,ninput[i+m,j+n]
-
Valid convolution produces 1×1 output:
- Output size: (3−3+1)×(3−3+1)=1×1
-
Calculate the average of all 9 pixels: mean=91+2+3+4+5+6+7+8+9
-
Sum the values: sum=1+2+3+4+5+6+7+8+9=45
-
Compute mean: mean=945=5.0
-
Result: [[5.0]]
The box blur smooths the image by replacing each pixel with the average of its neighborhood.
Constraints:
- kernel_size is odd (3, 5, 7, etc.)
- Round output to nearest integer
- Use zero-padding