Aluode/PerceptionLabPortable
0
1#
2# The Python Imaging Library
3# $Id$
4#
5# map CSS3-style colour description strings to RGB
6#
7# History:
8# 2002-10-24 fl Added support for CSS-style color strings
9# 2002-12-15 fl Added RGBA support
10# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
11# 2004-07-19 fl Fixed gray/grey spelling issues
12# 2009-03-05 fl Fixed rounding error in grayscale calculation
13#
14# Copyright (c) 2002-2004 by Secret Labs AB
15# Copyright (c) 2002-2004 by Fredrik Lundh
16#
17# See the README file for information on usage and redistribution.
18#
19from __future__ import annotations
20
21import re
22from functools import lru_cache
23
24from . import Image
25
26
27@lru_cache
28def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
29 """
30 Convert a color string to an RGB or RGBA tuple. If the string cannot be
31 parsed, this function raises a :py:exc:`ValueError` exception.
32
33 .. versionadded:: 1.1.4
34
35 :param color: A color string
36 :return: ``(red, green, blue[, alpha])``
37 """
38 if len(color) > 100:
39 msg = "color specifier is too long"
40 raise ValueError(msg)
41 color = color.lower()
42
43 rgb = colormap.get(color, None)
44 if rgb:
45 if isinstance(rgb, tuple):
46 return rgb
47 rgb_tuple = getrgb(rgb)
48 assert len(rgb_tuple) == 3
49 colormap[color] = rgb_tuple
50 return rgb_tuple
51
52 # check for known string formats
53 if re.match("#[a-f0-9]{3}$", color):
54 return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
55
56 if re.match("#[a-f0-9]{4}$", color):
57 return (
58 int(color[1] * 2, 16),
59 int(color[2] * 2, 16),
60 int(color[3] * 2, 16),
61 int(color[4] * 2, 16),
62 )
63
64 if re.match("#[a-f0-9]{6}$", color):
65 return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
66
67 if re.match("#[a-f0-9]{8}$", color):
68 return (
69 int(color[1:3], 16),
70 int(color[3:5], 16),
71 int(color[5:7], 16),
72 int(color[7:9], 16),
73 )
74
75 m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
76 if m:
77 return int(m.group(1)), int(m.group(2)), int(m.group(3))
78
79 m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
80 if m:
81 return (
82 int((int(m.group(1)) * 255) / 100.0 + 0.5),
83 int((int(m.group(2)) * 255) / 100.0 + 0.5),
84 int((int(m.group(3)) * 255) / 100.0 + 0.5),
85 )
86
87 m = re.match(
88 r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
89 )
90 if m:
91 from colorsys import hls_to_rgb
92
93 rgb_floats = hls_to_rgb(
94 float(m.group(1)) / 360.0,
95 float(m.group(3)) / 100.0,
96 float(m.group(2)) / 100.0,
97 )
98 return (
99 int(rgb_floats[0] * 255 + 0.5),
100 int(rgb_floats[1] * 255 + 0.5),
101 int(rgb_floats[2] * 255 + 0.5),
102 )
103
104 m = re.match(
105 r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
106 )
107 if m:
108 from colorsys import hsv_to_rgb
109
110 rgb_floats = hsv_to_rgb(
111 float(m.group(1)) / 360.0,
112 float(m.group(2)) / 100.0,
113 float(m.group(3)) / 100.0,
114 )
115 return (
116 int(rgb_floats[0] * 255 + 0.5),
117 int(rgb_floats[1] * 255 + 0.5),
118 int(rgb_floats[2] * 255 + 0.5),
119 )
120
121 m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
122 if m:
123 return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
124 msg = f"unknown color specifier: {repr(color)}"
125 raise ValueError(msg)
126
127
128@lru_cache
129def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
130 """
131 Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
132 ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
133 not color or a palette image, converts the RGB value to a grayscale value.
134 If the string cannot be parsed, this function raises a :py:exc:`ValueError`
135 exception.
136
137 .. versionadded:: 1.1.4
138
139 :param color: A color string
140 :param mode: Convert result to this mode
141 :return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
142 """
143 # same as getrgb, but converts the result to the given mode
144 rgb, alpha = getrgb(color), 255
145 if len(rgb) == 4:
146 alpha = rgb[3]
147 rgb = rgb[:3]
148
149 if mode == "HSV":
150 from colorsys import rgb_to_hsv
151
152 r, g, b = rgb
153 h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
154 return int(h * 255), int(s * 255), int(v * 255)
155 elif Image.getmodebase(mode) == "L":
156 r, g, b = rgb
157 # ITU-R Recommendation 601-2 for nonlinear RGB
158 # scaled to 24 bits to match the convert's implementation.
159 graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
160 if mode[-1] == "A":
161 return graylevel, alpha
162 return graylevel
163 elif mode[-1] == "A":
164 return rgb + (alpha,)
165 return rgb
166
167
168colormap: dict[str, str | tuple[int, int, int]] = {
169 # X11 colour table from https://drafts.csswg.org/css-color-4/, with
170 # gray/grey spelling issues fixed. This is a superset of HTML 4.0
171 # colour names used in CSS 1.
172 "aliceblue": "#f0f8ff",
173 "antiquewhite": "#faebd7",
174 "aqua": "#00ffff",
175 "aquamarine": "#7fffd4",
176 "azure": "#f0ffff",
177 "beige": "#f5f5dc",
178 "bisque": "#ffe4c4",
179 "black": "#000000",
180 "blanchedalmond": "#ffebcd",
181 "blue": "#0000ff",
182 "blueviolet": "#8a2be2",
183 "brown": "#a52a2a",
184 "burlywood": "#deb887",
185 "cadetblue": "#5f9ea0",
186 "chartreuse": "#7fff00",
187 "chocolate": "#d2691e",
188 "coral": "#ff7f50",
189 "cornflowerblue": "#6495ed",
190 "cornsilk": "#fff8dc",
191 "crimson": "#dc143c",
192 "cyan": "#00ffff",
193 "darkblue": "#00008b",
194 "darkcyan": "#008b8b",
195 "darkgoldenrod": "#b8860b",
196 "darkgray": "#a9a9a9",
197 "darkgrey": "#a9a9a9",
198 "darkgreen": "#006400",
199 "darkkhaki": "#bdb76b",
200 "darkmagenta": "#8b008b",
201 "darkolivegreen": "#556b2f",
202 "darkorange": "#ff8c00",
203 "darkorchid": "#9932cc",
204 "darkred": "#8b0000",
205 "darksalmon": "#e9967a",
206 "darkseagreen": "#8fbc8f",
207 "darkslateblue": "#483d8b",
208 "darkslategray": "#2f4f4f",
209 "darkslategrey": "#2f4f4f",
210 "darkturquoise": "#00ced1",
211 "darkviolet": "#9400d3",
212 "deeppink": "#ff1493",
213 "deepskyblue": "#00bfff",
214 "dimgray": "#696969",
215 "dimgrey": "#696969",
216 "dodgerblue": "#1e90ff",
217 "firebrick": "#b22222",
218 "floralwhite": "#fffaf0",
219 "forestgreen": "#228b22",
220 "fuchsia": "#ff00ff",
221 "gainsboro": "#dcdcdc",
222 "ghostwhite": "#f8f8ff",
223 "gold": "#ffd700",
224 "goldenrod": "#daa520",
225 "gray": "#808080",
226 "grey": "#808080",
227 "green": "#008000",
228 "greenyellow": "#adff2f",
229 "honeydew": "#f0fff0",
230 "hotpink": "#ff69b4",
231 "indianred": "#cd5c5c",
232 "indigo": "#4b0082",
233 "ivory": "#fffff0",
234 "khaki": "#f0e68c",
235 "lavender": "#e6e6fa",
236 "lavenderblush": "#fff0f5",
237 "lawngreen": "#7cfc00",
238 "lemonchiffon": "#fffacd",
239 "lightblue": "#add8e6",
240 "lightcoral": "#f08080",
241 "lightcyan": "#e0ffff",
242 "lightgoldenrodyellow": "#fafad2",
243 "lightgreen": "#90ee90",
244 "lightgray": "#d3d3d3",
245 "lightgrey": "#d3d3d3",
246 "lightpink": "#ffb6c1",
247 "lightsalmon": "#ffa07a",
248 "lightseagreen": "#20b2aa",
249 "lightskyblue": "#87cefa",
250 "lightslategray": "#778899",
251 "lightslategrey": "#778899",
252 "lightsteelblue": "#b0c4de",
253 "lightyellow": "#ffffe0",
254 "lime": "#00ff00",
255 "limegreen": "#32cd32",
256 "linen": "#faf0e6",
257 "magenta": "#ff00ff",
258 "maroon": "#800000",
259 "mediumaquamarine": "#66cdaa",
260 "mediumblue": "#0000cd",
261 "mediumorchid": "#ba55d3",
262 "mediumpurple": "#9370db",
263 "mediumseagreen": "#3cb371",
264 "mediumslateblue": "#7b68ee",
265 "mediumspringgreen": "#00fa9a",
266 "mediumturquoise": "#48d1cc",
267 "mediumvioletred": "#c71585",
268 "midnightblue": "#191970",
269 "mintcream": "#f5fffa",
270 "mistyrose": "#ffe4e1",
271 "moccasin": "#ffe4b5",
272 "navajowhite": "#ffdead",
273 "navy": "#000080",
274 "oldlace": "#fdf5e6",
275 "olive": "#808000",
276 "olivedrab": "#6b8e23",
277 "orange": "#ffa500",
278 "orangered": "#ff4500",
279 "orchid": "#da70d6",
280 "palegoldenrod": "#eee8aa",
281 "palegreen": "#98fb98",
282 "paleturquoise": "#afeeee",
283 "palevioletred": "#db7093",
284 "papayawhip": "#ffefd5",
285 "peachpuff": "#ffdab9",
286 "peru": "#cd853f",
287 "pink": "#ffc0cb",
288 "plum": "#dda0dd",
289 "powderblue": "#b0e0e6",
290 "purple": "#800080",
291 "rebeccapurple": "#663399",
292 "red": "#ff0000",
293 "rosybrown": "#bc8f8f",
294 "royalblue": "#4169e1",
295 "saddlebrown": "#8b4513",
296 "salmon": "#fa8072",
297 "sandybrown": "#f4a460",
298 "seagreen": "#2e8b57",
299 "seashell": "#fff5ee",
300 "sienna": "#a0522d",
301 "silver": "#c0c0c0",
302 "skyblue": "#87ceeb",
303 "slateblue": "#6a5acd",
304 "slategray": "#708090",
305 "slategrey": "#708090",
306 "snow": "#fffafa",
307 "springgreen": "#00ff7f",
308 "steelblue": "#4682b4",
309 "tan": "#d2b48c",
310 "teal": "#008080",
311 "thistle": "#d8bfd8",
312 "tomato": "#ff6347",
313 "turquoise": "#40e0d0",
314 "violet": "#ee82ee",
315 "wheat": "#f5deb3",
316 "white": "#ffffff",
317 "whitesmoke": "#f5f5f5",
318 "yellow": "#ffff00",
319 "yellowgreen": "#9acd32",
320}
321 