Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RGB Int to RGB - Python

Tags:

How can I convert an RGB integer to the corresponding RGB tuple (R,G,B)? Seems simple enough, but I can't find anything on google.

I know that for every RGB (r,g,b) you have the integer n = r256^2 + g256 + b, how can I solve the reverse in Python, IE given an n, I need the r,g,b values.

like image 891
Omar Avatar asked Feb 14 '10 17:02

Omar


People also ask

Why do we convert BGR to RGB?

Converting a BGR image to RGB and vice versa can have several reasons, one of them being that several image processing libraries have different pixel orderings.

How do you calculate RGB int?

So far I use the following to get the RGB values from it: // rgbs is an array of integers, every single integer represents the // RGB values combined in some way int r = (int) ((Math. pow(256,3) + rgbs[k]) / 65536); int g = (int) (((Math. pow(256,3) + rgbs[k]) / 256 ) % 256 ); int b = (int) ((Math.

What is RGB in Python?

In the most common color space, RGB (Red Green Blue), colors are represented in terms of their red, green, and blue components. In more technical terms, RGB describes a color as a tuple of three components.


2 Answers

I'm not a Python expert by all means, but as far as I know it has the same operators as C.

If so this should work and it should also be a lot quicker than using modulo and division.

Blue =  RGBint & 255 Green = (RGBint >> 8) & 255 Red =   (RGBint >> 16) & 255 

What it does it to mask out the lowest byte in each case (the binary and with 255.. Equals to a 8 one bits). For the green and red component it does the same, but shifts the color-channel into the lowest byte first.

like image 113
Nils Pipenbrinck Avatar answered Oct 16 '22 14:10

Nils Pipenbrinck


From a RGB integer:

Blue =  RGBint mod 256 Green = RGBint / 256 mod 256 Red =   RGBint / 256 / 256 mod 256 

This can be pretty simply implemented once you know how to get it. :)

Upd: Added python function. Not sure if there's a better way to do it, but this works on Python 3 and 2.4

def rgb_int2tuple(rgbint):     return (rgbint // 256 // 256 % 256, rgbint // 256 % 256, rgbint % 256) 

There's also an excellent solution that uses bitshifting and masking that's no doubt much faster that Nils Pipenbrinck posted.

like image 40
Xorlev Avatar answered Oct 16 '22 14:10

Xorlev