如何添加垂直高斯模糊

时间:2019-07-18 08:11:24

标签: opengl glsl

这是我的片段着色器代码,在其中我将高斯模糊应用于Texture2D图像。

vec3 incrementalGaussian;
incrementalGaussian.x = 1.0f / (sqrt(2.0f * pi) * BlurValue  );
incrementalGaussian.y = exp(-0.5f / (BlurValue  * BlurValue ));
incrementalGaussian.z = incrementalGaussian.y * incrementalGaussian.y;
 vec4 avgValue = vec4(0.0f, 0.0f, 0.0f, 0.0f);
float coefficientSum = 0.0f;

// Take the central sample first...
avgValue += texture2D(text, TexCoords.st) * incrementalGaussian.x;
coefficientSum += incrementalGaussian.x;
incrementalGaussian.xy *= incrementalGaussian.yz;

//Go through the remaining 8 vertical samples (4 on each side of the center)

for (float i = 1.0f; i <= numBlurPixelsPerSide ; i++) { 
    avgValue += texture2D(text, TexCoords.st - i * 0.01f * 
               blurMultiplyVec) * incrementalGaussian.x;         
    avgValue += texture2D(text, TexCoords.st + i * 0.01f * 
                blurMultiplyVec) * incrementalGaussian.x;         
    coefficientSum += 2 * incrementalGaussian.x;
    incrementalGaussian.xy *= incrementalGaussian.yz;
avgValue.g = avgValue.r;
avgValue.b = avgValue.r;
color =  avgValue * vec4(textColor, 1.0)  / coefficientSum ;
}  

这仅适用于水平模糊,我如何还可以添加垂直高斯模糊。

1 个答案:

答案 0 :(得分:3)

对于高斯模糊,通常使用2次通过。对于垂直模糊,您必须添加第二遍。首先进行水平模糊,然后将垂直模糊应用于结果。

对于水平模糊,位移纹理坐标的u分量:

for (float i = 1.0f; i <= numBlurPixelsPerSide ; i++) { 
    float offset = i * 0.01f * blurMultiplyVec;
    avgValue += texture2D(text, TexCoords.st - vec2(offset, 0.0) * incrementalGaussian.x;
    avgValue += texture2D(text, TexCoords.st + vec2(offset, 0.0) * incrementalGaussian.x;
    // ...
}

对于垂直模糊,将移动纹理坐标的v分量:

for (float i = 1.0f; i <= numBlurPixelsPerSide ; i++) { 
    float offset = i * 0.01f * blurMultiplyVec;
    avgValue += texture2D(text, TexCoords.st - vec2(0.0, offset) * incrementalGaussian.x;
    avgValue += texture2D(text, TexCoords.st + vec2(0.0, offset) * incrementalGaussian.x;
    // ...
}

一个相关的问题是What kind of blurs can be implemented in pixel shaders?
网络上有很多很好的教程,例如LearnOpenGL.com - Gaussian blur