Fragment Shader - Average Luminosity

后端 未结 3 648
死守一世寂寞
死守一世寂寞 2020-12-11 05:50

Does any body know how to find average luminosity for a texture in a fragment shader? I have access to both RGB and YUV textures the Y component in YUV is an array and I wan

3条回答
  •  孤街浪徒
    2020-12-11 06:45

    I'm presenting a solution for the RGB texture here as I'm not sure mip map generation would work with a YUV texture.

    The first step is to create mipmaps for the texture, if not already present:

    glGenerateMipmapOES(GL_TEXTURE_2D);
    

    Now we can access the RGB value of the smallest mipmap level from the fragment shader by using the optional third argument of the sampler function texture2D, the "bias":

    vec4 color = texture2D(sampler, vec2(0.5, 0.5), 8.0);
    

    This will shift the mipmap level up eight levels, resulting in sampling a far smaller level.

    If you have a 256x256 texture and render it with a scale of 1, a bias of 8.0 will effectively reduce the picked mipmap to the smallest 1x1 level (256 / 2^8 == 1). Of course you have to adjust the bias for your conditions to sample the smallest level.

    OK, now we have the average RGB value of the whole image. The third step is to reduce RGB to a luminosity:

    float lum = dot(vec3(0.30, 0.59, 0.11), color.xyz);
    

    The dot product is just a fancy (and fast) way of calculating a weighted sum.

提交回复
热议问题