c2cdf57c9705459388573a7519e333f6187620da
"""Conversion functions between RGB and other color systems.
This modules provides two functions for each color system ABC:
rgb_to_abc(r, g, b) --> a, b, c
abc_to_rgb(a, b, c) --> r, g, b
All inputs and outputs are triples of floats in the range [0.0...1.0].
Inputs outside this range may cause exceptions or invalid outputs.
RGB: Red, Green, Blue components
YIQ: used by composite video signals
HLS: Hue, Luminance, Saturation
HSV: Hue, Saturation, Value
# XXX Where's the literature?
__all__
= ["rgb_to_yiq","yiq_to_rgb","rgb_to_hls","hls_to_rgb",
"rgb_to_hsv","hsv_to_rgb"]
# Some floating point constants
# YIQ: used by composite video signals (linear combinations of RGB)
# Y: perceived grey level (0.0 == black, 1.0 == white)
y
= 0.30*r
+ 0.59*g
+ 0.11*b
i
= 0.60*r
- 0.28*g
- 0.32*b
q
= 0.21*r
- 0.52*g
+ 0.31*b
r
= y
+ 0.948262*i
+ 0.624013*q
g
= y
- 0.276066*i
- 0.639810*q
b
= y
- 1.105450*i
+ 1.729860*q
# HLS: Hue, Luminance, S???
# H: position in the spectrum
# XXX Can optimize (maxc+minc) and (maxc-minc)
if minc
== maxc
: return 0.0, l
, 0.0
if l
<= 0.5: s
= (maxc
-minc
) / (maxc
+minc
)
else: s
= (maxc
-minc
) / (2.0-maxc
-minc
)
rc
= (maxc
-r
) / (maxc
-minc
)
gc
= (maxc
-g
) / (maxc
-minc
)
bc
= (maxc
-b
) / (maxc
-minc
)
elif g
== maxc
: h
= 2.0+rc
-bc
if s
== 0.0: return l
, l
, l
if l
<= 0.5: m2
= l
* (1.0+s
)
return (_v(m1
, m2
, h
+ONE_THIRD
), _v(m1
, m2
, h
), _v(m1
, m2
, h
-ONE_THIRD
))
if hue
< ONE_SIXTH
: return m1
+ (m2
-m1
)*hue
*6.0
if hue
< TWO_THIRD
: return m1
+ (m2
-m1
)*(TWO_THIRD
-hue
)*6.0
# HSV: Hue, Saturation, Value(?)
# H: position in the spectrum
if minc
== maxc
: return 0.0, 0.0, v
rc
= (maxc
-r
) / (maxc
-minc
)
gc
= (maxc
-g
) / (maxc
-minc
)
bc
= (maxc
-b
) / (maxc
-minc
)
elif g
== maxc
: h
= 2.0+rc
-bc
if s
== 0.0: return v
, v
, v
i
= int(h
*6.0) # XXX assume int() truncates!
if i
%6 == 0: return v
, t
, p
if i
== 1: return q
, v
, p
if i
== 2: return p
, v
, t
if i
== 3: return p
, q
, v
if i
== 4: return t
, p
, v
if i
== 5: return v
, p
, q