Gaussian filter in OpenGL/WebGL

This sample source code below shows how to implement Gaussian blur filter in OpenGL (WebGL) shading language. The result of this algorithm is a blurry image with relatively good contour lines of objects.

Source Code

The GL shader code below implements a separable Gaussian convolution – once per rows and one per columns.

precision mediump float;

// our texture
uniform sampler2D u_image;

#define KERNEL_SIZE 15
uniform vec2 u_textureSize;
uniform int u_direction;
uniform float u_kernel[KERNEL_SIZE];
void main() {
	vec2 textCoord = gl_FragCoord.xy / u_textureSize;
	vec2 onePixel = ((u_direction == 0) ? vec2(1.0, 0.0) : vec2(0.0, 1.0)) / u_textureSize;
	vec4 meanColor = vec4(0);
	int ms = KERNEL_SIZE / 2;
	for (int i = 0; i < KERNEL_SIZE; i++)
	{
		meanColor += texture2D(u_image, textCoord  + onePixel*vec2(i - ms))*u_kernel[i];
	}
	gl_FragColor = meanColor;
}

How it works?

As this is a separable GL implementation of a smooth filter, it will run twice – for horizontal and vertical image blur. This means that the Gaussian kernel for convolution is one dimensional.

The following steps briefly describe how the algorithm works:

Bonus Tip

In case you are looking for a pure Java Script solution then you may take a look at our Gaussian blur in plain JS.

Try it Online

You can explore the above algorithm in our free online image processing app.

Image blur effect with Gaussian filter

WEB APPLET

See how it works in the browser!


Related articles