3

I have a series of float64's that represent rgb values, and I am trying to interpret this as an image using python. For each float64, bits 0-15 correspond to the data for an uint8 for the red value, bits 16-31 are for green, and 32-47 are for blue. How can I get these integer RGB values?

I know this kind of bit manipulation is very odd to be doing in python, but bear with me. Basically all I need is to interpret the underlying bits of a float as an int instead(not trying to cast). The closest thing I've found that allows me to access the bit values is python struct, but it doesn't seem to actually do what I want(and I'm sure it's very inefficient).

I've tried to accomplish it with the following code:

raw_byte_data = struct.pack('f', float_value)
data_as_int = struct.unpack('i', raw_byte_data)[0]
r = data_as_int & 0xFF
g = data_as_int >> 8 & 0xFF
b = data_as_int >> 16 & 0xFF

I'm not sure what this does, but whatever it does it doesn't give me the output bytes I want. Hopefully it illustrates what I'm trying to do at least.

3
  • 1
    What exactly is the source of your data? You could use struct to do this, but maybe numpy would be more wieldy. Commented Feb 7, 2022 at 18:52
  • 2
    Also, what you are asking doesn't make sense. uint8 are 8 bits, not 16. Do you mean uint16? Or am I missing something about the way images are represented? Commented Feb 7, 2022 at 18:54
  • 1
    So, you probably need something like r,g,b = struct.unpack_from('HHH', struct.pack('d', 3.14159)) where 'd' is for doubles (you want float64 not float32) and you want to unpack 3 unsigned longs (uint16) Commented Feb 7, 2022 at 18:58

1 Answer 1

0

After some more fiddling, I was able to get it to work using python struct thanks to this post. See below.

def float_to_rgb(f):
    s = struct.pack('>f', f)
    bits = struct.unpack('>l', s)[0]
    r = bits & 0xFF
    g = bits >> 8 & 0xFF
    b = bits >> 16 & 0xFF
    return (r,g,b)

I think the key here was unpacking the bytes as a long int('l').

Sign up to request clarification or add additional context in comments.

2 Comments

You said float64, not float32...
Is your image just a long one pixel height string ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.