Fast image blur filter with OpenGL/WebGL

In this post, we implement a simple but fast algorithm for image blur filter with WebGL / OpenGL. The GL shader code in this article implements the average or box smoothing using GPU parallel processing.

This filter is one of the easiest to understand and apply, but despite this fact it is a good choice in many computer science tasks.

Image blur source code

This example implementation of average blur uses a 3 by 3 pixel window.

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 show a simple shader code that we can use with WebGL and/or OpenGL for GPU computing. This is a classic photo filter algorithm and there are many variants of it for both GPU and CPU. Our implementation works well for 3 by 3 kernel sizes, but for stronger effect one may use other variants such as: moving average or Gaussian blur filter.

Bonus Tip

In case you are looking for a vanilla JS solution, then you can view our Gaussian blur in pure Javascript.

How it works online

WEB APPLET

See how it works in the browser!

fivekogfx-mean-filter

Spectrum Audio Editor (Free!)

Effortless audio editing, made free. Edit sound like a pro with our online spectrum analyzer.

SoundCMD - Free Spectrum Audio Editor