简体   繁体   中英

How to Convert This RGB format in Python

I am reading values from something in Python. The values come in a strange format. The documentation says:

 Color is represented by a single value from 0 to 8355711. The RGB(r,g,b) function calculates ((R*127 x 2^16) + (G*127 x 2^8) + B*127), where R, G and B are values between 0.00 and 1.00 

Som, a red color has the value of 16712965 I would love to know how to 'unpack' those values as a tuple or something but am struggling with that math. If this is not possible, a way to convert that value to an rgb value somehow would be great. Please help! Thanks

Notice the 2^8 an 2^16 in the formula, this suggest that you can use something akin to right shift in C. Dividing the input number by 2^8=256 is equivalent to 8 bit right shift. Another point to note here is that your R,G,B output values are real numbers. So you would like to use the float function during your calculations.

c = 8355711
print 'input colour', c

# conversion to RGB format
B = float( c % 256 )/127.0
c = c / 256
G = float( c % 256)/127.0
c = c / 256
R = float( c % 256)/127.0

print R, G, B

# reverse calculation for verifying the result
colour = int((R*127 * 65536) + (G*127 * 256) + B*127)
print colour

you have mistake in text

  • Red=16712965=0xFF0505h
  • is out of range of your claimed limit 8355711=7F7F7Fh

So what exactly is your source and destination color format ???

  • the most common is 8bit per R,G,B channel packed into 32 bit value
  • yours looks like 8bit per channel (7bit used) packed into ?? bit value

What exactly you want ?

  • double R,G,B values in range <0.0,1.0> from int col?
  • not a python coder in C++ it looks like this:

     // 8(7 used) bit per channel double R=double(col>>16)/127.0; double G=double(col>> 8)/127.0; double B=double(col )/127.0; // 8 bit per channel double R=double(col>>16)/255.0; double G=double(col>> 8)/255.0; double B=double(col )/255.0; 
  • x>>n means arithmetic bit shift right (padding zeros to MSB bit) of value x by n bits

  • it is the same as x/(2^n)

If you want different conversions then you must specify it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM