Search code examples
glslwebglshaderfragment-shader

OpenGL: Convert RGBA to Float


I have encoded floats into a texture (4 bytes of a float32 are stored as RBGA values). Now I need to decode them back into a single float.

Here's what I've tried so far and what didn't work for me:

    float rgbaToFloat(vec4 rgba) {
      uint r = uint(rgba.x*255.);
      uint g = uint(rgba.y*255.);
      uint b = uint(rgba.z*255.);
      uint a = uint(rgba.w*255.);

      return uintBitsToFloat((r << 24) | (g << 16) | (b << 8) | a);
    }

I pack floats into a texture image using the following snippet (python):

import numpy as np

data_flat = [...]  #floats

dim = int(np.sqrt(len(data_flat))) + 1
image = np.zeros((dim, dim, 4), dtype='uint8')
for i, d in enumerate(data_flat):
    image[i // dim, i % dim] = np.array([d], dtype=np.float32).view(np.uint8)

For a single floating-point value, it produces the following output:

d = 0.06797099858522415;
np.array([d], dtype=np.float32).view(np.uint8)
>>> array([ 97,  52, 139,  61], dtype=uint8)

Which seems to be correct, as binary representations match.

It seems to return overflowed values, hard to say, with the only debug way being comparing pictures, but it's certainly not what I expect it to output.


Solution

  • Thanks to @LJᛃ for referring me to this answer, it works like charm.