0

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

Startec
  • 12,496
  • 23
  • 93
  • 160

2 Answers2

1

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
Raiyan
  • 1,589
  • 1
  • 14
  • 28
  • This seems very very close, however, I am not sure my math is correct: For instance, when I try your result with the following: `c = 8912743 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) colour = int((R*127 * 65536) + (G*127 * 256) + B*127) print(colour)` The same value is not returned (it is however very close). similarly, the RGB values seem to be between something other than 0 - 1 (between 1 and three perhaps?) – Startec Sep 24 '14 at 06:09
  • @Startec with the information you've given `8912743` should be an invalid color, the only way to produce it is with `G=2.0079`. – Mark Ransom Sep 24 '14 at 11:31
1

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.

Spektre
  • 49,595
  • 11
  • 110
  • 380