在 OpenGLES 着色器中使用 LUT 进行伪着色

Using LUT in OpenGLES shader for false coloring

我正在尝试使用片段着色器将灰度图像转换为彩色输出。这个想法相当简单;制作三个长度为 256 的数组并将灰度值 [0,255] 映射到 RGB (3 * [0,255])。下面是我写的代码:

#extension GL_OES_EGL_image_external : require
precision mediump float;
varying vec2 vTextureCoord;
uniform samplerExternalOES sTexture;

const int red[256] = int[256](255, 128, 240, ... , 143); // declaring as const/non-const changes the output
const int green[256] = int[256](230, 120, 34, ... , 100);
const int blue[256] = int[256](90, 73, 99, ... , 42);

void main (void) {
    float r, g, b, y;
    y = texture2D(sTexture, vTextureCoord).r; // using only the r value from YUV received
    y = y * 255.0; // convert y from [0,1] to [0,255]

    int index = int(y); // use y as an index to map value to the lookup arrays

    r = float(red[index]) / 255.0;
    g = float(green[index]) / 255.0;
    b = float(blue[index]) / 255.0;

    // Set the RGB color of our pixel
    gl_FragColor = vec4(r, g, b, 1.0); 
    // here, if I were to instead assign gl_FragColor = vec4(y,y,y, 1.0); I'd see the expected greyscale output
}

我是 OpenGL 的新手,但我已经能够使用简单的方程式并获得假色输出,其代码如下所示:

y = y * 255;
r = y * 0.47446 + 0.65658;
g = y * 0.16213 + 0.58145;
b = y * 0.047524+ 0.75203;
gl_FragColor = vec4(r / 255.0, g / 255.0, b / 255.0, 1.0); 

然而,使用 LUT 的输出相当奇怪。将 int 数组声明为 const 仅给出第 0 个索引和第 255 个索引的输出;中间没有颜色。如果没有 const,代码会因 SIGSEGV 而崩溃。

有没有其他人尝试过这个/知道我在 LUT 代码中可能做错了什么?

我不确定为什么这不起作用,但更传统的方法是将 LUT 存储为 256x1 纹理,然后只进行纹理查找。

void main (void) {
    float luminance = texture2D(inputTexture, vTextureCoord).r;
    gl_FragColor = texture2D(lutTexture, vec2(luminance, 0.5));
}

...可能会更快、更灵活。