1 """Conversion functions between RGB and other color systems.
3 This modules provides two functions for each color system ABC:
5 rgb_to_abc(r, g, b) --> a, b, c
6 abc_to_rgb(a, b, c) --> r, g, b
8 All inputs and outputs are triples of floats in the range [0.0...1.0]
9 (with the exception of I and Q, which covers a slightly larger range).
10 Inputs outside the valid range may cause exceptions or invalid outputs.
12 Supported color systems:
13 RGB: Red, Green, Blue components
14 YIQ: Luminance, Chrominance (used by composite video signals)
15 HLS: Hue, Luminance, Saturation
16 HSV: Hue, Saturation, Value
20 # http://en.wikipedia.org/wiki/YIQ
21 # http://en.wikipedia.org/wiki/HLS_color_space
22 # http://en.wikipedia.org/wiki/HSV_color_space
24 __all__
= ["rgb_to_yiq","yiq_to_rgb","rgb_to_hls","hls_to_rgb",
25 "rgb_to_hsv","hsv_to_rgb"]
27 # Some floating point constants
33 # YIQ: used by composite video signals (linear combinations of RGB)
34 # Y: perceived grey level (0.0 == black, 1.0 == white)
35 # I, Q: color components
37 def rgb_to_yiq(r
, g
, b
):
38 y
= 0.30*r
+ 0.59*g
+ 0.11*b
39 i
= 0.60*r
- 0.28*g
- 0.32*b
40 q
= 0.21*r
- 0.52*g
+ 0.31*b
43 def yiq_to_rgb(y
, i
, q
):
44 r
= y
+ 0.948262*i
+ 0.624013*q
45 g
= y
- 0.276066*i
- 0.639810*q
46 b
= y
- 1.105450*i
+ 1.729860*q
62 # HLS: Hue, Luminance, Saturation
63 # H: position in the spectrum
67 def rgb_to_hls(r
, g
, b
):
70 # XXX Can optimize (maxc+minc) and (maxc-minc)
75 s
= (maxc
-minc
) / (maxc
+minc
)
77 s
= (maxc
-minc
) / (2.0-maxc
-minc
)
78 rc
= (maxc
-r
) / (maxc
-minc
)
79 gc
= (maxc
-g
) / (maxc
-minc
)
80 bc
= (maxc
-b
) / (maxc
-minc
)
90 def hls_to_rgb(h
, l
, s
):
98 return (_v(m1
, m2
, h
+ONE_THIRD
), _v(m1
, m2
, h
), _v(m1
, m2
, h
-ONE_THIRD
))
103 return m1
+ (m2
-m1
)*hue
*6.0
107 return m1
+ (m2
-m1
)*(TWO_THIRD
-hue
)*6.0
111 # HSV: Hue, Saturation, Value
112 # H: position in the spectrum
113 # S: color saturation ("purity")
114 # V: color brightness
116 def rgb_to_hsv(r
, g
, b
):
122 s
= (maxc
-minc
) / maxc
123 rc
= (maxc
-r
) / (maxc
-minc
)
124 gc
= (maxc
-g
) / (maxc
-minc
)
125 bc
= (maxc
-b
) / (maxc
-minc
)
135 def hsv_to_rgb(h
, s
, v
):
138 i
= int(h
*6.0) # XXX assume int() truncates!
142 t
= v
*(1.0 - s
*(1.0-f
))