Gaussian filter in OpenGL/WebGL

This sample source code below shows how to make an OpenGL (WebGL) Gaussian blur filter.

Source Code

The 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;

The following steps briefly describe how it works:

The Fragment Shader code above is also part of our open source graphic library.

Related Sources

Demo App

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