|
1 | 1 | """Conversion functions between RGB and other color systems. |
| 2 | +
|
2 | 3 | This modules provides two functions for each color system ABC: |
| 4 | +
|
3 | 5 | rgb_to_abc(r, g, b) --> a, b, c |
4 | 6 | abc_to_rgb(a, b, c) --> r, g, b |
| 7 | +
|
5 | 8 | All inputs and outputs are triples of floats in the range [0.0...1.0] |
6 | 9 | (with the exception of I and Q, which covers a slightly larger range). |
7 | 10 | Inputs outside the valid range may cause exceptions or invalid outputs. |
| 11 | +
|
8 | 12 | Supported color systems: |
9 | 13 | RGB: Red, Green, Blue components |
10 | 14 | YIQ: Luminance, Chrominance (used by composite video signals) |
@@ -71,17 +75,18 @@ def yiq_to_rgb(y, i, q): |
71 | 75 | def rgb_to_hls(r, g, b): |
72 | 76 | maxc = max(r, g, b) |
73 | 77 | minc = min(r, g, b) |
74 | | - # XXX Can optimize (maxc+minc) and (maxc-minc) |
75 | | - l = (minc+maxc)/2.0 |
| 78 | + sumc = (maxc+minc) |
| 79 | + rangec = (maxc-minc) |
| 80 | + l = sumc/2.0 |
76 | 81 | if minc == maxc: |
77 | 82 | return 0.0, l, 0.0 |
78 | 83 | if l <= 0.5: |
79 | | - s = (maxc-minc) / (maxc+minc) |
| 84 | + s = rangec / sumc |
80 | 85 | else: |
81 | | - s = (maxc-minc) / (2.0-maxc-minc) |
82 | | - rc = (maxc-r) / (maxc-minc) |
83 | | - gc = (maxc-g) / (maxc-minc) |
84 | | - bc = (maxc-b) / (maxc-minc) |
| 86 | + s = rangec / (2.0-sumc) |
| 87 | + rc = (maxc-r) / rangec |
| 88 | + gc = (maxc-g) / rangec |
| 89 | + bc = (maxc-b) / rangec |
85 | 90 | if r == maxc: |
86 | 91 | h = bc-gc |
87 | 92 | elif g == maxc: |
@@ -120,13 +125,14 @@ def _v(m1, m2, hue): |
120 | 125 | def rgb_to_hsv(r, g, b): |
121 | 126 | maxc = max(r, g, b) |
122 | 127 | minc = min(r, g, b) |
| 128 | + rangec = (maxc-minc) |
123 | 129 | v = maxc |
124 | 130 | if minc == maxc: |
125 | 131 | return 0.0, 0.0, v |
126 | | - s = (maxc-minc) / maxc |
127 | | - rc = (maxc-r) / (maxc-minc) |
128 | | - gc = (maxc-g) / (maxc-minc) |
129 | | - bc = (maxc-b) / (maxc-minc) |
| 132 | + s = rangec / maxc |
| 133 | + rc = (maxc-r) / rangec |
| 134 | + gc = (maxc-g) / rangec |
| 135 | + bc = (maxc-b) / rangec |
130 | 136 | if r == maxc: |
131 | 137 | h = bc-gc |
132 | 138 | elif g == maxc: |
|
0 commit comments