Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert colorsys RGB coordinates to hex

Tags:

python

rgb

Following from this answer, I am generating some evenly spaced colors in Python as follows:

>>> import colorsys
>>> num_colors = 22
>>> hsv_tuples = [(x*1.0/num_colors, 0.5, 0.5) for x in range(num_colors)]
>>> rgb_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)
>>> rgb_tuples
[(0.5, 0.25, 0.25), (0.5, 0.3181818181818182, 0.25), (0.5, 0.38636363636363635, 0.25), (0.5, 0.45454545454545453, 0.25), (0.4772727272727273, 0.5, 0.25), (0.4090909090909091, 0.5, 0.25), (0.34090909090909094, 0.5, 0.25), (0.2727272727272727, 0.5, 0.25), (0.25, 0.5, 0.2954545454545454), (0.25, 0.5, 0.36363636363636365), (0.25, 0.5, 0.43181818181818177), (0.25, 0.5, 0.5), (0.25, 0.4318181818181819, 0.5), (0.25, 0.36363636363636354, 0.5), (0.25, 0.2954545454545454, 0.5), (0.2727272727272727, 0.25, 0.5), (0.34090909090909083, 0.25, 0.5), (0.40909090909090917, 0.25, 0.5), (0.4772727272727273, 0.25, 0.5), (0.5, 0.25, 0.4545454545454546), (0.5, 0.25, 0.38636363636363646), (0.5, 0.25, 0.3181818181818181)]

Hows does one now convert from these ("coordinate?") RGB tuples back to RGB hex strings, e.g. #FF00AA? Probably a simple question, but not one I've been able to find the answer to.

like image 394
Bryce Thomas Avatar asked Feb 09 '13 02:02

Bryce Thomas


1 Answers

For each color, floor(color * 256), printed out in hexadecimal (padded to 2 places). e.g.:

In [1]: rgb_tuples = [(0.5, 0.25, 0.25), (0.5, 0.3181818181818182, 0.25), (0.5, 0.38636363636363635, 0.25), (0.5, 0.45454545454545453, 0.25), (0.4772727272727273, 0.5, 0.25), (0.4090909090909091, 0.5, 0.25), (0.34090909090909094, 0.5, 0.25), (0.2727272727272727, 0.5, 0.25), (0.25, 0.5, 0.2954545454545454), (0.25, 0.5, 0.36363636363636365), (0.25, 0.5, 0.43181818181818177), (0.25, 0.5, 0.5), (0.25, 0.4318181818181819, 0.5), (0.25, 0.36363636363636354, 0.5), (0.25, 0.2954545454545454, 0.5), (0.2727272727272727, 0.25, 0.5), (0.34090909090909083, 0.25, 0.5), (0.40909090909090917, 0.25, 0.5), (0.4772727272727273, 0.25, 0.5), (0.5, 0.25, 0.4545454545454546), (0.5, 0.25, 0.38636363636363646), (0.5, 0.25, 0.3181818181818181)]

In [2]: for (r,g,b) in rgb_tuples:
   ...:     print '%02x%02x%02x' % (int(r*255), int(g*255), int(b*255))
   ...:     
804040
805140
806240
807440
like image 102
Brian Cain Avatar answered Sep 20 '22 22:09

Brian Cain