Sunday, July 11, 2010

Convolution Pixel Shader

What is convolution ? Simply speaking convolution is weighted sum of pixel values around target pixel. If those weights are put into vector W and pixel values around x,y are put in vector P, then in linear algebra terms convolution at x,y is nothing more than dot product of vectors W,P. More precisely:Convolution(x,y) = (W*P)/denominator + offsetThis W vector is called kernel. (Also formula can be re-written for matrix case, in that case W and P would be matrix). So by using different kernels we could achieve different image convolution effects. Several common convolution kernels:

Gaussian Blur kernel

1., 2., 1.,2., 4., 2.,1., 2., 1.

Sharpness kernel

-1., -1., -1.,-1., 9., -1.,-1., -1., -1.

Edge detection kernel

-1./8., -1./8., -1./8.,-1./8., 1., -1./8.,-1./8., -1./8., -1./8.

Emboss kernel

2., 0., 0.,0., -1., 0.,0., 0., -1.

Now, GLSL pixel shader code which performs convolution with all these kernels =>