Skip to content

Commit 2b7058c

Browse files
committed
Add colorsys
Adds HLS to RGB and HSV to RGB support via standard library colorsys module
1 parent 846dac0 commit 2b7058c

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

colorsys.py

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#This implements a chopped down relevant version of the colorsys library
2+
#to add HLS and HSV to RGB support
3+
#Returned values will be a 0-1 float and will need to be returned to 0-255 integer value.
4+
5+
__all__ = ["hls_to_rgb","hsv_to_rgb"]
6+
7+
# Some floating point constants
8+
9+
ONE_THIRD = 1.0/3.0
10+
ONE_SIXTH = 1.0/6.0
11+
TWO_THIRD = 2.0/3.0
12+
13+
# HLS: Hue, Luminance, Saturation
14+
# H: position in the spectrum
15+
# L: color lightness
16+
# S: color saturation
17+
18+
def hls_to_rgb(h, l, s):
19+
if s == 0.0:
20+
return l, l, l
21+
if l <= 0.5:
22+
m2 = l * (1.0+s)
23+
else:
24+
m2 = l+s-(l*s)
25+
m1 = 2.0*l - m2
26+
return (_v(m1, m2, h+ONE_THIRD), _v(m1, m2, h), _v(m1, m2, h-ONE_THIRD))
27+
28+
def _v(m1, m2, hue):
29+
hue = hue % 1.0
30+
if hue < ONE_SIXTH:
31+
return m1 + (m2-m1)*hue*6.0
32+
if hue < 0.5:
33+
return m2
34+
if hue < TWO_THIRD:
35+
return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0
36+
return m1
37+
38+
39+
# HSV: Hue, Saturation, Value
40+
# H: position in the spectrum
41+
# S: color saturation ("purity")
42+
# V: color brightness
43+
44+
def hsv_to_rgb(h, s, v):
45+
if s == 0.0:
46+
return v, v, v
47+
i = int(h*6.0) # XXX assume int() truncates!
48+
f = (h*6.0) - i
49+
p = v*(1.0 - s)
50+
q = v*(1.0 - s*f)
51+
t = v*(1.0 - s*(1.0-f))
52+
i = i%6
53+
if i == 0:
54+
return v, t, p
55+
if i == 1:
56+
return q, v, p
57+
if i == 2:
58+
return p, v, t
59+
if i == 3:
60+
return p, q, v
61+
if i == 4:
62+
return t, p, v
63+
if i == 5:
64+
return v, p, q
65+
# Cannot get here

0 commit comments

Comments
 (0)