In this post, we will implement a simple yet efficient algorithm for an image blur filter using WebGL/OpenGL. The GLSL shader code presented here applies average (or box) smoothing through GPU parallel processing.
While this filter is one of the easiest to understand and implement, it remains a valuable choice for various computer science tasks due to its effectiveness and speed.
Interactive Preview of the Gaussian Blur Tool
Image Blur Source Code
This example implementation of the average blur filter utilizes a 3×3 pixel window to calculate the blur effect. By averaging the color values of the surrounding pixels within this window, the algorithm effectively smooths out the image, creating a softening effect that reduces sharpness and noise.
precision mediump float;
// our texture
uniform sampler2D u_image;
uniform vec2 u_textureSize;
void main() {
vec2 textCoord = gl_FragCoord.xy / u_textureSize;
vec2 onePixel = vec2(1.0, 1.0) / u_textureSize;
gl_FragColor = (
texture2D(u_image, textCoord + onePixel*vec2(-1.0, -1.0)) +
texture2D(u_image, textCoord + onePixel*vec2(0.0, -1.0)) +
texture2D(u_image, textCoord + onePixel*vec2(1.0, -1.0)) +
texture2D(u_image, textCoord + onePixel*vec2(-1.0, 0.0)) +
texture2D(u_image, textCoord + onePixel*vec2(0.0, 0.0)) +
texture2D(u_image, textCoord + onePixel*vec2(1.0, 0.0)) +
texture2D(u_image, textCoord + onePixel*vec2(-1.0, 1.0)) +
texture2D(u_image, textCoord + onePixel*vec2(0.0, 1.0)) +
texture2D(u_image, textCoord + onePixel*vec2(1.0, 1.0))) / 9.0;
}
The filter can execute several times to provide a better blur effect as described in the mean filter lesson.
Conclusion
In this article, we presented a simple shader code that can be utilized with WebGL and/or OpenGL for GPU computing. This implementation showcases a classic photo filter algorithm, which has many variants for both GPU and CPU applications. While our implementation works well with a 3×3 kernel size, those seeking a stronger blur effect may consider alternative methods, such as the moving average or Gaussian blur filters.
Bonus Tip
If you’re looking for a vanilla JavaScript solution, check out our implementation of Gaussian blur in pure JavaScript.