Shader 高斯模糊(Gaussion Blur)

本文介绍了在Shader中实现高斯模糊的方法,通过详细解释高斯模糊的算法原理,展示了如何通过增大网格尺寸或像素间距增强模糊效果。同时,讨论了性能优化策略,将二维遍历拆分为两个一维向量,降低纹理采样次数,提升渲染效率。此外,还提到了通过多次应用模糊函数来加深模糊效果的可能性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

高斯模糊的算法可以看阮一峰写的这篇文章,高斯模糊之所以叫高斯模糊,是因为它运用了高斯的正态分布的密度函数:

一维形式:

二维形式:

相关计算步骤:

我们在 shader 中还原一个拼多多版简易版的高斯模糊算法:

void main() {
    vec2 st = gl_FragCoord / iResulution;

    vec4 color = vec4(0.0);
    const int coreSize = 3;         // 取 3x3 像素网格
    vec2 texelOffset = vec2(1.)/vec2(375., 667.);  // 每个素纹的间距

    float kernel[9];                // 卷积核,每个像素点的权重
    kernel[0] = 1.; kernel[1] = 2.; kernel[2] = 1.;
    kernel[3] = 2.; kernel[4] = 4.; kernel[5] = 2.;
    kernel[6] = 1.; kernel[7] = 2.; kernel[8] = 1.;

    int index = 0;
    for(int y=0; y<coreSize; y++)
    {
        for(int x = 0; x<coreSize; x++)
        {
            // 这是核心,依次取9个像素点的色值
            vec4 currentColor = texture2D(inputImageTexture, st + vec2(float(-1+x)*texelOffset.x, float(-1+y)*texelOffset.y));

            // 将颜色值和权重相乘,就是卷积运算
            if (index == 0) { color += currentColor * kernel[0]; }
            else if (index == 1) { color += currentColor * kernel[1]; }
            else if (index == 2) { color += currentColor * kernel[2]; }
            else if (index == 3) { color += currentColor * kernel[3]; }
            else if (index == 4) { color += currentColor * kernel[4]; }
            else if (index == 5) { color += currentColor * kernel[5]; }
            else if (index == 6) { color += currentColor * kernel[6]; }
            else if (index == 7) { color += currentColor * kernel[7]; }
            else if (index == 8) { color += currentColor * kernel[8]; }

            index++;
        }
    }
    
    // 除以权重总和
    color /= 16.0;
    gl_FragColor=color;
}
复制代码

效果不明显,因为我们的权重没有很准确

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值