Converting an Rgb Color Tuple to a Hexidecimal String

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 RGBA tuple to hex with matplotlib

You need to specify keep_alpha=True:

mpl.colors.rgb2hex((0.1, 0.1, 0.1, 0.1), keep_alpha=True)
# out: #1a1a1a1a
mpl.colors.rgb2hex((0.1, 0.1, 0.1, 0.8), keep_alpha=True)
# out: #1a1a1acc

Convert numpy array of RGB values to hex using format operator %

You can use the rgb2hex from matplotlib.

from matplotlib.colors import rgb2hex

[ rgb2hex(A[i,:]) for i in range(A.shape[0]) ]
# ['#687847', '#979b8d', '#706d59', '#6a734d', '#8b5e66', '#5e5051']

If you would rather not like the matplotlib function, you will need to convert your array to int before using the referenced SO answer. Note that there are slight differences in the output which I assume to be due to rounding errors.

B = np.array(A*255, dtype=int) # convert to int

# Define a function for the mapping
rgb2hex = lambda r,g,b: '#%02x%02x%02x' %(r,g,b)

[ rgb2hex(*B[i,:]) for i in range(B.shape[0]) ]
# ['#687846', '#979a8d', '#706d59', '#6a734d', '#8a5e66', '#5e5050']

RGB to hex and hex to RGB

Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

How do I convert a hex triplet to an RGB tuple and back?

You can use a look-up table with some slicing and shifts — all relatively fast operations — to create a couple of functions that will work unchanged in both Python 2 and 3:

_NUMERALS = '0123456789abcdefABCDEF'
_HEXDEC = {v: int(v, 16) for v in (x+y for x in _NUMERALS for y in _NUMERALS)}
LOWERCASE, UPPERCASE = 'x', 'X'

def rgb(triplet):
return _HEXDEC[triplet[0:2]], _HEXDEC[triplet[2:4]], _HEXDEC[triplet[4:6]]

def triplet(rgb, lettercase=LOWERCASE):
return format(rgb[0]<<16 | rgb[1]<<8 | rgb[2], '06'+lettercase)

if __name__ == '__main__':
print('{}, {}'.format(rgb('aabbcc'), rgb('AABBCC')))
# -> (170, 187, 204), (170, 187, 204)

print('{}, {}'.format(triplet((170, 187, 204)),
triplet((170, 187, 204), UPPERCASE)))
# -> aabbcc, AABBCC

print('{}, {}'.format(rgb('aa0200'), rgb('AA0200')))
# -> (170, 2, 0), (170, 2, 0)

print('{}, {}'.format(triplet((170, 2, 0)),
triplet((170, 2, 0), UPPERCASE)))
# -> aa0200, AA0200

Converting hex color to RGB and vice-versa

Real answer: Depends on what kind of hexadecimal color value you are looking for (e.g. 565, 555, 888, 8888, etc), the amount of alpha bits, the actual color distribution (rgb vs bgr...) and a ton of other variables.

Here's a generic algorithm for most RGB values using C++ templates (straight from ScummVM).

template<class T>
uint32 RGBToColor(uint8 r, uint8 g, uint8 b) {
return T::kAlphaMask |
(((r << T::kRedShift) >> (8 - T::kRedBits)) & T::kRedMask) |
(((g << T::kGreenShift) >> (8 - T::kGreenBits)) & T::kGreenMask) |
(((b << T::kBlueShift) >> (8 - T::kBlueBits)) & T::kBlueMask);
}

Here's a sample color struct for 565 (the standard format for 16 bit colors):

template<>
struct ColorMasks<565> {
enum {
highBits = 0xF7DEF7DE,
lowBits = 0x08210821,
qhighBits = 0xE79CE79C,
qlowBits = 0x18631863,

kBytesPerPixel = 2,

kAlphaBits = 0,
kRedBits = 5,
kGreenBits = 6,
kBlueBits = 5,

kAlphaShift = kRedBits+kGreenBits+kBlueBits,
kRedShift = kGreenBits+kBlueBits,
kGreenShift = kBlueBits,
kBlueShift = 0,

kAlphaMask = ((1 << kAlphaBits) - 1) << kAlphaShift,
kRedMask = ((1 << kRedBits) - 1) << kRedShift,
kGreenMask = ((1 << kGreenBits) - 1) << kGreenShift,
kBlueMask = ((1 << kBlueBits) - 1) << kBlueShift,

kRedBlueMask = kRedMask | kBlueMask

};
};

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

Convert matplotlib color value to RGB

The problem you describe is that your statement:

The last line, to_rgb(color) doesn't work.

is not true.

As OrOrg already commented:

to_rgb(c) converts whatever c is (can be many things as long as it
relates to color: a hex string, name, ...) into an RGB tuple with
values in the range [0,1]. But in your case c is already an RGB tuple,
so nothing extra happens.

What you expect is to get the RGB values as integers or a string with a hex-code what can be done as follows:

from matplotlib import pyplot as plt

cycler = plt.cycler("color", plt.cm.tab20c.colors)()
color = next(cycler)["color"]

color_rgb = tuple([int(c*255) for c in color]) # <--
print(color_rgb) # gives (49, 130, 189)
color_rgb_hex = '#%02x%02x%02x' % color_rgb # <--
print(color_rgb_hex) # gives '#3182bd'

The matplotlib .to_hex() works as by you expected :

color_rgb_hex_by_matplotlib = matplotlib.colors.to_hex(color)
print(color_rgb_hex_by_matplotlib) # gives '#3182bd'

The matplotlib .to_rgb() drops only the alpha channel from the to it passed color see here



Related Topics



Leave a reply



Submit