Skip to content

Instantly share code, notes, and snippets.

@JonasPf
Last active August 29, 2015 13:57
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 JonasPf/9461819 to your computer and use it in GitHub Desktop.
Save JonasPf/9461819 to your computer and use it in GitHub Desktop.
Create distinct colours
#
# Creates a html page with a list of distinct looking colours for graphs, etc.
# Algorithm from: http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
#
# Jonas Pfannschmidt
from colorsys import hsv_to_rgb
golden_ratio_conjugate = 0.618033988749895
# play around with these values to change the colours
h = 0.8
s = 0.7
v= 0.9
def calc_text_color(r, g, b):
r = r * 256
g = g * 256
b = b * 256
# Counting the perceptive luminance - human eye favors green color...
a = 1 - ( 0.299 * r + 0.587 * g + 0.114 * b)/255;
if (a < 0.5):
return '#000000'
else:
return '#ffffff'
def html_hex(dec):
return hex(int(dec * 255)).lstrip('0x').zfill(2)
def colour_256(rgb):
return (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))
def html_colour(rgb):
return '#' + html_hex(rgb[0]) + html_hex(rgb[1]) + html_hex(rgb[2])
for i in range(200):
# h = i / 20.0
h = h + golden_ratio_conjugate
h = h % 1
rgb = hsv_to_rgb(h, s, v)
# rgb = hsv_to_rgb(0, 1, 1)
print '<div style="background-color: {}; color: {}; width: 100px">{}<br>{}</div>'.format(html_colour(rgb), calc_text_color(rgb[0], rgb[1], rgb[2]), html_colour(rgb), colour_256(rgb))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment