Bluring only the alpha channel with a shader

#1

I’d like to blur only the alpha channel of an image.

I start a project based on the example 09_gaussianBlurFilter and change the shader code this way for the fragment shader :

#version 120

uniform sampler2DRect tex0;

uniform float blurAmnt;

varying vec2 texCoordVarying;

// Gaussian weights from http://dev.theomader.com/gaussian-kernel-calculator/

void main()
{
vec3 color ;
color = texture(tex0, texCoordVarying).rgb;

float alpha = 0.0;
alpha += 0.000229 * texture(tex0, texCoordVarying + vec2(blurAmnt * -4.0, 0.0)).a;
alpha += 0.005977 * texture(tex0, texCoordVarying + vec2(blurAmnt * -3.0, 0.0)).a;
alpha += 0.060598 * texture(tex0, texCoordVarying + vec2(blurAmnt * -2.0, 0.0)).a;
alpha += 0.241732 * texture(tex0, texCoordVarying + vec2(blurAmnt * -1.0, 0.0)).a;

alpha += 0.382928 * texture(tex0, texCoordVarying + vec2(0.0, 0)).a;

alpha += 0.241732 * texture(tex0, texCoordVarying + vec2(blurAmnt * 1.0, 0.0)).a;
alpha += 0.060598 * texture(tex0, texCoordVarying + vec2(blurAmnt * 2.0, 0.0)).a;
alpha += 0.005977 * texture(tex0, texCoordVarying + vec2(blurAmnt * 3.0, 0.0)).a;
alpha += 0.000229 * texture(tex0, texCoordVarying + vec2(blurAmnt * 4.0, 0.0)).a;

   gl_FragColor.a = alpha;
gl_FragColor.rgb = color;

} 

I change the the other shader the same way and add this blending in the draw function

     glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	float blur = ofMap(mouseX, 0, ofGetWidth(), 0, 40, true);

	//----------------------------------------------------------
	fboBlurOnePass.begin();
	ofClear(0.0, 0.0, 0.0, 0.0);
	shaderBlurX.begin();
	shaderBlurX.setUniform1f("blurAmnt", blur);

	Test.draw(0, 0, g_Width, g_Height);

	shaderBlurX.end();

	fboBlurOnePass.end();

	//----------------------------------------------------------
	fboBlurTwoPass.begin();
	ofClear(0.0, 0.0, 0.0, 0.0);
	shaderBlurY.begin();
	shaderBlurY.setUniform1f("blurAmnt", blur);

	fboBlurOnePass.draw(0, 0);

	shaderBlurY.end();

	fboBlurTwoPass.end();

	//----------------------------------------------------------
	ofSetColor(ofColor::white);
	fboBlurTwoPass.draw(0, 0);


glDisable(GL_BLEND);

The result is :

  • My image is drawn with its alpha channel
  • there is no blur effect on the alpha channel
  • actually my shader don’t care about the alpha channel (if I set it to 0.0 in the shader it changes nothing).

Is there a trick to make the shader use the alpha channel in the texture ?

#2

I reply to myself :

You can’t manipulate alpha with only one texture in a shader. You need a minimum of 2.