Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Integers to RGB values and back with Python

I have two functions, one to return RGB values from a given Integer, and the other function does the reverse, providing it with RGB values it returns an Integer. I'm testing this by seeing if the integer i convert to RGB turns back from RGB into the original integer value, but I'm getting different values.

def getRGBfromI(RGBint):
    blue =  RGBint & 255
    green = (RGBint >> 8) & 255
    red =   (RGBint >> 16) & 255
    return red, green, blue

def getIfromRGB(rgb):
    red = rgb[0]
    green = rgb[1]
    blue = rgb[2]
    print red, green, blue
    RGBint = (red<<16) + (green<<8) + blue
    return RGBint

the test:

i1 = 2147483647
colr1 = getRGBfromI(i1)
print colr1 # returns (255,255,255)

i2 =getIfromRGB(colr1)

print i1, i2 # returns 2147483647 16777215

To me it seems like the getRGBfromI() is correct and the getIfromRGB() is incorrect, but I may be wrong about that too.

like image 533
M_PF Avatar asked Oct 14 '15 11:10

M_PF


People also ask

How do I convert color to RGB in Python?

to_rgb() function is used convert c (ie, color) to an RGB color. It converts the color name into a array of RGB encoded colors. It returns an RGB tuple of three floats from 0-1.

Are RGB values integers?

RGB color space or RGB color system, constructs all the colors from the combination of the Red, Green and Blue colors. The red, green and blue use 8 bits each, which have integer values from 0 to 255.

Can we convert integer to list in Python?

Use map() to convert an integer to a list. Call str(x) on an integer x to convert it to a string. Use map(function, iterable) with the string from the previous step as iterable and int as function to apply the function int() on each digit in the string.

Why do RGB values go from 0 to 255?

In RGB, a color is defined as a mixture of pure red, green, and blue lights of various strengths. Each of the red, green and blue light levels is encoded as a number in the range 0.. 255, with 0 meaning zero light and 255 meaning maximum light.


1 Answers

Both functions seem to be working fine.

The max value expressed by a 24 bit integer (forget the sign for now) is

mx = pow(2,24)-1 # i.e. 16777215

So

i1 = 2147483647

is higher than mx and

colr1 = getRGBfromI(i1)

correctly gives

(255, 255, 255)  # better to view it in hex as 0xFFFFFF

since it cuts out the bits higher than 24 (0xFFFFFF occupies bits from 0 to 23)

Viceversa,

i2 = getIfromRGB(colr1)

correctly gives

16777215

which is the max value you can represent with 24 bits (i.e. the mx above).

If you pour 1.4 litres of water in a 1L bottle, some water will be lost in the overflow. When you empty the bottle, you will find 1L at max

like image 88
Pynchia Avatar answered Sep 20 '22 15:09

Pynchia