v9.1.1
Menu

Box Blur

easyFREELinear FilteringImage ProcessingCV: Image Processing

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:

  1. Define the kernel size and compute the kernel elements as 1/(kernel_size2)1 / (kernel\_size^2).
  2. Slide the kernel over the image, computing the average of neighboring pixels at each position.
  3. Assign the computed average to the corresponding pixel in the output image.
K=1kernel_size2(11...111...1............11...1)K = \frac{1}{kernel\_size^2}\begin{pmatrix} 1 & 1 &... & 1 \\ 1 & 1 &... & 1 \\... &... &... &... \\ 1 & 1 &... & 1 \end{pmatrix}

This technique is widely used in image processing applications to reduce noise.

Example

Input
image = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
kernel_size = 3
Output
[[1, 2, 2], [3, 5, 4], [3, 4, 3]]
Reasoning
  • Inputs: image is a 3×33 \times 3 grayscale grid with values 1 to 9, and kernel_size k=3k = 3, so every kernel weight is 1k2=19\frac{1}{k^2} = \frac{1}{9}.
  • The math: each output pixel is 19\frac{1}{9} times the sum of the 3×33 \times 3 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, 1+2+⋯+99=459=5\frac{1+2+\dots+9}{9} = \frac{45}{9} = 5.
  • Top-left corner (value 1): only 1,2,4,51, 2, 4, 5 are inside, so 129≈1.33→1\frac{12}{9} \approx 1.33 \to 1. Top-middle (value 2): the top two rows count, 219≈2.33→2\frac{21}{9} \approx 2.33 \to 2. Right-middle (value 6): 2+3+5+6+8+99=339≈3.67→4\frac{2+3+5+6+8+9}{9} = \frac{33}{9} \approx 3.67 \to 4.
  • Output: the remaining sums are 16,27,24,39,2816, 27, 24, 39, 28, giving 1.78,3,2.67,4.33,3.111.78, 3, 2.67, 4.33, 3.11, which round to [[1, 2, 2], [3, 5, 4], [3, 4, 3]], the same 3×33 \times 3 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

More from CV: Image Processing

solution.py

Test results

Sign in to run your code against the test cases.