跳到主要内容
← Image Manipulation with Shaders

Image Manipulation with Shaders

Bilateral Filter

shader-learning 自学第 15 课:Bilateral Filter

实时渲染 · 纹理 GLSL

第 15 课:Bilateral Filter

我的解

uniform vec2 iResolution;
uniform sampler2D iChannel0;
uniform vec2 iChannelSize0;

int   RADIUS  = 10;
float SIGMA_S = 4.0; // larger values - smoother result
float SIGMA_I = 0.1; // smaller values - sharper edges
float PI = 3.14;

float gaussian(float deltaSquare, float sigma) {
   return exp(-deltaSquare / (2.0 * sigma * sigma));
}

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  vec2 texelSize = vec2(1.0) / iChannelSize0;
  vec3 centerColor = texture(iChannel0, uv).rgb;


  float SumOfWeight = 0.0;
  vec3 result = vec3(0.0);
  for (int dx = -RADIUS; dx <= RADIUS; dx++) {
    for (int dy = -RADIUS; dy <= RADIUS; dy++) {
      vec2 offset = vec2(dx, dy);
      vec2 sampleUV = uv + offset * texelSize;
      vec3 sampleColor = texture(iChannel0, sampleUV).rgb;

      float SpatialWeight = gaussian(pow(offset.x, 2.0) + pow(offset.y, 2.0), SIGMA_S);
      float ColorWeight = gaussian(pow(distance(centerColor,sampleColor), 2.0), SIGMA_I);
      SumOfWeight += SpatialWeight*ColorWeight;

      result += sampleColor * SpatialWeight * ColorWeight;
    }
  }


  float N = SumOfWeight;
  gl_FragColor = vec4(result / N, 1.0);
}