Skip to content

Instantly share code, notes, and snippets.

@bagrow
Last active December 1, 2016 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bagrow/e5b08a3c8e6232fbfe65 to your computer and use it in GitHub Desktop.
Save bagrow/e5b08a3c8e6232fbfe65 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# color_stuff.py
# Jim Bagrow
# Last Modified: 2016-12-01
import colorsys
def distinguishable_colors(num, sat=1.0, val=1.0):
"""Generate a list of `num' rgb hexadecimal color strings. The strings are
linearly spaced along hue values from 0 to 1, leading to `num' colors with
maximally different hues.
Example:
>>> print(distinguishable_colors(5))
['#ff0000', '#ccff00', '#00ff66', '#0066ff', '#cc00ff']
"""
list_colors = [];
hue = 0.0
while abs(hue - 1.0) > 1e-4:
rgb = [i for i in list(colorsys.hsv_to_rgb(hue, sat, val))]
list_colors.append( rgb_to_hex(rgb) )
hue += 1.0/num;
return list_colors
def rgb_to_hex(rgb):
"""Convert an rgb 3-tuple to a hexadecimal color string.
Example:
>>> print(rgb_to_hex((0.50,0.2,0.8)))
#8033cc
"""
return '#%02x%02x%02x' % tuple([round(x*255) for x in rgb])
def hex_to_rgb(hexrgb):
""" Convert a hexadecimal color string to an rgb 3-tuple.
Example:
>>> print(hex_to_rgb("#8033CC"))
(0.502, 0.2, 0.8)
"""
hexrgb = hexrgb.lstrip('#')
lv = len(hexrgb)
return tuple(round(int(hexrgb[i:i+lv/3], 16)/255.0,4) for i in range(0, lv, lv/3))
def darken_hex(hexrgb, factor=0.5):
"""Take an rgb color of the form #RRGGBB and darken it by `factor' without
changing the color. Specifically the RGB is converted to HSV and V ->
V*factor.
Example:
>>> print(darken_hex("#8033CC"))
'#401966'
"""
rgb = hex_to_rgb(hexrgb)
hsv = list(colorsys.rgb_to_hsv(*rgb))
hsv[2] = hsv[2]*factor
rgb = colorsys.hsv_to_rgb(*hsv)
return rgb_to_hex(rgb)
def darken_rgb(rgb, factor=0.5):
"""Take an rgb 3-tuple and darken it by `factor', approximately
preserving the hue.
Example:
>>> print(darken_rgb((0.5,0.2,0.7)))
(0.251, 0.098, 0.3529)
"""
hexrgb = darken_hex(rgb_to_hex(rgb), factor=factor)
return hex_to_rgb(hexrgb)
if __name__ == '__main__':
print(darken_rgb((0.5,0.2,0.7)) )
print(darken_hex("#8033CC"))
print(hex_to_rgb("#8033CC") )
print(rgb_to_hex((0.50,0.2,0.8)))
print(distinguishable_colors(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment