Box blur (image)
{
set newImage to image;
For x /*row*/, y/*column*/ on newImage do:
{
// Kernel would not fit!
If x < 1 or y < 1 or x + 1 == width or y + 1 == height then:
Continue;
// Set P to the average of 9 pixels:
X X X
X P X
X X X
// Calculate average.
Sum = image[x - 1, y + 1] + // Top left
image[x + 0, y + 1] + // Top center
image[x + 1, y + 1] + // Top right
image[x - 1, y + 0] + // Mid left
image[x + 0, y + 0] + // Current pixel
image[x + 1, y + 0] + // Mid right
image[x - 1, y - 1] + // Low left
image[x + 0, y - 1] + // Low center
image[x + 1, y - 1]; // Low right
newImage[x, y] = Sum / 9;
}
Return newImage;
}
The example does not handle the edges of the image, which would not fit inside the kernel, so that these areas remain unblurred. In practice, the issue is better handled by:
[3]
A number of optimizations can be applied when implementing the box blur of a radius r and N pixels:[6]