1 # Conversion functions between RGB and other color systems.
3 # Define two functions for each color system XYZ:
4 # rgb_to_xyz(r, g, b) --> x, y, z
5 # xyz_to_rgb(x, y, z) --> r, g, b
6 # All inputs and outputs are triples of floats in the range [0.0...1.0].
7 # Inputs outside this range may cause exceptions or invalid outputs.
9 # Supported color systems:
10 # RGB: Red, Green, Blue components
11 # YIQ: used by composite video signals
12 # HLS: Hue, Luminance, S???
13 # HSV: Hue, Saturation, Value(?)
16 # XXX Where's the literature?
19 # Some floating point constants
26 # YIQ: used by composite video signals (linear combinations of RGB)
27 # Y: perceived grey level (0.0 == black, 1.0 == white)
28 # I, Q: color components
30 def rgb_to_yiq(r
, g
, b
):
31 y
= 0.30*r
+ 0.59*g
+ 0.11*b
32 i
= 0.60*r
- 0.28*g
- 0.32*b
33 q
= 0.21*r
- 0.52*g
+ 0.31*b
36 def yiq_to_rgb(y
, i
, q
):
37 r
= y
+ 0.948262*i
+ 0.624013*q
38 g
= y
- 0.276066*i
- 0.639810*q
39 b
= y
- 1.105450*i
+ 1.729860*q
49 # HLS: Hue, Luminance, S???
50 # H: position in the spectrum
54 def rgb_to_hls(r
, g
, b
):
57 # XXX Can optimize (maxc+minc) and (maxc-minc)
59 if minc
== maxc
: return 0.0, l
, 0.0
60 if l
<= 0.5: s
= (maxc
-minc
) / (maxc
+minc
)
61 else: s
= (maxc
-minc
) / (2.0-maxc
-minc
)
62 rc
= (maxc
-r
) / (maxc
-minc
)
63 gc
= (maxc
-g
) / (maxc
-minc
)
64 bc
= (maxc
-b
) / (maxc
-minc
)
65 if r
== maxc
: h
= bc
-gc
66 elif g
== maxc
: h
= 2.0+rc
-bc
71 def hls_to_rgb(h
, l
, s
):
72 if s
== 0.0: return l
, l
, l
73 if l
<= 0.5: m2
= l
* (1.0+s
)
76 return (_v(m1
, m2
, h
+ONE_THIRD
), _v(m1
, m2
, h
), _v(m1
, m2
, h
-ONE_THIRD
))
80 if hue
< ONE_SIXTH
: return m1
+ (m2
-m1
)*hue
*6.0
81 if hue
< 0.5: return m2
82 if hue
< TWO_THIRD
: return m1
+ (m2
-m1
)*(TWO_THIRD
-hue
)*6.0
86 # HSV: Hue, Saturation, Value(?)
87 # H: position in the spectrum
91 def rgb_to_hsv(r
, g
, b
):
95 if minc
== maxc
: return 0.0, 0.0, v
96 s
= (maxc
-minc
) / maxc
97 rc
= (maxc
-r
) / (maxc
-minc
)
98 gc
= (maxc
-g
) / (maxc
-minc
)
99 bc
= (maxc
-b
) / (maxc
-minc
)
100 if r
== maxc
: h
= bc
-gc
101 elif g
== maxc
: h
= 2.0+rc
-bc
106 def hsv_to_rgb(h
, s
, v
):
107 if s
== 0.0: return v
, v
, v
108 i
= int(h
*6.0) # XXX assume int() truncates!
112 t
= v
*(1.0 - s
*(1.0-f
))
113 if i
%6 == 0: return v
, t
, p
114 if i
== 1: return q
, v
, p
115 if i
== 2: return p
, v
, t
116 if i
== 3: return p
, q
, v
117 if i
== 4: return t
, p
, v
118 if i
== 5: return v
, p
, q