-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgencolors.py
58 lines (51 loc) · 2.33 KB
/
gencolors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
## From: http://stackoverflow.com/questions/470690/how-to-automatically-generate-n-distinct-colors
## (Heavily) adapted by HV to work with Python 2.6 and up
## Simplified to generate HSV (PGPLOT understands HSV as Hue-Saturation-Lightness)
## Also: I wanted the getfracs() to divide the colors nicer over the colourspace
## so there's an assumption about how many variations of each colour are created
## such that we can divide the "H" colour space in roughly even bits.
## If you requested a low number of colours from the original code, they would be
## rather close to each other
from __future__ import print_function
import itertools, math, colorsys
from fractions import Fraction
# Py2/Py3 compatibility: make sure map_() returns a list
# *efficiently* on either system
try:
# Crude Py2 detection
r = raw_input
ensure_list = lambda x: x
except NameError:
ensure_list = lambda f: (lambda *args, **kwargs: list(f(*args, **kwargs)))
map_ = ensure_list(map)
def getfracs(n):
# we generate four variations / colour (=h)
# so we want the step size to step through the colour wheel in ~ n/4 steps
# This stepsize seems to avoid the 120 and 240 degrees H value reasonably well
#d = (float(n)/4) * 9.2*math.e/360.0
ngen = math.ceil(float(n)/4)*4
s = 105.0 # start of colour wheel - just below red
e = 263.0 # end of colour wheel - just pas green
d = (4*(e - s))/ngen
f0 = s
while f0<e:
yield f0
f0 += d
# can be used for the v in hsv to map linear values 0..1 to something that looks equidistant
bias = lambda x: (math.sqrt(x/3)/Fraction(2,3)+Fraction(1,3))/Fraction(6,5)
## Iterate the fastest over the actual colour, then by pureness and finally
## by lightness
def genhsv(n):
for v in [Fraction(8,10),Fraction(5,10)]: # could use range too
for s in [Fraction(x,13) for x in range(3,9,3)]: # optionally use range
for h in getfracs(n):
yield (h, s, bias(v))
getflt = lambda x: map_(float, x)
gethsvs = lambda n: map_(getflt, genhsv(n))
getrgb = lambda x: colorsys.hsv_to_rgb(*x)
getncol_hsv = lambda n: list(itertools.islice(gethsvs(n), n))
getncol_rgb = lambda n: map_(getrgb, getncol_hsv(n))
if __name__ == "__main__":
l = getncol_hsv(13)
print("Generated ",len(l)," colours")
print(map_(getrgb, l))