Rgb Int to Rgb - Python

RGB Int to RGB - Python

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.

convert Integers to RGB values and back with Python

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

Convert RGB to class / single integer value

You can convert three 8 bit integers into a 32bit integer and easily recover the three integer back. The idea is to use bitwise operations, this way each 8 bit represents one of the rgb colors. This way you already know the N = 16777215 (including zero) = 256**3.

The following code can do this:

def rgbtoint32(rgb):
color = 0
for c in rgb[::-1]:
color = (color<<8) + c
# Do not forget parenthesis.
# color<< 8 + c is equivalent of color << (8+c)
return color

def int32torgb(color):
rgb = []
for i in range(3):
rgb.append(color&0xff)
color = color >> 8
return rgb

rgb = [32,253,200]
color = rgbtoint32(rgb)
rgb_c = int32torgb(color)

print(rgb)
print(color)
print(rgb_c)

This gives:

[32, 253, 200]
13172000
[32, 253, 200]

Update:
Using "view" from numpy, as denoted below by "Mad Physicist
", one can efficiently do the above process as

rgb = np.array([[[32,253,200], [210,25,42]]],dtype = np.uint8)
size_d = list(rgb.shape)
size_d[2] = -1

# Converting to 2D int32 array
colorint32 = np.dstack((rgb,np.zeros(rgb.shape[:2], 'uint8'))).view('uint32').squeeze(-1)

# Converting back from the int32 array to RGB space
rgb_c = colorint32.view('uint8').reshape(size_d)[:,:,:3]

# Print results
print(rgb)
print(colorint32)
print(rgb_c)

Which gives

[[[ 32 253 200]
[210 25 42]]]
[[13172000 2759122]]
[[[ 32 253 200]
[210 25 42]]]

How to convert RGB percentage to RGB values?

You cannot get exactly the same values, because you round numbers. 100 and 255 are not multiples. Your percentage RGB seems to be all integer, so you lost at minimum 1 bit of information (and possibly also 2 bits). So you cannot expect exact values on all cases. (You cannot map 100 numbers into 256 values, and get all 256 values).

But the good: you do not need it (usually). Your eyes are not so sensible (and we cannot see all combination of RGB with 256x256x256 values: our eyes can distinguish a lot less colours, so on some case you will see no differences, and on some, it is just barely noticeable). In addition some monitor panel trick displaying only 64 different shades per channel (and few people notice it). Consider that if you took data from a JPEG image, you get an additional conversion (data are not stored as RGB data, but as YCC).

To get the best choice, you need to know the original algorithm (do they round or trunc? or you should have a larger example test, and check the differences between different algorithms (e.g. how many cases are precise, how many are just 1 off, 2 off, 3 off).

Note: you have 3 possibilities: round(), math.floor(), and math.ceil(). I would avoid using int: according Python documentation, it seems the result depend on the system standard library (it could be truncated, or rounded). Note: math.trunc() and math.floor() gives the same results for positive (or zero) numbers.

In general, I would prefer round: it gives expected results for 0% and 100% (ceil is similar for these extreme values).

PS: there is not "correct RGB values". Historically RGB were given as numbers from 0 to 100 (and possibly as floating point number), or from 0.0 to 1.0. Just HTML pushed for 0 to 255, but it causes problems if you have a screens which can display more colours. And probably for RGB you mean R*G*B*, so not a linear RGB, but a OETF corrected RGB).

And no: there is not reputable sources. Nobody follows standards, so do not expect people which converted the colour channel (e.g. to 99%) are using exact the same method (we programmers are lazy). And standards tend to uses floating points. Note: internally a program may use floating point numbers, so in a colour picker you may get different colours with same displayed %-values, depending on how you input the colour. Or do you refer to a specific standard which specifies %-values? We cannot agree if black is 0,0,0 or 16,16,16 (e.g. MPEG-2, or TVs, and other limited range RGB devices), or how do do or interpret the gamma correction (ok: recent and less-recent standards are more precise, but most programs didn't get it). Also when reading your "RGB" values, in past I would assume it would be sRGB (so colour space of web and Microsoft), but since few years Apple use a different colour space (Apple P3), and other are following extending sRGB. Chaos. So just test different methods (and use your eyes to check quality).

How to map a range of numbers to RGB in Python

You could convert this answer from the post you linked into python:

import math

def num_to_rgb(val, max_val=3):
i = (val * 255 / max_val);
r = round(math.sin(0.024 * i + 0) * 127 + 128);
g = round(math.sin(0.024 * i + 2) * 127 + 128);
b = round(math.sin(0.024 * i + 4) * 127 + 128);
return (r,g,b)

print(num_to_rgb(1.32))
>> (183, 1, 179)

this will return a tuple of three integers (r,g,b).

It is also a good idea to to make sure invalid inputs aren't allowed (aka negatives, or val > max_val):

def num_to_rgb(val, max_val=3):
if (val > max_val):
raise ValueError("val must not be greater than max_val")
if (val < 0 or max_val < 0):
raise ValueError("arguments may not be negative")

i = (val * 255 / max_val);
r = round(math.sin(0.024 * i + 0) * 127 + 128);
g = round(math.sin(0.024 * i + 2) * 127 + 128);
b = round(math.sin(0.024 * i + 4) * 127 + 128);
return (r,g,b)

print(num_to_rgb(4.32))
>> ValueError: val must not be greater than max_val

Converting Hex to RGB value in Python

I believe that this does what you are looking for:

h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))

(The above was written for Python 3)

Sample run:

Enter hex: #B4FBB8
RGB = (180, 251, 184)

Writing to a file

To write to a file with handle fhandle while preserving the formatting:

fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) ))

how to convert rgb value to a integer number based on a map in python

Do you need a specific mapping otherwise you could try a direct mapping.

ann = Image.open(img_rgb)
ann = np.asarray(ann)
# define newann as:
newoann = ann[:, :, 0] + ann[:, :, 1] * 256 + ann[:, :, 2] * 256**2
# Then do the mapping

This will lead to a unique index for every RGB Value.

Converting an RGB color tuple to a hexidecimal string

Use the format operator %:

>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'

Note that it won't check bounds...

>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'

Convert RGB values to Integer

I think the code is something like:

int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;

Also, I believe you can get the individual values using:

int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;


Related Topics



Leave a reply



Submit