Free Online Image Tools

Edit photos directly in your web browser!

online-image-apps-at-fiveko
Home » Blog » Tutorials » Fast image blur filter with OpenGL/WebGL

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
TAGS:

Spectrum Audio Editor (Free!)

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

Sound CMD - Free Online Audio Editor

Fiveko Blog ↗

Discover articles and algorithms for image processing, programming, computer graphics, and more

Image Tools ↗

Free to use online image tools that run in a web browser. Apply photo effects to JPG, PNG, WebP and so on

Projects ↗

Small software projects and applications for various tasks: Graphics, Audio processing and others