Convert Rgb Values to Integer

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;

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 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.

Convert integer color value to RGB

Use this

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

We know lenght of color value in HEX is 6. So you see 6 here. %06X matches the result coming from (0xFFFFFF & intColor) and if length is less than 6, it makes result with 6 by appending ZERO to left side of result. And you see #, so this # char gets appended to result and finally you get a HEX COLOR value.


Update since API 26

Since API 26, new methods Color.valueOf(....) has been introduced to convert colors for similar reason. you can use it like

// sRGB
Color opaqueRed = Color.valueOf(0xffff0000); // from a color int
Color translucentRed = Color.valueOf(1.0f, 0.0f, 0.0f, 0.5f);

// Wide gamut color
ColorSpace sRgb = ColorSpace.get(ColorSpace.Named.SRGB);
@ColorLong long p3 = Color.pack(1.0f, 1.0f, 0.0f, 1.0f, sRgb);
Color opaqueYellow = Color.valueOf(p3); // from a color long

// CIE L*a*b* color space
ColorSpace lab = ColorSpace.get(Named.CIE_LAB);
Color green = Color.valueOf(100.0f, -128.0f, 128.0f, 1.0f, lab);

mView.setBackgroundColor(opaqueRed.toArgb());
mView2.setBackgroundColor(green.toArgb());
mView3.setBackgroundColor(translucentRed.toArgb());
mView4.setBackgroundColor(opaqueYellow.toArgb());

Convert RGB values to binary to decimal

You need the conversion from double because you cannot store the double value into 8 bit.

Your double values are between 0.0 and 1.0. You can see them as the proportion of color used (e.g. 0.33333333 in yellow means that one-third of the possible yellow is used). As you can see such a double can have many decimal places, which means we need a lot of memory (64-bit) to store such a color.

Your function now tries to store the double value into only 8 bit (256 values). As we said the double value can be seen as a portion (between 0 and 1) and the function calculates the same for 8 bit (between 0 and 255). This can simply be done by multiplying the double value with 255. For the example with yellow (0.33333333 of yellow is used) it is: 0.33333333 * 255 = 84,99999915. The meaning is still the same 84,99999915 yellow parts of 255 yellow parts are used, which is still a third.
In order to get a compressed version of this number, it is rounded to the next integer value. In our example, this is 85, which is really close to the actual portion, but we save a lot of memory.

It makes also sense for the lowest double value 0.0, which is converted to the lowest int value 0. The highest double value 1.0 is converted to 255 (highest 8-bit number).

In conclusion, we convert a double (64-bit) into an only 8-bit number, which has the same proportion of the color, but it is not as accurate.

Edit: As there is also a confusion with the 255: 8 bit can store 256 values (0 to 255). If you can choose 256 as a color value somewhere they use the range 1-256 without 0. Essentially it is the same one shifted by 1.

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

Converting RGB value into integers

Using regular expressions:
I used "[A=255, R=241, G=24, B=2]" as a test string and split it into four integers.

Dim a as Integer, r as Integer, g as Integer, b as Integer
Dim s as String = "[A=255, R=241, G=24, B=2]"
Dim mc as MatchCollection = System.Text.RegularExpressions.Regex.Matches( s, "(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+", RegexOptions.None )
Integer.TryParse( mc(0).Groups(1).Value, a )
Integer.TryParse( mc(0).Groups(2).Value, r )
Integer.TryParse( mc(0).Groups(3).Value, g )
Integer.TryParse( mc(0).Groups(4).Value, b )

NOTE: it will have no problems with numbers being 1, 2, or any number of digits long.



Related Topics



Leave a reply



Submit