Debian Codegraph @

DisplayCAL/colormath.py

raw
1 """Diverse color mathematical functions.
2
3 Note:
4
5 In most cases, unless otherwise stated RGB is R'G'B' (gamma-compressed)
6 """
7
8 from __future__ import annotations
9
10 import colorsys
11 import logging
12 import math
13 import sys
14 import warnings
15 from typing import TYPE_CHECKING, Any, Callable, overload
16
17 import numpy
18
19 from DisplayCAL.debughelpers import DEBUG
20
21 if TYPE_CHECKING:
22 if sys.version_info >= (3, 11):
23 from typing import Self
24 else:
25 from typing_extensions import Self
26
27
28 logger = logging.getLogger(__name__)
29 if DEBUG:
30 logger.setLevel(logging.DEBUG)
31 else:
32 logger.setLevel(logging.INFO)
33
34
35 def cache(f: Callable) -> Callable[..., Any]:
36 """Decorator to convert list arguments to tuples and cache.
37
38 Args:
39 f (Callable): The function to wrap.
40 """
41
42 def wrapper(*args, **kwargs) -> Any: # noqa: ANN401
43 cache_hash = (
44 ((tuple(arg) if isinstance(arg, (list, tuple)) else arg for arg in args)),
45 (
46 (key, tuple(kwargs[key]))
47 if isinstance(kwargs[key], (list, tuple))
48 else kwargs[key]
49 for key in kwargs
50 ),
51 )
52 if not hasattr(f, "cache"):
53 f.cache = {}
54 if cache_hash in f.cache:
55 return f.cache[cache_hash]
56
57 result = f(*args, **kwargs)
58 f.cache[cache_hash] = result
59 return result
60
61 return wrapper
62
63
64 def get_transfer_function_phi(alpha: float, gamma: float) -> float:
65 """Get transfer function phi.
66
67 Args:
68 alpha (float): Alpha value.
69 gamma (float): Gamma value.
70
71 Returns:
72 float: Transfer function phi value.
73 """
74 return (math.pow(1 + alpha, gamma) * math.pow(gamma - 1, gamma - 1)) / (
75 math.pow(alpha, gamma - 1) * math.pow(gamma, gamma)
76 )
77
78
79 LSTAR_E = 216.0 / 24389.0 # Intent of CIE standard, actual CIE standard = 0.008856
80 LSTAR_K = 24389.0 / 27.0 # Intent of CIE standard, actual CIE standard = 903.3
81 REC709_K0 = 0.081 # 0.099 / (1.0 / 0.45 - 1)
82 REC709_P = 4.5 # get_transfer_function_phi(0.099, 1.0 / 0.45)
83 SMPTE240M_K0 = 0.0913 # 0.1115 / (1.0 / 0.45 - 1)
84 SMPTE240M_P = 4.0 # get_transfer_function_phi(0.1115, 1.0 / 0.45)
85 SMPTE2084_M1 = (2610.0 / 4096) * 0.25
86 SMPTE2084_M2 = (2523.0 / 4096) * 128
87 SMPTE2084_C1 = 3424.0 / 4096
88 SMPTE2084_C2 = (2413.0 / 4096) * 32
89 SMPTE2084_C3 = (2392.0 / 4096) * 32
90 SRGB_K0 = 0.04045 # 0.055 / (2.4 - 1)
91 SRGB_P = 12.92 # get_transfer_function_phi(0.055, 2.4)
92
93
94 def special_pow(a: float, b: float, slope_limit: float = 0) -> float:
95 """Wrapper for power, Rec. 601/709, SMPTE 240M, sRGB and L* functions.
96
97 Positive b = power, -2.4 = sRGB, -3.0 = L*, -240 = SMPTE 240M,
98 -601 = Rec. 601, -709 = Rec. 709 (Rec. 601 and 709 transfer functions are
99 identical)
100
101 Args:
102 a (float): Input value.
103 b (float): Exponent, transfer function or gamma.
104 slope_limit (float, optional): Slope limit for power curve, defaults to
105 0.
106
107 Returns:
108 float: Output value.
109 """
110 if b >= 0.0:
111 # Power curve
112 if a < 0.0:
113 if slope_limit:
114 return min(-math.pow(-a, b), a / slope_limit)
115 return -math.pow(-a, b)
116 if slope_limit:
117 return max(math.pow(a, b), a / slope_limit)
118 return math.pow(a, b)
119
120 sign_scale = -1.0 if a < 0.0 else 1.0
121 a = abs(a)
122
123 v = {
124 1.0 / -601:
125 # XYZ -> RGB, Rec. 601/709 TRC
126 (a * REC709_P)
127 if (a < REC709_K0 / REC709_P)
128 else (1.099 * math.pow(a, 0.45) - 0.099),
129 1.0 / -709:
130 # XYZ -> RGB, Rec. 601/709 TRC
131 (a * REC709_P)
132 if (a < REC709_K0 / REC709_P)
133 else (1.099 * math.pow(a, 0.45) - 0.099),
134 1.0 / -240:
135 # XYZ -> RGB, SMPTE 240M TRC
136 (a * SMPTE240M_P)
137 if (a < SMPTE240M_K0 / SMPTE240M_P)
138 else (1.1115 * math.pow(a, 0.45) - 0.1115),
139 1.0 / -3.0:
140 # XYZ -> RGB, L* TRC
141 0.01 * a * LSTAR_K if a <= LSTAR_E else 1.16 * math.pow(a, 1.0 / 3.0) - 0.16,
142 1.0 / -2.4:
143 # XYZ -> RGB, sRGB TRC
144 (a * SRGB_P)
145 if (a <= SRGB_K0 / SRGB_P)
146 else (1.055 * math.pow(a, 1.0 / 2.4) - 0.055),
147 1.0 / -2084:
148 # XYZ -> RGB, SMPTE 2084 (PQ)
149 ((2413.0 * (a**SMPTE2084_M1) + 107) / (2392.0 * (a**SMPTE2084_M1) + 128))
150 ** SMPTE2084_M2,
151 -2.4:
152 # RGB -> XYZ, sRGB TRC
153 a / SRGB_P if a <= SRGB_K0 else math.pow((a + 0.055) / 1.055, 2.4),
154 -3.0:
155 # RGB -> XYZ, L* TRC
156 # E * K * 0.01
157 100.0 * a / LSTAR_K if a <= 0.08 else math.pow((a + 0.16) / 1.16, 3.0),
158 -240:
159 # RGB -> XYZ, SMPTE 240M TRC
160 (
161 a / SMPTE240M_P
162 if a < SMPTE240M_K0
163 else math.pow((0.1115 + a) / 1.1115, 1.0 / 0.45)
164 ),
165 -601:
166 # RGB -> XYZ, Rec. 601/709 TRC
167 a / REC709_P if a < REC709_K0 else math.pow((a + 0.099) / 1.099, 1.0 / 0.45),
168 -709:
169 # RGB -> XYZ, Rec. 601/709 TRC
170 a / REC709_P if a < REC709_K0 else math.pow((a + 0.099) / 1.099, 1.0 / 0.45),
171 -2084:
172 # RGB -> XYZ, SMPTE 2084 (PQ)
173 # See https://www.smpte.org/sites/default/files/2014-05-06-EOTF-Miller-1-2-handout.pdf
174 (
175 max(a ** (1.0 / SMPTE2084_M2) - SMPTE2084_C1, 0)
176 / (SMPTE2084_C2 - SMPTE2084_C3 * a ** (1.0 / SMPTE2084_M2))
177 )
178 ** (1.0 / SMPTE2084_M1),
179 }.get(b)
180 if v is None:
181 raise ValueError(f"Invalid gamma {b!r}")
182
183 return v * sign_scale
184
185
186 def DICOM(j: float, inverse: bool = False) -> float: # noqa: N802
187 """DICOM TRC.
188
189 Args:
190 j (float): Input value.
191 inverse (bool): If True, apply inverse DICOM TRC.
192
193 Returns:
194 float: Output value.
195 """
196 if inverse:
197 log10y = math.log10(j)
198 a = 71.498068
199 b = 94.593053
200 c = 41.912053
201 d = 9.8247004
202 e = 0.28175407
203 f = -1.1878455
204 g = -0.18014349
205 h = 0.14710899
206 i = -0.017046845
207 return (
208 a
209 + b * log10y
210 + c * math.pow(log10y, 2)
211 + d * math.pow(log10y, 3)
212 + e * math.pow(log10y, 4)
213 + f * math.pow(log10y, 5)
214 + g * math.pow(log10y, 6)
215 + h * math.pow(log10y, 7)
216 + i * math.pow(log10y, 8)
217 )
218 logj = math.log(j)
219 a = -1.3011877
220 b = -2.5840191e-2
221 c = 8.0242636e-2
222 d = -1.0320229e-1
223 e = 1.3646699e-1
224 f = 2.8745620e-2
225 g = -2.5468404e-2
226 h = -3.1978977e-3
227 k = 1.2992634e-4
228 m = 1.3635334e-3
229 return (
230 a
231 + c * logj
232 + e * math.pow(logj, 2)
233 + g * math.pow(logj, 3)
234 + m * math.pow(logj, 4)
235 ) / (
236 1
237 + b * logj
238 + d * math.pow(logj, 2)
239 + f * math.pow(logj, 3)
240 + h * math.pow(logj, 4)
241 + k * math.pow(logj, 5)
242 )
243
244
245 class HLG:
246 """Hybrid Log Gamma (HLG) as defined in Rec BT.2100 and BT.2390-4.
247
248 Args:
249 black_cdm2 (float): Black level in cd/m², defaults to 0.0.
250 white_cdm2 (float): White level in cd/m², defaults to 1000.0.
251 system_gamma (float): System gamma for nominal peak luminance and
252 ambient, defaults to 1.2.
253 ambient_cdm2 (float): Ambient luminance in cd/m², defaults to 5.
254 rgb_space (str): RGB color space, defaults to "Rec. 2020".
255 """
256
257 def __init__(
258 self,
259 black_cdm2: float = 0.0,
260 white_cdm2: float = 1000.0,
261 system_gamma: float = 1.2,
262 ambient_cdm2: float = 5,
263 rgb_space: str = "Rec. 2020",
264 ) -> None:
265 self.black_cdm2 = black_cdm2
266 self.white_cdm2 = white_cdm2
267 self.rgb_space = get_rgb_space(rgb_space)
268 self.system_gamma = system_gamma
269 self.ambient_cdm2 = ambient_cdm2
270
271 @property
272 def gamma(self) -> float:
273 """System gamma for nominal peak luminance and ambient.
274
275 Returns:
276 float: Adjusted system gamma based on peak luminance and ambient
277 luminance.
278 """
279 # Adjust system gamma for peak luminance != 1000 cd/m2 (extended model
280 # described in BT.2390-4)
281 k = 1.111
282 gamma = self.system_gamma * k ** math.log(self.white_cdm2 / 1000.0, 2)
283 if self.ambient_cdm2 > 0:
284 # Adjust system gamma for ambient surround != 5 cd/m2 (BT.2390-4)
285 u = 0.98
286 gamma *= u ** math.log(self.ambient_cdm2 / 5.0, 2)
287 return gamma
288
289 def oetf(self, v: float, inverse: bool = False) -> float:
290 """Hybrid Log Gamma (HLG) OETF.
291
292 Relative scene linear light to non-linear HLG signal, or inverse
293
294 Input domain 0..1
295 Output range 0..1
296
297 Args:
298 v (float): Relative scene linear light or non-linear HLG signal.
299 inverse (bool): If True, apply inverse OETF.
300
301 Returns:
302 float: Non-linear HLG signal if inverse is False, or relative scene
303 linear light if inverse is True.
304 """
305 if v == 1:
306 return 1.0
307 a = 0.17883277
308 b = 1 - 4 * a
309 c = 0.5 - a * math.log(4 * a)
310 if inverse:
311 # Non-linear HLG signal to relative scene linear light
312 if 0 <= v <= 1 / 2.0:
313 v = v**2 / 3.0
314 else:
315 v = (math.exp((v - c) / a) + b) / 12.0
316 else:
317 # Relative scene linear light to non-linear HLG signal
318 v = math.sqrt(3 * v) if 0 <= v <= 1 / 12.0 else a * math.log(12 * v - b) + c
319 return v
320
321 @overload
322 def eotf(
323 self,
324 RGB: float, # noqa: N803
325 inverse: bool = False,
326 apply_black_offset: bool = True,
327 ) -> float: ...
328
329 @overload
330 def eotf(
331 self,
332 RGB: tuple[float, float, float], # noqa: N803
333 inverse: bool = False,
334 apply_black_offset: bool = True,
335 ) -> tuple[float, float, float]: ...
336
337 def eotf(
338 self,
339 RGB: float | tuple[float, float, float], # noqa: N803
340 inverse: bool = False,
341 apply_black_offset: bool = True,
342 ) -> float | tuple[float, float, float]:
343 """Hybrid Log Gamma (HLG) EOTF.
344
345 Non-linear HLG signal to display light, or inverse
346
347 Input domain 0..1
348 Output range 0..1
349
350 Args:
351 RGB (float | tuple[float, float, float]): R, G, B components of the
352 non-linear HLG signal or display light.
353 inverse (bool): If True, apply inverse EOTF.
354 apply_black_offset (bool): Whether to apply black offset, defaults
355 to True.
356
357 Returns:
358 float | tuple[float, float, float]: G component of the display
359 light if RGB is a float, or R, G, B components of the display
360 light if RGB is a tuple.
361 """
362 if isinstance(RGB, (float, int)):
363 r, g, b = (RGB,) * 3
364 else:
365 r, g, b = RGB
366 if inverse:
367 # Display light -> relative scene linear light -> HLG signal
368 r, g, b = (
369 self.oetf(v) for v in self.ootf((r, g, b), True, apply_black_offset)
370 )
371 else:
372 # HLG signal -> relative scene linear light -> display light
373 r, g, b = self.ootf(
374 [self.oetf(v, True) for v in (r, g, b)], False, apply_black_offset
375 )
376 return g if isinstance(RGB, (float, int)) else (r, g, b)
377
378 @overload
379 def ootf(
380 self,
381 RGB: float, # noqa: N803
382 inverse: bool = False,
383 apply_black_offset: bool = True,
384 ) -> float: ...
385
386 @overload
387 def ootf(
388 self,
389 RGB: tuple[float, float, float], # noqa: N803
390 inverse: bool = False,
391 apply_black_offset: bool = True,
392 ) -> tuple[float, float, float]: ...
393
394 def ootf(
395 self,
396 RGB: float | tuple[float, float, float], # noqa: N803
397 inverse: bool = False,
398 apply_black_offset: bool = True,
399 ) -> float | tuple[float, float, float]:
400 """Hybrid Log Gamma (HLG) OOTF.
401
402 Relative scene linear light to display light, or inverse
403
404 Input domain 0..1
405 Output range 0..1
406
407 Args:
408 RGB (float | tuple[float, float, float]): R, G, B components of the
409 relative scene linear light or non-linear HLG signal.
410 inverse (bool): If True, apply inverse OOTF.
411 apply_black_offset (bool): Whether to apply black offset, defaults
412 to True.
413
414 Returns:
415 float | tuple[float, float, float]: G component of the display
416 light if RGB is a float, or R, G, B components of the display
417 light if RGB is a tuple.
418 """
419 r, g, b = (RGB,) * 3 if isinstance(RGB, (float, int)) else RGB
420 black_cdm2 = float(self.black_cdm2) if apply_black_offset else 0
421 alpha = (self.white_cdm2 - black_cdm2) / self.white_cdm2
422 beta = black_cdm2 / self.white_cdm2
423 y = 0.2627 * r + 0.6780 * g + 0.0593 * b
424 if inverse:
425 if beta < y:
426 r, g, b = (
427 ((y - beta) / alpha) ** ((1 - self.gamma) / self.gamma)
428 * ((v - beta) / alpha)
429 for v in (r, g, b)
430 )
431 else:
432 r, g, b = 0, 0, 0
433 else:
434 if y:
435 y **= self.gamma - 1
436 r, g, b = (alpha * y * e + beta for e in (r, g, b))
437 return g if isinstance(RGB, (float, int)) else (r, g, b)
438
439 def RGB2XYZ( # noqa: N802
440 self,
441 R: float, # noqa: N803
442 G: float, # noqa: N803
443 B: float, # noqa: N803
444 apply_black_offset: bool = True,
445 ) -> tuple[float, float, float]:
446 """Non-linear HLG signal to display XYZ.
447
448 Args:
449 R (float): R component of the non-linear HLG signal.
450 G (float): G component of the non-linear HLG signal.
451 B (float): B component of the non-linear HLG signal.
452 apply_black_offset (bool): Whether to apply black offset, defaults
453 to True.
454
455 Returns:
456 tuple[float, float, float]: X, Y, Z components of the display XYZ.
457 """
458 x, y, z = self.rgb_space[-1] * [self.oetf(v, True) for v in (R, G, B)]
459 x, y, z = (max(v, 0) for v in (x, y, z))
460 yy = self.ootf(y, apply_black_offset=False)
461 if y:
462 x, y, z = (v / y * yy for v in (x, y, z))
463 else:
464 x, y, z = (v * yy for v in self.rgb_space[1])
465 if apply_black_offset:
466 beta = self.ootf(0)
467 bp_out = [v * beta for v in self.rgb_space[1]]
468 x, y, z = apply_bpc(x, y, z, (0, 0, 0), bp_out, self.rgb_space[1])
469 return x, y, z
470
471 def XYZ2RGB( # noqa: N802
472 self,
473 X: float, # noqa: N803
474 Y: float, # noqa: N803
475 Z: float, # noqa: N803
476 apply_black_offset: bool = True,
477 ) -> tuple[float, float, float]:
478 """Display XYZ to non-linear HLG signal.
479
480 Args:
481 X (float): X component of the XYZ color value.
482 Y (float): Y component of the XYZ color value.
483 Z (float): Z component of the XYZ color value.
484 apply_black_offset (bool): Whether to apply black offset, defaults
485 to True.
486
487 Returns:
488 tuple[float, float, float]: R, G, B components of the non-linear
489 HLG signal.
490 """
491 if apply_black_offset:
492 beta = self.ootf(0)
493 bp_in = [v * beta for v in self.rgb_space[1]]
494 X, Y, Z = apply_bpc(X, Y, Z, bp_in, (0, 0, 0), self.rgb_space[1]) # noqa: N806
495 yy = self.ootf(Y, True, apply_black_offset=False)
496 if Y:
497 X, Y, Z = (v / Y * yy for v in (X, Y, Z)) # noqa: N806
498 r, g, b = self.rgb_space[-1].inverted() * (X, Y, Z)
499 r, g, b = (max(v, 0) for v in (r, g, b))
500 r, g, b = [self.oetf(v) for v in (r, g, b)]
501 return r, g, b
502
503
504 rgb_spaces = {
505 "ACES": (
506 1.0,
507 (0.95265, 1.0, 1.00883),
508 (0.7347, 0.2653, 0.343961),
509 (0.0000, 1.0000, 0.728164),
510 (0.0001, -0.0770, -0.072125),
511 ),
512 "ACEScg": (
513 1.0,
514 (0.95265, 1.0, 1.00883),
515 (0.7130, 0.2930, 0.272230),
516 (0.1650, 0.8300, 0.674080),
517 (0.1280, 0.0440, 0.053690),
518 ),
519 "Adobe RGB (1998)": (
520 2 + 51 / 256.0,
521 "D65",
522 (0.6400, 0.3300, 0.297361),
523 (0.2100, 0.7100, 0.627355),
524 (0.1500, 0.0600, 0.075285),
525 ),
526 "Apple RGB": (
527 1.8,
528 "D65",
529 (0.6250, 0.3400, 0.244634),
530 (0.2800, 0.5950, 0.672034),
531 (0.1550, 0.0700, 0.083332),
532 ),
533 "Best RGB": (
534 2.2,
535 "D50",
536 (0.7347, 0.2653, 0.228457),
537 (0.2150, 0.7750, 0.737352),
538 (0.1300, 0.0350, 0.034191),
539 ),
540 "Beta RGB": (
541 2.2,
542 "D50",
543 (0.6888, 0.3112, 0.303273),
544 (0.1986, 0.7551, 0.663786),
545 (0.1265, 0.0352, 0.032941),
546 ),
547 "Bruce RGB": (
548 2.2,
549 "D65",
550 (0.6400, 0.3300, 0.240995),
551 (0.2800, 0.6500, 0.683554),
552 (0.1500, 0.0600, 0.075452),
553 ),
554 "CIE RGB": (
555 2.2,
556 "E",
557 (0.7350, 0.2650, 0.176204),
558 (0.2740, 0.7170, 0.812985),
559 (0.1670, 0.0090, 0.010811),
560 ),
561 "ColorMatch RGB": (
562 1.8,
563 "D50",
564 (0.6300, 0.3400, 0.274884),
565 (0.2950, 0.6050, 0.658132),
566 (0.1500, 0.0750, 0.066985),
567 ),
568 # "DCDM X'Y'Z'": (
569 # 2.6,
570 # "E",
571 # (1.0000, 0.0000, 0.000000),
572 # (0.0000, 1.0000, 1.000000),
573 # (0.0000, 0.0000, 0.000000)
574 # ),
575 "DCI P3": (
576 2.6,
577 (0.89459, 1.0, 0.95442),
578 (0.6800, 0.3200, 0.209475),
579 (0.2650, 0.6900, 0.721592),
580 (0.1500, 0.0600, 0.068903),
581 ),
582 "DCI P3 D65": (
583 2.6,
584 "D65",
585 (0.6800, 0.3200, 0.209475),
586 (0.2650, 0.6900, 0.721592),
587 (0.1500, 0.0600, 0.068903),
588 ),
589 "Don RGB 4": (
590 2.2,
591 "D50",
592 (0.6960, 0.3000, 0.278350),
593 (0.2150, 0.7650, 0.687970),
594 (0.1300, 0.0350, 0.033680),
595 ),
596 "ECI RGB": (
597 1.8,
598 "D50",
599 (0.6700, 0.3300, 0.320250),
600 (0.2100, 0.7100, 0.602071),
601 (0.1400, 0.0800, 0.077679),
602 ),
603 "ECI RGB v2": (
604 -3.0,
605 "D50",
606 (0.6700, 0.3300, 0.320250),
607 (0.2100, 0.7100, 0.602071),
608 (0.1400, 0.0800, 0.077679),
609 ),
610 "Ekta Space PS5": (
611 2.2,
612 "D50",
613 (0.6950, 0.3050, 0.260629),
614 (0.2600, 0.7000, 0.734946),
615 (0.1100, 0.0050, 0.004425),
616 ),
617 "NTSC 1953": (
618 2.2,
619 "C",
620 (0.6700, 0.3300, 0.298839),
621 (0.2100, 0.7100, 0.586811),
622 (0.1400, 0.0800, 0.114350),
623 ),
624 "PAL/SECAM": (
625 2.2,
626 "D65",
627 (0.6400, 0.3300, 0.222021),
628 (0.2900, 0.6000, 0.706645),
629 (0.1500, 0.0600, 0.071334),
630 ),
631 "ProPhoto RGB": (
632 1.8,
633 "D50",
634 (0.7347, 0.2653, 0.288040),
635 (0.1596, 0.8404, 0.711874),
636 (0.0366, 0.0001, 0.000086),
637 ),
638 "Rec. 709": (
639 -709,
640 "D65",
641 (0.6400, 0.3300, 0.212656),
642 (0.3000, 0.6000, 0.715158),
643 (0.1500, 0.0600, 0.072186),
644 ),
645 "Rec. 2020": (
646 -709,
647 "D65",
648 (0.7080, 0.2920, 0.262694),
649 (0.1700, 0.7970, 0.678009),
650 (0.1310, 0.0460, 0.059297),
651 ),
652 "SMPTE-C": (
653 2.2,
654 "D65",
655 (0.6300, 0.3400, 0.212395),
656 (0.3100, 0.5950, 0.701049),
657 (0.1550, 0.0700, 0.086556),
658 ),
659 "SMPTE 240M": (
660 -240,
661 "D65",
662 (0.6300, 0.3400, 0.212395),
663 (0.3100, 0.5950, 0.701049),
664 (0.1550, 0.0700, 0.086556),
665 ),
666 "sRGB": (
667 -2.4,
668 "D65",
669 (0.6400, 0.3300, 0.212656),
670 (0.3000, 0.6000, 0.715158),
671 (0.1500, 0.0600, 0.072186),
672 ),
673 "Wide Gamut RGB": (
674 2.2,
675 "D50",
676 (0.7350, 0.2650, 0.258187),
677 (0.1150, 0.8260, 0.724938),
678 (0.1570, 0.0180, 0.016875),
679 ),
680 }
681 """
682 http://brucelindbloom.com/WorkingSpaceInfo.html
683 ACES: https://github.com/ampas/aces-dev/blob/master/docs/ACES_1.0.1.pdf?raw=true
684 Adobe RGB: http://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
685 DCI P3: http://www.hp.com/united-states/campaigns/workstations/pdfs/lp2480zx-dci--p3-emulation.pdf
686 http://dcimovies.com/specification/DCI_DCSS_v12_with_errata_2012-1010.pdf
687 Rec. 2020: http://en.wikipedia.org/wiki/Rec._2020
688
689 name gamma white primaries
690 point Rx Ry RY Gx Gy GY Bx By BY
691 """ # noqa: E501
692
693
694 @cache
695 def get_cat_matrix(
696 cat: str | bytes | list | tuple | Matrix3x3 = "Bradford",
697 ) -> Matrix3x3:
698 """Get chromatic adaption matrix.
699
700 Args:
701 cat (bytes | str | list | tuple | Matrix3x3): Chromatic adaption matrix
702 name or instance. Defaults to "Bradford".
703
704 Returns:
705 Matrix3x3: Chromatic adaption matrix.
706 """
707 if isinstance(cat, str):
708 cat = CAT_MATRICES[cat]
709 elif isinstance(cat, bytes):
710 cat = CAT_MATRICES[cat.decode()]
711 if not isinstance(cat, Matrix3x3):
712 cat = Matrix3x3(cat)
713 return cat
714
715
716 def cbrt(x: float) -> float:
717 """Cube root.
718
719 Args:
720 x (float): Input value.
721
722 Returns:
723 float: Cube root of x.
724 """
725 return math.pow(x, 1.0 / 3.0) if x >= 0 else -math.pow(-x, 1.0 / 3.0)
726
727
728 def var(a: list[float]) -> float:
729 """Variance.
730
731 Args:
732 a (list[float]): List of numbers.
733
734 Returns:
735 float: Variance of the numbers in the list.
736 """
737 s = 0.0
738 l = len(a)
739 while l:
740 l -= 1
741 s += a[l]
742 l = len(a)
743 m = s / l
744 s = 0.0
745 while l:
746 l -= 1
747 s += (a[l] - m) ** 2
748 return s / len(a)
749
750
751 def XYZ2LMS( # noqa: N802
752 X: float, # noqa: N803
753 Y: float, # noqa: N803
754 Z: float, # noqa: N803
755 cat: str = "Bradford",
756 ) -> tuple[float, float, float]:
757 """Convert from XYZ to cone response domain.
758
759 Args:
760 X (float): X component of the XYZ color value.
761 Y (float): Y component of the XYZ color value.
762 Z (float): Z component of the XYZ color value.
763 cat (str): Chromatic adaptation transform, defaults to 'Bradford'.
764
765 Returns:
766 tuple[float, float, float]: L, M, S components of the LMS color value.
767 """
768 cat = get_cat_matrix(cat)
769 p, y, b = cat * [X, Y, Z]
770 return p, y, b
771
772
773 def LMS_wp_adaption_matrix( # noqa: N802
774 whitepoint_source: None | float | str | list | tuple = None,
775 whitepoint_destination: None | float | str | list | tuple = None,
776 cat: str = "Bradford",
777 ) -> Matrix3x3:
778 """Prepare a matrix to match the whitepoints in cone response domain.
779
780 Args:
781 whitepoint_source (None | float | str | list | tuple): Source white
782 point, defaults to None.
783 whitepoint_destination (None | float | str | list | tuple): Destination
784 white point, defaults to None.
785 cat (str): Chromatic adaptation transform, defaults to 'Bradford'.
786
787 Returns:
788 Matrix3x3: Matrix to adapt source whitepoint to destination in LMS.
789 """
790 # chromatic adaption
791 # based on formula http://brucelindbloom.com/Eqn_ChromAdapt.html
792 # cat = adaption matrix or predefined choice ('CAT02', 'Bradford',
793 # 'Von Kries', 'XYZ Scaling', see CAT_MATRICES), defaults to 'Bradford'
794 cat = get_cat_matrix(cat)
795 xyz_ws = get_whitepoint(whitepoint_source)
796 xyz_wd = get_whitepoint(whitepoint_destination)
797 if xyz_ws[1] <= 1.0 < xyz_wd[1]:
798 # make sure the scaling is identical
799 xyz_wd = [v / xyz_wd[1] * xyz_ws[1] for v in xyz_wd]
800 if xyz_wd[1] <= 1.0 < xyz_ws[1]:
801 # make sure the scaling is identical
802 xyz_ws = [v / xyz_ws[1] * xyz_wd[1] for v in xyz_ws]
803 ls, ms, ss = XYZ2LMS(xyz_ws[0], xyz_ws[1], xyz_ws[2], cat)
804 ld, md, dd = XYZ2LMS(xyz_wd[0], xyz_wd[1], xyz_wd[2], cat)
805 return Matrix3x3([[ld / ls, 0, 0], [0, md / ms, 0], [0, 0, dd / ss]])
806
807
808 @cache
809 def wp_adaption_matrix(
810 whitepoint_source: None | float | str | list | tuple = None,
811 whitepoint_destination: None | float | str | list | tuple = None,
812 cat: str = "Bradford",
813 ) -> Matrix3x3:
814 """Return matrix to adapt source whitepoint to destination in XYZ.
815
816 Args:
817 whitepoint_source (None | float | str | list | tuple): Source white
818 point, defaults to None.
819 whitepoint_destination (None | float | str | list | tuple): Destination
820 white point, defaults to None.
821 cat (str): Chromatic adaptation transform, defaults to 'Bradford'.
822
823 Returns:
824 Matrix3x3: Matrix to adapt source whitepoint to destination.
825 """
826 # chromatic adaption
827 # based on formula http://brucelindbloom.com/Eqn_ChromAdapt.html
828 # cat = adaption matrix or predefined choice ('CAT02', 'Bradford',
829 # 'Von Kries', 'XYZ Scaling', see CAT_MATRICES), defaults to 'Bradford'
830 cat = get_cat_matrix(cat)
831 return (
832 cat.inverted()
833 * LMS_wp_adaption_matrix(whitepoint_source, whitepoint_destination, cat)
834 * cat
835 )
836
837
838 def adapt(
839 X: float, # noqa: N803
840 Y: float, # noqa: N803
841 Z: float, # noqa: N803
842 whitepoint_source: None | float | str | list | tuple = None,
843 whitepoint_destination: None | float | str | list | tuple = None,
844 cat: str = "Bradford",
845 ) -> tuple[float, float, float]:
846 """Transform XYZ under source illuminant to XYZ under destination illuminant.
847
848 Args:
849 X (float): X value.
850 Y (float): Y value.
851 Z (float): Z value.
852 whitepoint_source (None | float | str | list | tuple): Source white
853 point, defaults to None.
854 whitepoint_destination (None | float | str | list | tuple): Destination
855 white point, defaults to None.
856 cat (str): Chromatic adaptation transform, defaults to 'Bradford'.
857
858 Returns:
859 tuple[float, float, float]: Adapted X, Y, Z values.
860 """
861 # chromatic adaption
862 # based on formula http://brucelindbloom.com/Eqn_ChromAdapt.html
863 # cat = adaption matrix or predefined choice ('CAT02', 'Bradford',
864 # 'Von Kries', 'XYZ Scaling', see CAT_MATRICES), defaults to 'Bradford'
865 return wp_adaption_matrix(whitepoint_source, whitepoint_destination, cat) * (
866 X,
867 Y,
868 Z,
869 )
870
871
872 def apply_bpc(
873 X: float, # noqa: N803
874 Y: float, # noqa: N803
875 Z: float, # noqa: N803
876 bp_in: None | tuple = None,
877 bp_out: None | tuple = None,
878 wp_out: None | float | str | list | tuple = "D50",
879 weight: bool = False,
880 pin_chromaticity: bool = False,
881 ) -> tuple[float, float, float]:
882 """Apply black point compensation.
883
884 Args:
885 X (float): X value
886 Y (float): Y value
887 Z (float): Z value
888 bp_in (tuple): Input black point
889 bp_out (tuple): Output black point
890 wp_out (str or tuple): Output white point
891 weight (bool): Whether to apply weight
892 pin_chromaticity (bool): Whether to pin chromaticity
893
894 Returns:
895 tuple[float, float, float]: Adjusted X, Y, Z values.
896 """
897 if not bp_in:
898 bp_in = (0, 0, 0)
899 if not bp_out:
900 bp_out = (0, 0, 0)
901 wp_out = get_whitepoint(wp_out)
902 if weight:
903 l = XYZ2Lab(*[v * 100 for v in (X, Y, Z)])[0]
904 bp_in_lab = XYZ2Lab(*[v * 100 for v in bp_in])
905 bp_out_lab = XYZ2Lab(*[v * 100 for v in bp_out])
906 vv = (l - bp_in_lab[0]) / (100.0 - bp_in_lab[0]) # 0 at bp, 1 at wp
907 vv = 1.0 - vv
908 if vv < 0.0:
909 vv = 0.0
910 elif vv > 1.0:
911 vv = 1.0
912 vv = math.pow(vv, min(40.0, 40.0 / (max(bp_in_lab[0], bp_out_lab[0]) or 1.0)))
913 bp_in = Lab2XYZ(*[v * vv for v in bp_in_lab])
914 bp_out = Lab2XYZ(*[v * vv for v in bp_out_lab])
915 if pin_chromaticity:
916 XYZ = [Y] # noqa: N806
917 x, y = XYZ2xyY(X, Y, Z, wp_out)[:2]
918 bp_in = bp_in[1:2]
919 bp_out = bp_out[1:2]
920 wp_out = wp_out[1:2]
921 else:
922 XYZ = [X, Y, Z] # noqa: N806
923 for i, v in enumerate(XYZ):
924 XYZ[i] = ((wp_out[i] - bp_out[i]) * v - wp_out[i] * (bp_in[i] - bp_out[i])) / ( # noqa: N806
925 wp_out[i] - bp_in[i]
926 )
927 if pin_chromaticity:
928 XYZ = xyY2XYZ(x, y, XYZ[0]) # noqa: N806
929 return XYZ
930
931
932 def avg(*args: list[float]) -> float:
933 """Average of a list of numbers.
934
935 Args:
936 *args (list[float]): A list of numbers.
937
938 Returns:
939 float: Average of the numbers.
940 """
941 return float(sum(args)) / len(args)
942
943
944 def blend_ab(
945 X: float, # noqa: N803
946 Y: float, # noqa: N803
947 Z: float, # noqa: N803
948 bp: tuple,
949 wp: tuple,
950 power: float = 40.0,
951 signscale: float = 1,
952 ) -> tuple[float, float, float]:
953 """Blend to destination black as L approaches black.
954
955 Args:
956 X (float): X value
957 Y (float): Y value
958 Z (float): Z value
959 bp (tuple): Black point
960 wp (tuple): White point
961 power (float): Power for blending
962 signscale (int): Sign scale for blending
963
964 Returns:
965 tuple[float, float, float]: Blended X, Y, Z values
966 """
967 if Y < 0:
968 return 0, 0, 0
969 l, a, b = XYZ2Lab(X, Y, Z, whitepoint=wp)
970 bpl, bpa, bpb = XYZ2Lab(*bp, whitepoint=wp)
971 if bpl == 100:
972 raise ValueError("Black L* is 100!")
973 vv = (l - bpl) / (100.0 - bpl) # 0 at bp, 1 at wp
974 vv = 1.0 - vv # 1 at bp, 0 at wp
975 if vv < 0.0:
976 vv = 0.0
977 elif vv > 1.0:
978 vv = 1.0
979 vv = math.pow(vv, power) * signscale
980 a += vv * bpa
981 b += vv * bpb
982 return Lab2XYZ(l, a, b, whitepoint=wp)
983
984
985 def blend_blackpoint(
986 X: float, # noqa: N803
987 Y: float, # noqa: N803
988 Z: float, # noqa: N803
989 bp_in: None | tuple = None,
990 bp_out: None | tuple = None,
991 wp: None | float | str | list | tuple = None,
992 power: float = 40.0,
993 pin_chromaticity: bool = False,
994 ) -> tuple[float, float, float]:
995 """Blend to destination black as L approaches black, with optional input black compensation.
996
997 Args:
998 X (float): X value
999 Y (float): Y value
1000 Z (float): Z value
1001 bp_in (tuple): Input black point
1002 bp_out (tuple): Output black point
1003 wp (str or tuple): White point, defaults to "D50"
1004 power (float): Power for blending, defaults to 40.0
1005 pin_chromaticity (bool): Whether to pin chromaticity, defaults to False.
1006
1007 Returns:
1008 tuple[float, float, float]: Adjusted X, Y, Z values.
1009 """ # noqa: E501
1010 wp = get_whitepoint(wp)
1011
1012 for i, bp in enumerate((bp_in, bp_out)):
1013 if not bp or tuple(bp) == (0, 0, 0):
1014 continue
1015 bp_wp = tuple(v / wp[1] * bp[1] for v in wp)
1016 if i == 0:
1017 X, Y, Z = blend_ab(X, Y, Z, bp, wp, power, -1) # noqa: N806
1018 X, Y, Z = apply_bpc(X, Y, Z, bp_wp, None, wp, pin_chromaticity) # noqa: N806
1019 else:
1020 X, Y, Z = apply_bpc(X, Y, Z, None, bp_wp, wp, pin_chromaticity) # noqa: N806
1021 X, Y, Z = blend_ab(X, Y, Z, bp, wp, power, 1) # noqa: N806
1022
1023 return X, Y, Z
1024
1025
1026 def interp_old(
1027 x: float,
1028 xp: list,
1029 fp: list,
1030 left: None | float = None,
1031 right: None | float = None,
1032 ) -> float:
1033 """One-dimensional linear interpolation similar to numpy.interp.
1034
1035 Values do NOT have to be monotonically increasing
1036 interp(0, [0, 0], [0, 1]) will return 0.
1037
1038 Args:
1039 x (float): The x value to interpolate.
1040 xp (list): The x-coordinates of the data points.
1041 fp (list): The y-coordinates of the data points.
1042 left (float, optional): Value to return for x < xp[0]. Defaults to None.
1043 right (float, optional): Value to return for x > xp[-1]. Defaults to None.
1044
1045 Returns:
1046 float: Interpolated value.
1047 """
1048 if not isinstance(x, (int, float, complex)):
1049 return [interp_old(n, xp, fp, left, right) for n in x]
1050 if x in xp:
1051 return fp[xp.index(x)]
1052 if x < xp[0]:
1053 return fp[0] if left is None else left
1054 if x > xp[-1]:
1055 return fp[-1] if right is None else right
1056 # Interpolate
1057 lower = 0
1058 higher = len(fp) - 1
1059 for i, v in enumerate(xp):
1060 if v < x and i > lower:
1061 lower = i
1062 elif v > x and i < higher:
1063 higher = i
1064 step = float(x - xp[lower])
1065 steps = (xp[higher] - xp[lower]) / step
1066 return fp[lower] + (fp[higher] - fp[lower]) / steps
1067
1068
1069 # This is much faster than the old implementation
1070 def interp(
1071 x: float | list,
1072 xp: list,
1073 fp: list,
1074 left: None | float = None,
1075 right: None | float = None,
1076 period: None | float = None,
1077 ) -> float | list:
1078 """One-dimensional linear interpolation similar to numpy.interp.
1079
1080 Values do NOT have to be monotonically increasing
1081 interp(0, [0, 0], [0, 1]) will return 0
1082
1083 Args:
1084 x (float or list): The x value(s) to interpolate.
1085 xp (list): The x-coordinates of the data points.
1086 fp (list): The y-coordinates of the data points.
1087 left (float, optional): Value to return for x < xp[0]. Defaults to None.
1088 right (float, optional): Value to return for x > xp[-1]. Defaults to None.
1089 period (float, optional): Periodicity of the interpolation. Defaults to None.
1090
1091 Returns:
1092 float | list: Interpolated value(s).
1093 """
1094 # TODO: This function overrides the class implementation (Interp) and forces to use
1095 # numpy.interp all the time, and it is kind of rude in that manner.
1096 # Please respect the previous implementation, but use nump.interp again.
1097 return numpy.interp(x, xp, fp, left, right, period)
1098
1099
1100 def interp_resize(iterable: list, new_size: int, use_numpy: bool = False) -> list:
1101 """Change size of iterable through linear interpolation.
1102
1103 Args:
1104 iterable (list): A list of float values.
1105 new_size (int): New size of the list
1106 use_numpy (bool): Use numpy for interpolation. Defaults to False.
1107
1108 Returns:
1109 list: Interpolated values.
1110 """
1111 # interp = Interp(list(range(len(iterable))), iterable, use_numpy=use_numpy)
1112 return [
1113 interp(
1114 i / (new_size - 1.0) * (len(iterable) - 1.0),
1115 list(range(len(iterable))),
1116 iterable,
1117 )
1118 for i in range(new_size)
1119 ]
1120
1121
1122 def interp_fill(xp: list, fp: list, new_size: int, use_numpy: bool = False) -> list:
1123 """Fill missing points by interpolation.
1124
1125 Args:
1126 xp (list): X values
1127 fp (list): Y values
1128 new_size (int): New size of the list
1129 use_numpy (bool): Use numpy for interpolation. Defaults to False.
1130
1131 Returns:
1132 list: Interpolated values.
1133 """
1134 # interp = Interp(xp, fp, use_numpy=use_numpy)
1135 return [interp(i / (new_size - 1.0) * xp[-1], xp, fp) for i in range(new_size)]
1136
1137
1138 def smooth_avg_old(
1139 values: list,
1140 passes: int = 1,
1141 window: None | tuple | list = None,
1142 protect: None | list = None,
1143 ) -> list:
1144 """Smooth values (moving average).
1145
1146 Args:
1147 values (list): A list of float values.
1148 passes (int): Number of passes
1149 window (tuple/list): Tuple or list containing weighting factors. Its length
1150 determines the size of the window to use. Defaults to (1.0, 1.0, 1.0)
1151 protect (list): A list of indices to protect. The values related to these
1152 indices will be protected.
1153
1154 Returns:
1155 list: Smoothed values.
1156 """
1157 if not window or len(window) < 3 or len(window) % 2 != 1:
1158 if window:
1159 warnings.warn(
1160 f"Invalid window {window!r}, size {len(window)} "
1161 "- using default (1, 1, 1)",
1162 Warning,
1163 stacklevel=2,
1164 )
1165 window = (1.0, 1.0, 1.0)
1166 for _x in range(passes):
1167 data = []
1168 for j, v in enumerate(values):
1169 tmp_window = window
1170 if not protect or j not in protect:
1171 while 0 < j < len(values) - 1 and len(tmp_window) >= 3:
1172 tl = (len(tmp_window) - 1) / 2
1173 # print j, tl, tmp_window
1174 if tl > 0 and j - tl >= 0 and j + tl <= len(values) - 1:
1175 windowslice = values[int(j - tl) : int(j + tl + 1)]
1176 windowsize = 0
1177 for k, weight in enumerate(tmp_window):
1178 windowsize += float(weight) * windowslice[k]
1179 v = windowsize / sum(tmp_window)
1180 break
1181 tmp_window = tmp_window[1:-1]
1182 data.append(v)
1183 values = data
1184 return values
1185
1186
1187 def smooth_avg(
1188 values: list,
1189 passes: int = 1,
1190 window: None | tuple[float, float, float] | list = None,
1191 protect: None | list = None,
1192 ) -> list:
1193 """Smooth values fast (moving average).
1194
1195 This is (should be) the fast implementation of the ``smooth_avg``. Inputs are the
1196 same.
1197
1198 Args:
1199 values (list): A list of float values.
1200 passes (int): Number of passes
1201 window (tuple/list): Tuple or list containing weighting factors. Its length
1202 determines the size of the window to use. Defaults to (1.0, 1.0, 1.0)
1203 protect (list): A list of indices to protect. The values related to these
1204 indices will be restored after each pass.
1205
1206 Returns:
1207 list: Smoothed values.
1208 """
1209 if not window or len(window) < 3 or len(window) % 2 != 1:
1210 if window:
1211 warnings.warn(
1212 f"Invalid window {window!r}, size {len(window)} "
1213 "- using default (1, 1, 1)",
1214 Warning,
1215 stacklevel=2,
1216 )
1217 window = (1, 1, 1)
1218 # fix the window values
1219 window_length = float(len(window))
1220 window_weight = sum(window)
1221 window = tuple([i / window_weight for i in window])
1222
1223 # extend the array by ceil(window_size / 2)
1224 extend_amount = math.ceil(window_length / 2)
1225
1226 # protect start and end values by adding the first and last values by the half of
1227 # the window length
1228 values = values[0:1] * extend_amount + values + values[-1:] * extend_amount
1229
1230 protection_extension = 1
1231 protected_start = values[: extend_amount + protection_extension]
1232 protected_end = values[-extend_amount - protection_extension :]
1233
1234 protected_values = {}
1235 if protect is not None:
1236 for index in protect:
1237 # offset the values with ``extend_amount``
1238 protected_values[index + extend_amount] = values[index + extend_amount]
1239
1240 for _ in range(passes):
1241 values = list(numpy.convolve(values, window, mode="same"))
1242 # Protect start and end values
1243 values[: extend_amount + protection_extension] = protected_start
1244 values[-extend_amount - protection_extension :] = protected_end
1245
1246 # restore protected values
1247 if protect is not None:
1248 for k in protected_values:
1249 v = protected_values[k]
1250 values[k] = v
1251
1252 # return the non-extended portion
1253 return values[extend_amount:-extend_amount]
1254
1255
1256 def compute_bpc(
1257 bp_in: tuple[float, float, float],
1258 bp_out: tuple[float, float, float],
1259 ) -> tuple[Matrix3x3, list]:
1260 """Black point compensation. Implemented as a linear scaling in XYZ.
1261
1262 Black points should come relative to the white point. Fills and
1263 returns a matrix/offset element.
1264
1265 [matrix]*bp_in + offset = bp_out
1266 [matrix]*D50 + offset = D50
1267
1268 Args:
1269 bp_in (tuple[float, float, float]): Input black point in XYZ.
1270 bp_out (tuple[float, float, float]): Output black point in XYZ.
1271
1272 Returns:
1273 tuple[Matrix, list]: A tuple containing a Matrix3x3 and an offset list.
1274 The matrix is used to scale the input black point to the output
1275 black point, and the offset is used to adjust the output black
1276 point to the desired value.
1277 """
1278 # This is a linear scaling in the form ax+b, where
1279 # a = (bp_out - D50) / (bp_in - D50)
1280 # b = - D50* (bp_out - bp_in) / (bp_in - D50)
1281
1282 d50 = get_standard_illuminant("D50")
1283
1284 tx = bp_in[0] - d50[0]
1285 ty = bp_in[1] - d50[1]
1286 tz = bp_in[2] - d50[2]
1287
1288 ax = (bp_out[0] - d50[0]) / tx
1289 ay = (bp_out[1] - d50[1]) / ty
1290 az = (bp_out[2] - d50[2]) / tz
1291
1292 bx = -d50[0] * (bp_out[0] - bp_in[0]) / tx
1293 by = -d50[1] * (bp_out[1] - bp_in[1]) / ty
1294 bz = -d50[2] * (bp_out[2] - bp_in[2]) / tz
1295
1296 matrix = Matrix3x3([[ax, 0, 0], [0, ay, 0], [0, 0, az]])
1297 offset = [bx, by, bz]
1298 return matrix, offset
1299
1300
1301 def delta(
1302 L1: float, # noqa: N803
1303 a1: float,
1304 b1: float,
1305 L2: float, # noqa: N803
1306 a2: float,
1307 b2: float,
1308 method: str = "1976",
1309 p1: None | float = None,
1310 p2: None | float = None,
1311 p3: None | float = None,
1312 cie94_use_symmetric_chrominance: bool = True,
1313 ) -> dict:
1314 """Compute the delta of two samples.
1315
1316 - CIE 1994 & CMC calculation code derived from formulas on
1317 www.brucelindbloom.com
1318 - CIE 1994 code uses some alterations seen on
1319 www.farbmetrik-gall.de/cielab/korrcielab/cie94.html
1320 (see notes in code below)
1321 - CIE 2000 calculation code derived from Excel spreadsheet available at
1322 www.ece.rochester.edu/~gsharma/ciede2000
1323
1324 p1, p2, p3 arguments have different meaning for each calculation method:
1325
1326 CIE 1994: If p1 is not None, calculation will be adjusted for
1327 textiles, otherwise graphics arts (default if p1 is not set)
1328 CMC(l:c): p1 equals l (lightness) weighting factor and p2 equals c
1329 (chroma) weighting factor.
1330 Commonly used values are CMC(1:1) for perceptability
1331 (default if p1 and p2 are not set) and CMC(2:1) for
1332 acceptability
1333 CIE 2000: p1 becomes kL (lightness) weighting factor, p2 becomes
1334 kC (chroma) weighting factor and p3 becomes kH (hue)
1335 weighting factor (all three default to 1 if not set)
1336
1337 Args:
1338 L1 (float): Lightness of first sample
1339 a1 (float): a* value of first sample
1340 b1 (float): b* value of first sample
1341 L2 (float): Lightness of second sample
1342 a2 (float): a* value of second sample
1343 b2 (float): b* value of second sample
1344 method (str): Method to use for delta calculation.
1345 Can be "CIE94", "CMC", "CIE2K" or "CIE76". Defaults to "CIE76".
1346 p1 (float): Parameter 1
1347 - for CIE94, if not None, adjusts calculation for textiles,
1348 otherwise for graphics arts (default if p1 is not set)
1349 - for CMC, equals l (lightness) weighting factor (default if p1 is
1350 not set)
1351 - for CIE2K, equals kL (lightness) weighting factor (default if p1
1352 is not set)
1353 p2 (float): Parameter 2
1354 - for CIE94, not used (default if p2 is not set)
1355 - for CMC, equals c (chroma) weighting factor (default if p2 is not
1356 set)
1357 - for CIE2K, equals kC (chroma) weighting factor (default if p2 is
1358 not set)
1359 p3 (float): Parameter 3
1360 - for CIE94, not used (default if p3 is not set)
1361 - for CMC, not used (default if p3 is not set)
1362 - for CIE2K, equals kH (hue) weighting factor (default if p3 is not
1363 set)
1364 cie94_use_symmetric_chrominance (bool):
1365 If True, CIE94 will use symmetric chrominance calculation.
1366 If False, it will use asymmetric chrominance calculation.
1367 Defaults to True.
1368
1369 Returns:
1370 dict: A dictionary containing the delta E value and the method used.
1371 The dictionary will have the following keys:
1372 - "E": The calculated delta E value.
1373 - "L": The difference in lightness between the two samples.
1374 - "C": The difference in chroma between the two samples.
1375 - "H": The difference in hue between the two samples.
1376 - "a": The a* value of the first sample.
1377 - "b": The b* value of the first sample.
1378 - "Lw": The lightness difference adjusted for the method used.
1379 - "Cw": The chroma difference adjusted for the method used.
1380 - "Hw": The hue difference adjusted for the method used.
1381 """
1382 method = method.lower() if isinstance(method, str) else str(int(method))
1383 if method in ("94", "1994", "cie94", "cie1994"):
1384 textiles = p1
1385 dl = L2 - L1
1386 c1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
1387 c2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
1388 dc = c2 - c1
1389 dh2 = math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2) - math.pow(dc, 2)
1390 dh = math.sqrt(dh2) if dh2 > 0 else 0
1391 sl = 1.0
1392 k1 = 0.048 if textiles else 0.045
1393 k2 = 0.014 if textiles else 0.015
1394 c_ = math.sqrt(c1 * c2) if cie94_use_symmetric_chrominance else c1
1395 sc = 1.0 + k1 * c_
1396 sh = 1.0 + k2 * c_
1397 kl = 2.0 if textiles else 1.0
1398 kc = 1.0
1399 kh = 1.0
1400 dlw, dcw, dhw = dl / (kl * sl), dc / (kc * sc), dh / (kh * sh)
1401 de = math.sqrt(math.pow(dlw, 2) + math.pow(dcw, 2) + math.pow(dhw, 2))
1402 elif method in ("cmc(2:1)", "cmc21", "cmc(1:1)", "cmc11", "cmc"):
1403 if method in ("cmc(2:1)", "cmc21"):
1404 p1 = 2.0
1405 l = p1 if isinstance(p1, (float, int)) else 1.0
1406 c = p2 if isinstance(p2, (float, int)) else 1.0
1407 dl = L2 - L1
1408 c1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
1409 c2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
1410 dc = c2 - c1
1411 dh2 = math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2) - math.pow(dc, 2)
1412 dh = math.sqrt(dh2) if dh2 > 0 else 0
1413 sl = 0.511 if L1 < 16 else (0.040975 * L1) / (1 + 0.01765 * L1)
1414 sc = (0.0638 * c1) / (1 + 0.0131 * c1) + 0.638
1415 f = math.sqrt(math.pow(c1, 4) / (math.pow(c1, 4) + 1900.0))
1416 h1 = math.degrees(math.atan2(b1, a1)) + (0 if b1 >= 0 else 360.0)
1417 t = (
1418 0.56 + abs(0.2 * math.cos(math.radians(h1 + 168.0)))
1419 if 164 <= h1 <= 345
1420 else 0.36 + abs(0.4 * math.cos(math.radians(h1 + 35)))
1421 )
1422 sh = sc * (f * t + 1 - f)
1423 dlw, dcw, dhw = dl / (l * sl), dc / (c * sc), dh / sh
1424 de = math.sqrt(math.pow(dlw, 2) + math.pow(dcw, 2) + math.pow(dhw, 2))
1425 elif method in ("00", "2k", "2000", "cie00", "cie2k", "cie2000"):
1426 pow25_7 = math.pow(25, 7)
1427 k_l = p1 if isinstance(p1, (float, int)) else 1.0
1428 k_c = p2 if isinstance(p2, (float, int)) else 1.0
1429 k_h = p3 if isinstance(p3, (float, int)) else 1.0
1430 c1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
1431 c2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
1432 c_avg = avg(c1, c2)
1433 g = 0.5 * (1 - math.sqrt(math.pow(c_avg, 7) / (math.pow(c_avg, 7) + pow25_7)))
1434 l1_ = L1
1435 a1_ = (1 + g) * a1
1436 b1_ = b1
1437 l2_ = L2
1438 a2_ = (1 + g) * a2
1439 b2_ = b2
1440 c1_ = math.sqrt(math.pow(a1_, 2) + math.pow(b1_, 2))
1441 c2_ = math.sqrt(math.pow(a2_, 2) + math.pow(b2_, 2))
1442 h1_ = (
1443 0
1444 if a1_ == 0 and b1_ == 0
1445 else math.degrees(math.atan2(b1_, a1_)) + (0 if b1_ >= 0 else 360.0)
1446 )
1447 h2_ = (
1448 0
1449 if a2_ == 0 and b2_ == 0
1450 else math.degrees(math.atan2(b2_, a2_)) + (0 if b2_ >= 0 else 360.0)
1451 )
1452 dh_cond = 1.0 if h2_ - h1_ > 180 else (2.0 if h2_ - h1_ < -180 else 0)
1453 dh_ = (
1454 h2_ - h1_
1455 if dh_cond == 0
1456 else (h2_ - h1_ - 360.0 if dh_cond == 1 else h2_ + 360.0 - h1_)
1457 )
1458 dl_ = l2_ - l1_
1459 dl = dl_
1460 dc_ = c2_ - c1_
1461 dc = dc_
1462 dhh_ = 2 * math.sqrt(c1_ * c2_) * math.sin(math.radians(dh_ / 2.0))
1463 dh = dhh_
1464 l__avg = avg(l1_, l2_)
1465 c__avg = avg(c1_, c2_)
1466 h__avg_cond = (
1467 3.0
1468 if c1_ * c2_ == 0
1469 else (0 if abs(h2_ - h1_) <= 180 else (1.0 if h2_ + h1_ < 360 else 2.0))
1470 )
1471 h__avg = (
1472 h1_ + h2_
1473 if h__avg_cond == 3
1474 else (
1475 avg(h1_, h2_)
1476 if h__avg_cond == 0
1477 else (
1478 avg(h1_, h2_) + 180.0 if h__avg_cond == 1 else avg(h1_, h2_) - 180.0
1479 )
1480 )
1481 )
1482 ab = math.pow(l__avg - 50.0, 2) # (L'_ave-50)^2
1483 s_l = 1 + 0.015 * ab / math.sqrt(20.0 + ab)
1484 s_c = 1 + 0.045 * c__avg
1485 t = (
1486 1
1487 - 0.17 * math.cos(math.radians(h__avg - 30.0))
1488 + 0.24 * math.cos(math.radians(2.0 * h__avg))
1489 + 0.32 * math.cos(math.radians(3.0 * h__avg + 6.0))
1490 - 0.2 * math.cos(math.radians(4 * h__avg - 63.0))
1491 )
1492 s_h = 1 + 0.015 * c__avg * t
1493 dtheta = 30.0 * math.exp(-1 * math.pow((h__avg - 275.0) / 25.0, 2))
1494 r_c = 2.0 * math.sqrt(math.pow(c__avg, 7) / (math.pow(c__avg, 7) + pow25_7))
1495 r_t = -math.sin(math.radians(2.0 * dtheta)) * r_c
1496 aj = dl_ / s_l / k_l # dL' / k_L / S_L
1497 ak = dc_ / s_c / k_c # dC' / k_C / S_C
1498 al = dhh_ / s_h / k_h # dH' / k_H / S_H
1499 dlw, dcw, dhw = aj, ak, al
1500 de = math.sqrt(
1501 math.pow(aj, 2) + math.pow(ak, 2) + math.pow(al, 2) + r_t * ak * al
1502 )
1503 else:
1504 # dE 1976
1505 dl = L2 - L1
1506 c1 = math.sqrt(math.pow(a1, 2) + math.pow(b1, 2))
1507 c2 = math.sqrt(math.pow(a2, 2) + math.pow(b2, 2))
1508 dc = c2 - c1
1509 dh2 = math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2) - math.pow(dc, 2)
1510 dh = math.sqrt(dh2) if dh2 > 0 else 0
1511 dlw, dcw, dhw = dl, dc, dh
1512 de = math.sqrt(math.pow(dl, 2) + math.pow(a1 - a2, 2) + math.pow(b1 - b2, 2))
1513
1514 return {
1515 "E": de,
1516 "L": dl,
1517 "C": dc,
1518 "H": dh,
1519 "a": a1 - a2,
1520 "b": b1 - b2,
1521 # Weighted
1522 "Lw": dlw,
1523 "Cw": dcw,
1524 "Hw": dhw,
1525 }
1526
1527
1528 def XYZ2Lab_delta( # noqa: N802
1529 X1: float, # noqa: N803
1530 Y1: float, # noqa: N803
1531 Z1: float, # noqa: N803
1532 X2: float, # noqa: N803
1533 Y2: float, # noqa: N803
1534 Z2: float, # noqa: N803
1535 method: str = "76",
1536 whitepoint1: None | float | str | list | tuple = "D50",
1537 whitepoint2: None | float | str | list | tuple = "D50",
1538 whitepoint_reference: None | float | str | tuple = "D50",
1539 cat: str = "Bradford",
1540 ) -> dict:
1541 """Compute the delta of two samples in XYZ space.
1542
1543 Args:
1544 X1 (float): XYZ values of the first sample.
1545 Y1 (float): XYZ values of the first sample.
1546 Z1 (float): XYZ values of the first sample.
1547 X2 (float): XYZ values of the second sample.
1548 Y2 (float): XYZ values of the second sample.
1549 Z2 (float): XYZ values of the second sample.
1550 method (str): Method to use for delta calculation. Defaults to "76".
1551 whitepoint1 (None | float | str | list | tuple): Whitepoint of
1552 the first sample. Defaults to "D50".
1553 whitepoint2 (None | float | str | list | tuple): Whitepoint of
1554 the second sample. Defaults to "D50".
1555 whitepoint_reference (None | float | str | list | tuple): Reference
1556 whitepoint. Defaults to "D50".
1557 cat (str): Chromatic adaptation transform. Defaults to "Bradford".
1558
1559 Returns:
1560 dict: Dictionary containing the delta values.
1561 """
1562 whitepoint1 = get_whitepoint(whitepoint1)
1563 whitepoint2 = get_whitepoint(whitepoint2)
1564 whitepoint_reference = get_whitepoint(whitepoint_reference)
1565 if whitepoint1 != whitepoint_reference:
1566 X1, Y1, Z1 = adapt(X1, Y1, Z1, whitepoint1, whitepoint_reference, cat) # noqa: N806
1567 if whitepoint2 != whitepoint_reference:
1568 X2, Y2, Z2 = adapt(X2, Y2, Z2, whitepoint2, whitepoint_reference, cat) # noqa: N806
1569 l1, a1, b1 = XYZ2Lab(X1, Y1, Z1, whitepoint_reference)
1570 l2, a2, b2 = XYZ2Lab(X2, Y2, Z2, whitepoint_reference)
1571 logger.debug(
1572 f"L*a*b*[1] {l1:.4f} {a1:.4f} {b1:.4f} L*a*b*[2] {l2:.4f} {a2:.4f} {b2:.4f}"
1573 )
1574 return delta(l1, a1, b1, l2, a2, b2, method)
1575
1576
1577 def is_similar_matrix(
1578 matrix1: Matrix3x3, matrix2: Matrix3x3, digits: float = 3
1579 ) -> bool:
1580 """Check if two matrices are equal up to n decimal digits.
1581
1582 Args:
1583 matrix1 (Matrix3x3): First matrix to compare.
1584 matrix2 (Matrix3x3): Second matrix to compare.
1585 digits (int): Number of decimal digits to consider for equality.
1586 Defaults to 3.
1587
1588 Returns:
1589 bool: True if the matrices are equal up to the specified number of
1590 digits, False otherwise.
1591 """
1592 return matrix1.rounded(digits) == matrix2.rounded(digits)
1593
1594
1595 def is_equal(
1596 values1: list[float],
1597 values2: list[float],
1598 quantizer: None | Callable = None,
1599 ) -> bool:
1600 """Check if two value sets are equal after quantization.
1601
1602 Args:
1603 values1 (list): First list of float values.
1604 values2 (list): Second list of float values.
1605 quantizer (callable, optional): Function to quantize the values. If None,
1606 defaults to rounding to 4 decimal places.
1607
1608 Returns:
1609 bool: True if the quantized values are equal, False otherwise.
1610 """
1611 if quantizer is None:
1612
1613 def quantizer(v: float) -> float:
1614 """Default quantizer that rounds to 4 decimal places.
1615
1616 Args:
1617 v (float): The value to quantize.
1618
1619 Returns:
1620 float: The quantized value rounded to 4 decimal places.
1621 """
1622 return round(v, 4)
1623
1624 return [quantizer(v) for v in values1] == [quantizer(v) for v in values2]
1625
1626
1627 def four_color_matrix(
1628 xrr: float, # noqa: N803
1629 yrr: float, # noqa: N803
1630 zrr: float, # noqa: N803
1631 xrg: float, # noqa: N803
1632 yrg: float, # noqa: N803
1633 zrg: float, # noqa: N803
1634 xrb: float, # noqa: N803
1635 yrb: float, # noqa: N803
1636 zrb: float, # noqa: N803
1637 xrw: float, # noqa: N803
1638 yrw: float, # noqa: N803
1639 zrw: float, # noqa: N803
1640 xmr: float, # noqa: N803
1641 ymr: float, # noqa: N803
1642 zmr: float, # noqa: N803
1643 xmg: float, # noqa: N803
1644 ymg: float, # noqa: N803
1645 zmg: float, # noqa: N803
1646 xmb: float, # noqa: N803
1647 ymb: float, # noqa: N803
1648 zmb: float, # noqa: N803
1649 xmw: float, # noqa: N803
1650 ymw: float, # noqa: N803
1651 zmw: float, # noqa: N803
1652 y_correction: bool = True, # noqa: N803
1653 ) -> Matrix3x3:
1654 """Four-Color Matrix Method for Correction of Tristimulus Colorimeters.
1655
1656 Based on paper published in Proc., IS&T Fifth Color Imaging Conference,
1657 301-305 (1997) and IS&T Sixth Color Imaging Conference (1998).
1658
1659 Args:
1660 xrr (float): Reference RGB values for red.
1661 yrr (float): Reference RGB values for red.
1662 zrr (float): Reference RGB values for red.
1663 xrg (float): Reference RGB values for green.
1664 yrg (float): Reference RGB values for green.
1665 zrg (float): Reference RGB values for green.
1666 xrb (float): Reference RGB values for blue.
1667 yrb (float): Reference RGB values for blue.
1668 zrb (float): Reference RGB values for blue.
1669 xrw (float): Reference RGB values for white.
1670 yrw (float): Reference RGB values for white.
1671 zrw (float): Reference RGB values for white.
1672 xmr (float): Measured RGB values for red.
1673 ymr (float): Measured RGB values for red.
1674 zmr (float): Measured RGB values for red.
1675 xmg (float): Measured RGB values for green.
1676 ymg (float): Measured RGB values for green.
1677 zmg (float): Measured RGB values for green.
1678 xmb (float): Measured RGB values for blue.
1679 ymb (float): Measured RGB values for blue.
1680 zmb (float): Measured RGB values for blue.
1681 xmw (float): Measured RGB values for white.
1682 ymw (float): Measured RGB values for white.
1683 zmw (float): Measured RGB values for white.
1684 y_correction (bool): If True, apply Y correction. Defaults to True.
1685
1686 Returns:
1687 Matrix3x3: The four-color matrix.
1688 """
1689 components = {
1690 "XrR": xrr,
1691 "YrR": yrr,
1692 "ZrR": zrr,
1693 "XrG": xrg,
1694 "YrG": yrg,
1695 "ZrG": zrg,
1696 "XrB": xrb,
1697 "YrB": yrb,
1698 "ZrB": zrb,
1699 "XrW": xrw,
1700 "YrW": yrw,
1701 "ZrW": zrw,
1702 "XmR": xmr,
1703 "YmR": ymr,
1704 "ZmR": zmr,
1705 "XmG": xmg,
1706 "YmG": ymg,
1707 "ZmG": zmg,
1708 "XmB": xmb,
1709 "YmB": ymb,
1710 "ZmB": zmb,
1711 "XmW": xmw,
1712 "YmW": ymw,
1713 "ZmW": zmw,
1714 }
1715 xyz = {}
1716 m = {}
1717 k = {}
1718 for s in "mr":
1719 xyz[s] = {}
1720 for color in "RGBW":
1721 x, y, _ = XYZ2xyY(
1722 *(components[f"{component}{s}{color}"] for component in "XYZ")
1723 )
1724 xyz[s][color] = x, y, 1 - x - y
1725 m[s] = Matrix3x3([xyz[s][color] for color in "RGB"]).transposed()
1726 k[s] = m[s].inverted() * xyz[s]["W"]
1727 m[f"{s}RGB"] = m[s] * Matrix3x3(
1728 [[k[s][0], 0, 0], [0, k[s][1], 0], [0, 0, k[s][2]]]
1729 )
1730 r = m["rRGB"] * m["mRGB"].inverted()
1731 if y_correction:
1732 # The Y calibration factor kY is obtained as the ratio of the reference
1733 # luminance value to the matrix-corrected Y value, as defined in
1734 # Four-Color Matrix Method for Correction of Tristimulus Colorimeters -
1735 # Part 2
1736 mw = xmw, ymw, zmw
1737 ky = yrw / (r * mw)[1]
1738 r[:] = [[ky * v for v in row] for row in r]
1739 return r
1740
1741
1742 def get_gamma(
1743 values: list | tuple,
1744 scale: float = 1.0,
1745 vmin: float = 0.0,
1746 vmax: float = 1.0,
1747 average: bool = True,
1748 least_squares: bool = False,
1749 ) -> float | list:
1750 """Return average or least squares gamma or a list of gamma values.
1751
1752 Args:
1753 values (list): A list of tuples containing x and y values.
1754 scale (float): The scale factor. Defaults to 1.0.
1755 vmin (float): Minimum value. Defaults to 0.0.
1756 vmax (float): Maximum value. Defaults to 1.0.
1757 average (bool): If True, return the average gamma. Defaults to True.
1758 least_squares (bool): If True, return the least squares gamma. Defaults
1759 to False.
1760
1761 Returns:
1762 float | list: The average or least squares gamma, or a list of gamma
1763 values.
1764 """
1765 if least_squares:
1766 logxy = []
1767 logx2 = []
1768 else:
1769 gammas = []
1770 vmin /= scale
1771 vmax /= scale
1772 for x, y in values:
1773 x /= scale
1774 y = (y / scale - vmin) * (vmax + vmin)
1775 if 0 < x < 1 and y > 0:
1776 if least_squares:
1777 logxy.append(math.log(x) * math.log(y))
1778 logx2.append(math.pow(math.log(x), 2))
1779 else:
1780 gammas.append(math.log(y) / math.log(x))
1781 if average or least_squares:
1782 if least_squares:
1783 if not logxy or not logx2:
1784 return 0
1785 return sum(logxy) / sum(logx2)
1786 if not gammas:
1787 return 0
1788 return sum(gammas) / len(gammas)
1789 return gammas
1790
1791
1792 def guess_cat(
1793 chad: Matrix3x3,
1794 whitepoint_source: None | float | str | list | tuple = None,
1795 whitepoint_destination: None | float | str | list | tuple = None,
1796 ) -> None | str:
1797 """Guess the chromatic adaption transform used in a chromatic adaption matrix.
1798
1799 ...as found in an ICC profile's 'chad' tag
1800
1801 Args:
1802 chad (Matrix3x3): The chromatic adaption matrix.
1803 whitepoint_source (tuple): The source whitepoint.
1804 whitepoint_destination (tuple): The destination whitepoint.
1805
1806 Returns:
1807 None | str: The guessed chromatic adaption transform.
1808 """
1809 if chad == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]:
1810 # Cannot figure out CAT from identity chad
1811 return None
1812 for cat in CAT_MATRICES:
1813 if is_similar_matrix(
1814 (
1815 chad
1816 * CAT_MATRICES[cat].inverted()
1817 * LMS_wp_adaption_matrix(whitepoint_destination, whitepoint_source, cat)
1818 ).inverted(),
1819 CAT_MATRICES[cat],
1820 2,
1821 ):
1822 return cat
1823 return None
1824
1825
1826 def CIEDCCT2xyY(T: float, scale: float = 1.0) -> tuple[float, float, float]: # noqa: N802, N803
1827 """Convert from CIE correlated daylight temperature to xyY.
1828
1829 Based on formula from http://brucelindbloom.com/Eqn_T_to_xy.html
1830
1831 Args:
1832 T (float): The temperature in Kelvin.
1833 scale (float): The scale factor. Defaults to 1.0.
1834
1835 Returns:
1836 tuple[float, float, float]: The xyY values.
1837 """
1838 if isinstance(T, str):
1839 # Assume standard illuminant, e.g. "D50"
1840 return XYZ2xyY(*get_standard_illuminant(T, scale=scale))
1841 if not (2500 <= T <= 25000):
1842 # Lower limit of 2500 is consistent with Argyll xicc/xspect.c daylight_il
1843 # Actual usable lower limit lies at roughly 2244
1844 return None
1845 if T < 4000:
1846 # Only accurate down to about 4000
1847 warnings.warn(
1848 "Daylight CCT is only accurate down to about 4000 K",
1849 Warning,
1850 stacklevel=2,
1851 )
1852 if T <= 7000:
1853 xd = (
1854 ((-4.607 * math.pow(10, 9)) / math.pow(T, 3))
1855 + ((2.9678 * math.pow(10, 6)) / math.pow(T, 2))
1856 + ((0.09911 * math.pow(10, 3)) / T)
1857 + 0.244063
1858 )
1859 else:
1860 xd = (
1861 ((-2.0064 * math.pow(10, 9)) / math.pow(T, 3))
1862 + ((1.9018 * math.pow(10, 6)) / math.pow(T, 2))
1863 + ((0.24748 * math.pow(10, 3)) / T)
1864 + 0.237040
1865 )
1866 yd = -3 * math.pow(xd, 2) + 2.87 * xd - 0.275
1867 return xd, yd, scale
1868
1869
1870 def CIEDCCT2XYZ(T: float, scale: float = 1.0) -> tuple[float, float, float]: # noqa: N802, N803
1871 """Convert from CIE correlated daylight temperature to XYZ.
1872
1873 Args:
1874 T (float): The temperature in Kelvin.
1875 scale (float): The scale factor. Defaults to 1.0.
1876
1877 Returns:
1878 tuple[float, float, float]: The XYZ values.
1879 """
1880 xyY = CIEDCCT2xyY(T, scale) # noqa: N806
1881 return xyY2XYZ(*xyY) if xyY else None # noqa: N806
1882
1883
1884 def cLUT65_to_VidRGB(v: float, size: int = 65) -> float: # noqa: N802
1885 """cLUT65 to VidRGB conversion.
1886
1887 cLUT Input value tweaks to make Video encoded black land on
1888 65 res grid nodes, which should help 33 and 17 res cLUTs too.
1889
1890 Args:
1891 v (float): The value to convert.
1892 size (int): The size of the LUT. Defaults to 65.
1893
1894 Returns:
1895 float: The converted value.
1896 """
1897 if v <= 236.0 / 256:
1898 # Scale up to near black point
1899 return v * 256.0 / 255
1900 return 1 - (1 - v) * (1 - 236.0 / 255) / (1 - 236.0 / 256)
1901
1902
1903 def VidRGB_to_cLUT65(v: float, size: int = 65) -> float: # noqa: N802
1904 """Convert from VidRGB to cLUT65.
1905
1906 Args:
1907 v (float): The value to convert.
1908 size (int): The size of the LUT. Defaults to 65.
1909
1910 Returns:
1911 float: The converted value.
1912 """
1913 if v <= 236.0 / 255.0:
1914 return v * 255.0 / 256
1915 return 1 - (1 - v) * (1 - 236.0 / 256) / (1 - 236.0 / 255)
1916
1917
1918 def VidRGB_to_eeColor(v: float) -> float: # noqa: N802
1919 """Convert from VidRGB to eeColor.
1920
1921 Args:
1922 v (float): The value to convert.
1923
1924 Returns:
1925 float: The converted value.
1926 """
1927 return v * 255.0 / 256.0
1928
1929
1930 def eeColor_to_VidRGB(v: float) -> float: # noqa: N802
1931 """Convert from eeColor to VidRGB.
1932
1933 Args:
1934 v (float): The value to convert.
1935
1936 Returns:
1937 float: The converted value.
1938 """
1939 return v * 256.0 / 255.0
1940
1941
1942 def DIN992Lab( # noqa: N802
1943 l99: float,
1944 a99: float,
1945 b99: float,
1946 kCH: float = 1.0, # noqa: N803
1947 kE: float = 1.0, # noqa: N803
1948 ) -> tuple[float, float, float]:
1949 """Convert from DIN99 to Lab.
1950
1951 Args:
1952 l99 (float): The L value of the color.
1953 a99 (float): The a value of the color.
1954 b99 (float): The b value of the color.
1955 kCH (float, optional): The kCH value of the color. Defaults to 1.0.
1956 kE (float, optional): The kE value of the color. Defaults to 1.0.
1957
1958 Returns:
1959 tuple[float, float, float]: The L, a, b values.
1960 """
1961 c99, h99 = DIN99familyab2DIN99CH(a99, b99)
1962 return DIN99familyLCH2Lab(
1963 l99, c99, h99, 0, 105.51, 0.0158, 16, 0.7, 1 / (0.045 * kCH * kE), 0.045, kE, 0
1964 )
1965
1966
1967 def DIN99b2Lab(l99: float, a99: float, b99: float) -> tuple[float, float, float]: # noqa: N802, N803
1968 """Convert from DIN99b to Lab.
1969
1970 Args:
1971 l99 (float): The L value of the color.
1972 a99 (float): The a value of the color.
1973 b99 (float): The b value of the color.
1974
1975 Returns:
1976 tuple[float, float, float]: The L, a, b values.
1977 """
1978 c99, h99 = DIN99familyab2DIN99CH(a99, b99)
1979 return DIN99familyLCH2Lab(l99, c99, h99, 0, 303.67, 0.0039, 26, 0.83, 23, 0.075)
1980
1981
1982 def DIN99o2Lab( # noqa: N802
1983 l99: float,
1984 a99: float,
1985 b99: float,
1986 kCH: float = 1.0, # noqa: N803
1987 kE: float = 1.0, # noqa: N803
1988 ) -> tuple[float, float, float]:
1989 """Convert from DIN99o to Lab.
1990
1991 Args:
1992 l99 (float): The L value of the color.
1993 a99 (float): The a value of the color.
1994 b99 (float): The b value of the color.
1995 kCH (float, optional): The kCH value of the color. Defaults to 1.0.
1996 kE (float, optional): The kE value of the color. Defaults to 1.0.
1997
1998 Returns:
1999 tuple[float, float, float]: The L, a, b values.
2000 """
2001 c99, h99 = DIN99familyab2DIN99CH(a99, b99)
2002 return DIN99familyLCH2Lab(
2003 l99, c99, h99, 0, 303.67, 0.0039, 26, 0.83, 1 / (0.0435 * kCH * kE), 0.075, kE
2004 )
2005
2006
2007 def DIN99bLCH2Lab(l99: float, c99: float, h99: float) -> tuple[float, float, float]: # noqa: N802, N803
2008 """Convert from DIN99bLCH to Lab.
2009
2010 Args:
2011 l99 (float): The L value of the color.
2012 c99 (float): The C value of the color.
2013 h99 (float): The H value of the color.
2014
2015 Returns:
2016 tuple[float, float, float]: The L, a, b values.
2017 """
2018 return DIN99familyLCH2Lab(l99, c99, h99, 0, 303.67, 0.0039, 26, 0.83, 23, 0.075)
2019
2020
2021 def DIN99c2Lab( # noqa: N802
2022 l99: float, # noqa: N803
2023 a99: float,
2024 b99: float,
2025 whitepoint: None | float | str | list | tuple = None,
2026 ) -> tuple[float, float, float]:
2027 """Convert from DIN99c to Lab.
2028
2029 Args:
2030 l99 (float): The L value of the color.
2031 a99 (float): The a value of the color.
2032 b99 (float): The b value of the color.
2033 whitepoint (None | float | str | list | tuple): The whitepoint to
2034 use. Defaults to D50.
2035
2036 Returns:
2037 tuple[float, float, float]: The L, a, b values.
2038 """
2039 c99, h99 = DIN99familyab2DIN99CH(a99, b99)
2040 return DIN99familyLCH2Lab(
2041 l99, c99, h99, 0.1, 317.651, 0.0037, 0, 0.94, 23, 0.066, whitepoint
2042 )
2043
2044
2045 def DIN99d2Lab( # noqa: N802
2046 l99: float, # noqa: N803
2047 a99: float,
2048 b99: float,
2049 whitepoint: None | float | str | list | tuple = None,
2050 ) -> tuple[float, float, float]:
2051 """Convert from DIN99d to Lab.
2052
2053 Args:
2054 l99 (float): The L value of the color.
2055 a99 (float): The a value of the color.
2056 b99 (float): The b value of the color.
2057 whitepoint (None | float | str | list | tuple): The whitepoint to
2058 use. Defaults to D50.
2059
2060 Returns:
2061 tuple[float, float, float]: The L, a, b values.
2062 """
2063 c99, h99 = DIN99familyab2DIN99CH(a99, b99)
2064 return DIN99familyLCH2Lab(
2065 l99, c99, h99, 0.12, 325.221, 0.0036, 50, 1.14, 22.5, 0.06, whitepoint
2066 )
2067
2068
2069 def DIN99dLCH2Lab( # noqa: N802
2070 l99: float, # noqa: N803
2071 c99: float, # noqa: N803
2072 h99: float, # noqa: N803
2073 whitepoint: None | float | str | list | tuple = None,
2074 ) -> tuple[float, float, float]:
2075 """Convert from DIN99dLCH to Lab.
2076
2077 Args:
2078 l99 (float): The L value of the color.
2079 c99 (float): The C value of the color.
2080 h99 (float): The H value of the color.
2081 whitepoint (None | float | str | list | tuple): The whitepoint to
2082 use. Defaults to D50.
2083
2084 Returns:
2085 tuple[float, float, float]: The L, a, b values.
2086 """
2087 return DIN99familyLCH2Lab(
2088 l99, c99, h99, 0.12, 325.221, 0.0036, 50, 1.14, 22.5, 0.06, whitepoint
2089 )
2090
2091
2092 def DIN99familyLCH2Lab( # noqa: N802
2093 l99: float, # noqa: N803
2094 c99: float, # noqa: N803
2095 h99: float, # noqa: N803
2096 x: float,
2097 l1: float,
2098 l2: float,
2099 deg: float,
2100 f1: float,
2101 c1: float,
2102 c2: float,
2103 whitepoint: None | float | str | list | tuple = None,
2104 kE: float = 1.0, # noqa: N803
2105 hdeg: None | float = None,
2106 ) -> tuple[float, float, float]:
2107 """Convert from DIN99LCH to Lab.
2108
2109 Args:
2110 l99 (float): The L value of the color.
2111 c99 (float): The C value of the color.
2112 h99 (float): The H value of the color.
2113 x (float): The x value of the color.
2114 l1 (float): The l1 value of the color.
2115 l2 (float): The l2 value of the color.
2116 deg (float): The degree value of the color.
2117 f1 (float): The f1 value of the color.
2118 c1 (float): The c1 value of the color.
2119 c2 (float): The c2 value of the color.
2120 whitepoint (None | float | str | list | tuple): The whitepoint to
2121 use. Defaults to D50.
2122 kE (float, optional): The kE value of the color. Defaults to 1.0.
2123 hdeg (None | float, optional): The hdeg value of the color. Defaults to
2124 None.
2125
2126 Returns:
2127 tuple[float, float, float]: The L, a, b values.
2128 """
2129 g = (math.exp(c99 / c1) - 1) / c2
2130 if hdeg is None:
2131 hdeg = deg
2132 h99 -= hdeg
2133 l, a, b = DIN99familyLHCG2Lab(l99, h99, c99, g, kE, l1, l2, deg, f1)
2134 if x:
2135 whitepoint99d = XYZ2DIN99cdXYZ(*get_whitepoint(whitepoint, 100), x=x)
2136 X, Y, Z = Lab2XYZ(l, a, b, whitepoint99d, scale=100) # noqa: N806
2137 X, Y, Z = DIN99cdXYZ2XYZ(X, Y, Z, x) # noqa: N806
2138 l, a, b = XYZ2Lab(X, Y, Z, whitepoint)
2139 return l, a, b
2140
2141
2142 def DIN99cdXYZ2XYZ( # noqa: N802
2143 X: float, # noqa: N803
2144 Y: float, # noqa: N803
2145 Z: float, # noqa: N803
2146 x: float,
2147 ) -> tuple[float, float, float]:
2148 """Convert from DIN99cdXYZ to XYZ.
2149
2150 Args:
2151 X (float): The X value of the color.
2152 Y (float): The Y value of the color.
2153 Z (float): The Z value of the color.
2154 x (float): The x value of the color.
2155
2156 Returns:
2157 tuple[float, float, float]: The X, Y, Z values.
2158 """
2159 X = (X + x * Z) / (1 + x) # noqa: N806
2160 return X, Y, Z
2161
2162
2163 def DIN99familyLHCG2Lab( # noqa: N802
2164 l99: float, # noqa: N803
2165 h99: float, # noqa: N803
2166 c99: float, # noqa: N803
2167 G: float, # noqa: N803
2168 kE: float, # noqa: N803
2169 l1: float,
2170 l2: float,
2171 deg: float,
2172 f1: float,
2173 ) -> tuple[float, float, float]:
2174 """Convert from DIN99LCH to Lab.
2175
2176 Args:
2177 l99 (float): The L value of the color.
2178 h99 (float): The H value of the color.
2179 c99 (float): The C value of the color.
2180 G (float): The G value of the color.
2181 kE (float): The kE value of the color.
2182 l1 (float): The l1 value of the color.
2183 l2 (float): The l2 value of the color.
2184 deg (float): The degree value of the color.
2185 f1 (float): The f1 value of the color.
2186
2187 Returns:
2188 tuple[float, float, float]: The L, a, b values.
2189 """
2190 l = (math.exp((l99 * kE) / l1) - 1) / l2
2191 h99ef = h99 * math.pi / 180
2192 e = G * math.cos(h99ef)
2193 f = G * math.sin(h99ef)
2194 rad = deg * math.pi / 180
2195 a = e * math.cos(rad) - (f / f1) * math.sin(rad)
2196 b = e * math.sin(rad) + (f / f1) * math.cos(rad)
2197 return l, a, b
2198
2199
2200 def DIN99familyCH2DIN99ab(c99: float, h99: float) -> tuple[float, float]: # noqa: N802, N803
2201 """Convert from DIN99CH to DIN99ab.
2202
2203 Args:
2204 c99 (float): The C value of the color.
2205 h99 (float): The H value of the color.
2206
2207 Returns:
2208 tuple[float, float]: The a99 and b99 values.
2209 """
2210 h99ef = h99 * math.pi / 180
2211 return c99 * math.cos(h99ef), c99 * math.sin(h99ef)
2212
2213
2214 def DIN99familyab2DIN99CH(a99: float, b99: float) -> tuple[float, float]: # noqa: N802
2215 """Convert from DIN99ab to DIN99CH.
2216
2217 Args:
2218 a99 (float): The a value of the color.
2219 b99 (float): The b value of the color.
2220
2221 Returns:
2222 tuple[float, float]: The c99 and h99 values.
2223 """
2224 c99 = math.sqrt(math.pow(a99, 2) + math.pow(b99, 2))
2225 if a99 > 0:
2226 h99ef = math.atan2(b99, a99) if b99 >= 0 else 2 * math.pi + math.atan2(b99, a99)
2227 elif a99 < 0:
2228 h99ef = math.atan2(b99, a99)
2229 elif b99 > 0:
2230 h99ef = math.pi / 2
2231 elif b99 < 0:
2232 h99ef = (3 * math.pi) / 2
2233 else:
2234 h99ef = 0.0
2235 h99 = h99ef * 180 / math.pi
2236 return c99, h99
2237
2238
2239 def HSI2RGB( # noqa: N802
2240 H: float, # noqa: N803
2241 S: float, # noqa: N803
2242 I: float, # noqa: N803
2243 scale: float = 1.0,
2244 ) -> tuple[float, float, float]:
2245 """Convert from HSI to RGB.
2246
2247 Args:
2248 H (float): The hue value of the color.
2249 S (float): The saturation value of the color.
2250 I (float): The intensity value of the color.
2251 scale (float): The scale factor to apply to the RGB values.
2252
2253 Returns:
2254 tuple[float, float, float]: The R, G, B values.
2255 """
2256 H *= 360 # noqa: N806
2257
2258 h = H
2259 if 120 < H <= 240:
2260 h -= 120
2261 elif 240 < H <= 360:
2262 h -= 240
2263
2264 f = math.cos(math.radians(h)) / math.cos(math.radians(60 - h))
2265 a = I + I * S * f
2266 b = I + I * S * (1 - f)
2267 c = I - I * S
2268
2269 if H <= 120:
2270 r = a
2271 g = b
2272 b = c
2273 elif H <= 240:
2274 g = a
2275 b = b
2276 r = c
2277 else:
2278 b = a
2279 r = b
2280 g = c
2281
2282 return tuple(v * scale for v in (r, g, b))
2283
2284
2285 def HSL2RGB( # noqa: N802
2286 H: float, # noqa: N803
2287 S: float, # noqa: N803
2288 L: float, # noqa: N803
2289 scale: float = 1.0,
2290 ) -> tuple[float, float, float]:
2291 """Convert from HSL to RGB.
2292
2293 Args:
2294 H (float): The hue value of the color.
2295 S (float): The saturation value of the color.
2296 L (float): The lightness value of the color.
2297 scale (float): The scale factor to apply to the RGB values.
2298
2299 Returns:
2300 tuple[float, float, float]: The R, G, B values.
2301 """
2302 return tuple(v * scale for v in colorsys.hls_to_rgb(H, L, S))
2303
2304
2305 def HSV2RGB( # noqa: N802
2306 H: float, # noqa: N803
2307 S: float, # noqa: N803
2308 V: float, # noqa: N803
2309 scale: float = 1.0,
2310 ) -> tuple[float, float, float]:
2311 """Convert from HSV to RGB.
2312
2313 Args:
2314 H (float): The hue value of the color.
2315 S (float): The saturation value of the color.
2316 V (float): The value (brightness) of the color.
2317 scale (float): The scale factor to apply to the RGB values.
2318
2319 Returns:
2320 tuple[float, float, float]: The R, G, B values.
2321 """
2322 return tuple(v * scale for v in colorsys.hsv_to_rgb(H, S, V))
2323
2324
2325 def get_dbl_min() -> float:
2326 """Get the smallest positive normalized double value.
2327
2328 Returns:
2329 float: The smallest positive normalized double value.
2330 """
2331 t = "0.0"
2332 i = 10
2333 n = 0
2334 dbl_min = 0.0
2335 while True:
2336 if i > 1:
2337 i -= 1
2338 else:
2339 t += "0"
2340 i = 9
2341 if float(t + str(i)) == 0.0:
2342 if n > 1:
2343 break
2344 n += 1
2345 t += str(i)
2346 i = 10
2347 else:
2348 if n > 1:
2349 n -= 1
2350 dbl_min = float(t + str(i))
2351 return dbl_min
2352
2353
2354 DBL_MIN = get_dbl_min()
2355
2356
2357 def LCHab2Lab(L: float, C: float, H: float) -> tuple[float, float, float]: # noqa: N802, N803
2358 """Convert from LCHab to Lab.
2359
2360 Args:
2361 L (float): The L value of the color.
2362 C (float): The C value of the color.
2363 H (float): The H value of the color.
2364
2365 Returns:
2366 tuple[float, float, float]: The L, a, b values.
2367 """
2368 a = C * math.cos(H * math.pi / 180.0)
2369 b = C * math.sin(H * math.pi / 180.0)
2370 return L, a, b
2371
2372
2373 def Lab2DIN99( # noqa: N802
2374 L: float, # noqa: N803
2375 a: float,
2376 b: float,
2377 kCH: float = 1.0, # noqa: N803
2378 kE: float = 1.0, # noqa: N803
2379 ) -> tuple[float, float, float]:
2380 """Convert from Lab to DIN99.
2381
2382 Args:
2383 L (float): The L value of the color.
2384 a (float): The a value of the color.
2385 b (float): The b value of the color.
2386 kCH (float): The kCH value. Defaults to 1.0.
2387 kE (float): The kE value. Defaults to 1.0.
2388
2389 Returns:
2390 tuple[float, float, float]: The l99, a99, b99 values.
2391 """
2392 l99, c99, h99 = Lab2DIN99LCH(L, a, b, kCH, kE)
2393 a99, b99 = DIN99familyCH2DIN99ab(c99, h99)
2394 return l99, a99, b99
2395
2396
2397 def Lab2DIN99b( # noqa: N802
2398 L: float, # noqa: N803
2399 a: float,
2400 b: float,
2401 kE: float = 1.0, # noqa: N803
2402 ) -> tuple[float, float, float]:
2403 """Convert from Lab to DIN99b.
2404
2405 Args:
2406 L (float): The L value of the color.
2407 a (float): The a value of the color.
2408 b (float): The b value of the color.
2409 kE (float): The kE value. Defaults to 1.0.
2410
2411 Returns:
2412 tuple[float, float, float]: The l99, a99, b99 values.
2413 """
2414 l99, c99, h99 = Lab2DIN99bLCH(L, a, b, kE)
2415 a99, b99 = DIN99familyCH2DIN99ab(c99, h99)
2416 return l99, a99, b99
2417
2418
2419 def Lab2DIN99o( # noqa: N802
2420 L: float, # noqa: N803
2421 a: float,
2422 b: float,
2423 kCH: float = 1.0, # noqa: N803
2424 kE: float = 1.0, # noqa: N803
2425 ) -> tuple[float, float, float]:
2426 """Convert from Lab to DIN99o.
2427
2428 Args:
2429 L (float): The L value of the color.
2430 a (float): The a value of the color.
2431 b (float): The b value of the color.
2432 kCH (float): The kCH value.
2433 kE (float): The kE value.
2434
2435 Returns:
2436 tuple[float, float, float]: The l99, a99, b99 values.
2437 """
2438 l99, c99, h99 = Lab2DIN99oLCH(L, a, b, kCH, kE)
2439 a99, b99 = DIN99familyCH2DIN99ab(c99, h99)
2440 return l99, a99, b99
2441
2442
2443 def Lab2DIN99c( # noqa: N802
2444 L: float, # noqa: N803
2445 a: float,
2446 b: float,
2447 kE: float = 1.0, # noqa: N803
2448 whitepoint: None | float | str | list | tuple = None,
2449 ) -> tuple[float, float, float]:
2450 """Convert from Lab to DIN99c.
2451
2452 Args:
2453 L (float): The L value of the color.
2454 a (float): The a value of the color.
2455 b (float): The b value of the color.
2456 kE (float): The kE value. Defaults to 1.0. Unused, but kept for
2457 compatibility.
2458 whitepoint (None | float | str | list | tuple): The whitepoint to
2459 use. Defaults to D50.
2460
2461 Returns:
2462 tuple[float, float, float]: The l99, a99, b99 values.
2463 """
2464 return XYZ2DIN99c(*Lab2XYZ(L, a, b, whitepoint, scale=100), whitepoint)
2465
2466
2467 def Lab2DIN99d( # noqa: N802
2468 L: float, # noqa: N803
2469 a: float,
2470 b: float,
2471 kE: float = 1.0, # noqa: N803
2472 whitepoint: None | float | str | tuple | list = None,
2473 ) -> tuple[float, float, float]:
2474 """Convert from Lab to DIN99d.
2475
2476 Args:
2477 L (float): The L value of the color.
2478 a (float): The a value of the color.
2479 b (float): The b value of the color.
2480 kE (float, optional): The kE value. Currently not used.
2481 whitepoint (None | float | str | list | tuple): The whitepoint to
2482 use. Defaults to D50.
2483
2484 Returns:
2485 tuple[float, float, float]: The l99, a99, b99 values.
2486 """
2487 return XYZ2DIN99d(*Lab2XYZ(L, a, b, whitepoint, scale=100), whitepoint)
2488
2489
2490 def Lab2DIN99LCH( # noqa: N802
2491 L: float, # noqa: N803
2492 a: float,
2493 b: float,
2494 kCH: float = 1.0, # noqa: N803
2495 kE: float = 1.0, # noqa: N803
2496 ) -> tuple[float, float, float]:
2497 """Convert from Lab to DIN99 LCH.
2498
2499 Args:
2500 L (float): The L value of the color.
2501 a (float): The a value of the color.
2502 b (float): The b value of the color.
2503 kCH (float): The kCH value.
2504 kE (float): The kE value.
2505
2506 Returns:
2507 tuple[float, float, float]: The l99, c99, h99 values.
2508 """
2509 return Lab2DIN99familyLCH(
2510 L, a, b, 105.51, 0.0158, 16, 0.7, 1 / (0.045 * kCH * kE), 0.045, kE, 0
2511 )
2512
2513
2514 def Lab2DIN99bLCH( # noqa: N802
2515 L: float, # noqa: N803
2516 a: float,
2517 b: float,
2518 kE: float = 1.0, # noqa: N803
2519 ) -> tuple[float, float, float]:
2520 """Convert from Lab to DIN99b LCH.
2521
2522 Args:
2523 L (float): The L value of the color.
2524 a (float): The a value of the color.
2525 b (float): The b value of the color.
2526 kE (float): The kE value. Unused, but kept for compatibility.
2527
2528 Returns:
2529 tuple[float, float, float]: The l99, c99, h99 values.
2530 """
2531 return Lab2DIN99familyLCH(L, a, b, 303.67, 0.0039, 26, 0.83, 23, 0.075)
2532
2533
2534 def Lab2DIN99oLCH( # noqa: N802
2535 L: float, # noqa: N803
2536 a: float,
2537 b: float,
2538 kCH: float = 1.0, # noqa: N803
2539 kE: float = 1.0, # noqa: N803
2540 ) -> tuple[float, float, float]:
2541 """Convert from Lab to DIN99o LCH.
2542
2543 Args:
2544 L (float): The L value of the color.
2545 a (float): The a value of the color.
2546 b (float): The b value of the color.
2547 kCH (float, optional): The kCH value. Defaults to 1.0.
2548 kE (float, optional): The kE value. Defaults to 1.0.
2549
2550 Returns:
2551 tuple[float, float, float]: The l99, c99, h99 values.
2552 """
2553 return Lab2DIN99familyLCH(
2554 L, a, b, 303.67, 0.0039, 26, 0.83, 1 / (0.0435 * kCH * kE), 0.075, kE
2555 )
2556
2557
2558 def Lab2DIN99familyLCH( # noqa: N802
2559 L: float, # noqa: N803
2560 a: float,
2561 b: float,
2562 l1: float,
2563 l2: float,
2564 deg: float,
2565 f1: float,
2566 c1: float,
2567 c2: float,
2568 kE: float = 1.0, # noqa: N803
2569 hdeg: None | float = None,
2570 ) -> tuple[float, float, float]:
2571 """Convert from Lab to DIN99 family LCH.
2572
2573 Args:
2574 L (float): The L value of the color.
2575 a (float): The a value of the color.
2576 b (float): The b value of the color.
2577 l1 (float): The l1 value.
2578 l2 (float): The l2 value.
2579 deg (float): The degree value.
2580 f1 (float): The f1 value.
2581 c1 (float): The c1 value.
2582 c2 (float): The c2 value.
2583 kE (float): The kE value.
2584 hdeg (None | float): The hdeg value. Defaults to None.
2585
2586 Returns:
2587 tuple[float, float, float]: The l99, c99, h99 values.
2588 """
2589 l99, g, h99ef, _ = Lab2DIN99familyLGhrad(L, a, b, kE, l1, l2, deg, f1)
2590 c99 = c1 * math.log(1 + c2 * g)
2591 if hdeg is None:
2592 hdeg = deg
2593 h99 = h99ef * 180 / math.pi + hdeg
2594 return l99, c99, h99
2595
2596
2597 def Lab2DIN99familyLGhrad( # noqa: N802
2598 L: float, # noqa: N803
2599 a: float,
2600 b: float,
2601 kE: float, # noqa: N803
2602 l1: float,
2603 l2: float,
2604 deg: float,
2605 f1: float,
2606 ) -> tuple[float, float, float, float]:
2607 """Convert from Lab to DIN99 family LCH.
2608
2609 Args:
2610 L (float): The L value of the color.
2611 a (float): The a value of the color.
2612 b (float): The b value of the color.
2613 kE (float): The kE value.
2614 l1 (float): The l1 value.
2615 l2 (float): The l2 value.
2616 deg (float): The degree value.
2617 f1 (float): The f1 value.
2618
2619 Returns:
2620 tuple[float, float, float, float]: The l99, G, h99ef values.
2621 """
2622 l99 = (1.0 / kE) * l1 * math.log(1 + l2 * L)
2623 rad = deg * math.pi / 180
2624 if rad != 0:
2625 ar = math.cos(rad) # a rotation term
2626 br = math.sin(rad) # b rotation term
2627 e = a * ar + b * br
2628 f = f1 * (b * ar - a * br)
2629 else:
2630 e = a
2631 f = f1 * b
2632 g = math.sqrt(math.pow(e, 2) + math.pow(f, 2))
2633 h99ef = math.atan2(f, e)
2634 return l99, g, h99ef, rad
2635
2636
2637 def Lab2LCHab(L: float, a: float, b: float) -> tuple[float, float, float]: # noqa: N802, N803
2638 """Convert from Lab to LCHab.
2639
2640 Args:
2641 L (float): The L value of the color.
2642 a (float): The a value of the color.
2643 b (float): The b value of the color.
2644
2645 Returns:
2646 tuple[float, float, float]: The LCHab values.
2647 """
2648 c = math.sqrt(math.pow(a, 2) + math.pow(b, 2))
2649 h = 180.0 * math.atan2(b, a) / math.pi
2650 if h < 0.0:
2651 h += 360.0
2652 return L, c, h
2653
2654
2655 def Lab2Luv( # noqa: N802
2656 L: float, # noqa: N803
2657 a: float,
2658 b: float,
2659 whitepoint: None | float | str | list | tuple = None,
2660 scale: float = 100,
2661 ) -> tuple[float, float, float]:
2662 """Convert from Lab to Luv.
2663
2664 Args:
2665 L (float): The L value of the color.
2666 a (float): The a value of the color.
2667 b (float): The b value of the color.
2668 whitepoint (None | float | str | list | tuple): The whitepoint to
2669 use. Defaults to D50.
2670 scale (float): The scale factor to apply to the output values.
2671 Defaults to 100.
2672
2673 Returns:
2674 tuple[float, float, float]: The Luv values.
2675 """
2676 return XYZ2Luv(*Lab2XYZ(L, a, b, whitepoint, scale), whitepoint)
2677
2678
2679 def Lab2RGB( # noqa: N802
2680 L: float, # noqa: N803
2681 a: float,
2682 b: float,
2683 rgb_space: None | str | list | tuple = None,
2684 scale: float = 1.0,
2685 round_: bool = False,
2686 clamp: bool = True,
2687 whitepoint: None | float | str | list | tuple = None,
2688 whitepoint_source: None | float | str | list | tuple = None,
2689 noadapt: bool = False,
2690 cat: str = "Bradford",
2691 ) -> list[float]:
2692 """Convert from Lab to RGB.
2693
2694 Args:
2695 L (float): The L value of the color.
2696 a (float): The a value of the color.
2697 b (float): The b value of the color.
2698 rgb_space (str or tuple): The RGB space to use. Defaults to sRGB.
2699 scale (float): The scale factor to apply to the output values.
2700 Defaults to 1.0.
2701 round_ (bool): Whether to round the output values. Defaults to False.
2702 clamp (bool): Whether to clamp the output values. Defaults to True.
2703 whitepoint (None | float | str | list | tuple): The whitepoint to
2704 use. Defaults to D50.
2705 whitepoint_source (None | float | str | list | tuple): The source
2706 whitepoint to use. Defaults to D50.
2707 noadapt (bool): Whether to skip chromatic adaptation. Defaults to False.
2708 cat (str): The chromatic adaptation transform to use. Defaults to
2709 "Bradford".
2710
2711 Returns:
2712 list[float]: The RGB values.
2713 """
2714 x, y, z = Lab2XYZ(L, a, b, whitepoint)
2715 if not noadapt:
2716 rgb_space = get_rgb_space(rgb_space)
2717 x, y, z = adapt(x, y, z, whitepoint_source, rgb_space[1], cat)
2718 return XYZ2RGB(x, y, z, rgb_space, scale, round_, clamp)
2719
2720
2721 def Lab2XYZ( # noqa: N802
2722 L: float, # noqa: N803
2723 a: float,
2724 b: float,
2725 whitepoint: None | float | str | list | tuple = None,
2726 scale: float = 1.0,
2727 ) -> tuple[float, float, float]:
2728 """Convert from Lab to XYZ.
2729
2730 The input L value needs to be in the nominal range [0.0, 100.0] and
2731 other input values scaled accordingly.
2732 The output XYZ values are in the nominal range [0.0, scale].
2733
2734 whitepoint can be string (e.g. "D50"), a tuple of XYZ coordinates or
2735 color temperature as float or int. Defaults to D50 if not set.
2736
2737 Based on formula from http://brucelindbloom.com/Eqn_Lab_to_XYZ.html
2738
2739 Args:
2740 L (float): The L value of the color.
2741 a (float): The a value of the color.
2742 b (float): The b value of the color.
2743 whitepoint (None | float | str | list | tuple): The whitepoint to
2744 use. Defaults to D50.
2745 scale (float): The scale factor to apply to the output values.
2746 Defaults to 1.0.
2747
2748 Returns:
2749 tuple[float, float, float]: The XYZ values.
2750 """
2751 fy = (L + 16) / 116.0
2752 fx = a / 500.0 + fy
2753 fz = fy - b / 200.0
2754
2755 if math.pow(fx, 3.0) > LSTAR_E:
2756 xr = math.pow(fx, 3.0)
2757 else:
2758 xr = (116.0 * fx - 16) / LSTAR_K
2759
2760 yr = math.pow((L + 16) / 116.0, 3.0) if L > LSTAR_K * LSTAR_E else L / LSTAR_K
2761 zr = (
2762 math.pow(fz, 3.0)
2763 if math.pow(fz, 3.0) > LSTAR_E
2764 else (116.0 * fz - 16) / LSTAR_K
2765 )
2766
2767 Xr, Yr, Zr = get_whitepoint(whitepoint, scale) # noqa: N806
2768 return (xr * Xr), (yr * Yr), (zr * Zr)
2769
2770
2771 def Lab2xyY( # noqa: N802
2772 L: float, # noqa: N803
2773 a: float,
2774 b: float,
2775 whitepoint: None | float | str | list | tuple = None,
2776 scale: float = 1.0,
2777 ) -> tuple[float, float, float]:
2778 """Convert from Lab to xyY.
2779
2780 Args:
2781 L (float): The L value of the color.
2782 a (float): The a value of the color.
2783 b (float): The b value of the color.
2784 whitepoint (None | float | str | list | tuple): The whitepoint to
2785 use. Defaults to D50.
2786 scale (float): The scale factor to apply to the output values.
2787 Defaults to 1.0.
2788
2789 Returns:
2790 tuple[float, float, float]: The xyY values.
2791 """
2792 return XYZ2xyY(*Lab2XYZ(L, a, b, whitepoint, scale), whitepoint)
2793
2794
2795 def Luv2LCHuv(L: float, u: float, v: float) -> tuple[float, float, float]: # noqa: N802, N803
2796 """Convert from Luv to LCHuv.
2797
2798 Args:
2799 L (float): The L value of the color.
2800 u (float): The u' value of the color.
2801 v (float): The v' value of the color.
2802
2803 Returns:
2804 tuple[float, float, float]: The LCHuv values.
2805 """
2806 c = math.sqrt(math.pow(u, 2) + math.pow(v, 2))
2807 h = 180.0 * math.atan2(v, u) / math.pi
2808 if h < 0.0:
2809 h += 360.0
2810 return L, c, h
2811
2812
2813 def Luv2RGB( # noqa: N802
2814 L: float, # noqa: N803
2815 u: float,
2816 v: float,
2817 rgb_space: None | str | list | tuple = None,
2818 scale: float = 1.0,
2819 round_: bool = False,
2820 clamp: bool = True,
2821 whitepoint: None | float | str | list | tuple = None,
2822 ) -> list[float]:
2823 """Convert from Luv to RGB.
2824
2825 Args:
2826 L (float): The L value of the color.
2827 u (float): The u' value of the color.
2828 v (float): The v' value of the color.
2829 rgb_space (str or tuple): The RGB space to use. Defaults to sRGB.
2830 scale (float): The scale factor to apply to the output values.
2831 Defaults to 1.0.
2832 round_ (bool): Whether to round the output values. Defaults to False.
2833 clamp (bool): Whether to clamp the output values. Defaults to True.
2834 whitepoint (None | float | str | list | tuple): The whitepoint to
2835 use. Defaults to D50.
2836
2837 Returns:
2838 tuple[float, float, float]: The RGB values.
2839 """
2840 return XYZ2RGB(*Luv2XYZ(L, u, v, whitepoint), rgb_space, scale, round_, clamp)
2841
2842
2843 def u_v_2xy(u: float, v: float) -> tuple[float, float]:
2844 """Convert from u'v' to xy.
2845
2846 Args:
2847 u (float): The u' value of the color.
2848 v (float): The v' value of the color.
2849
2850 Returns:
2851 tuple[float, float]: The xy values.
2852 """
2853 x = (9.0 * u) / (6 * u - 16 * v + 12)
2854 y = (4 * v) / (6 * u - 16 * v + 12)
2855
2856 return x, y
2857
2858
2859 def Luv2XYZ( # noqa: N802
2860 L: float, # noqa: N803
2861 u: float,
2862 v: float,
2863 whitepoint: None | str | float | list | tuple = None,
2864 scale: float = 1.0,
2865 ) -> tuple[float, float, float]:
2866 """Convert from Luv to XYZ.
2867
2868 Args:
2869 L (float): The L value of the color.
2870 u (float): The u' value of the color.
2871 v (float): The v' value of the color.
2872 whitepoint (str or tuple): The whitepoint to use. Defaults to D50.
2873 scale (float): The scale factor to apply to the output values.
2874 Defaults to 1.0.
2875
2876 Returns:
2877 tuple[float, float, float]: The XYZ values.
2878 """
2879 xr, yr, zr = get_whitepoint(whitepoint)
2880
2881 y = math.pow((L + 16.0) / 116.0, 3) if L > LSTAR_K * LSTAR_E else L / LSTAR_K
2882
2883 uo = (4.0 * xr) / (xr + 15.0 * yr + 3.0 * zr)
2884 vo = (9.0 * yr) / (xr + 15.0 * yr + 3.0 * zr)
2885
2886 a = (1.0 / 3.0) * (((52.0 * L) / (u + 13 * L * uo)) - 1)
2887 b = -5.0 * y
2888 c = -(1.0 / 3.0)
2889 d = y * (((39.0 * L) / (v + 13 * L * vo)) - 5)
2890
2891 x = (d - b) / (a - c)
2892 z = x * a + b
2893
2894 return tuple([v * scale for v in (x, y, z)])
2895
2896
2897 def RGB2HSI( # noqa: N802
2898 R: float, # noqa: N803
2899 G: float, # noqa: N803
2900 B: float, # noqa: N803
2901 scale: float = 1.0,
2902 ) -> tuple[float, float, float]:
2903 """Convert from RGB to HSI.
2904
2905 The input RGB values need to be in the nominal range [0.0, 1.0] and
2906 the output HSI values are in the nominal range [0.0, scale].
2907
2908 Args:
2909 R (float): The red value of the color.
2910 G (float): The green value of the color.
2911 B (float): The blue value of the color.
2912 scale (float): The scale factor to apply to the output values.
2913 Defaults to 1.0.
2914
2915 Returns:
2916 tuple[float, float, float]: The HSI values.
2917 """
2918 i = (R + G + B) / 3.0
2919 s = 1 - min(R, G, B) / i if i else 0
2920 if not R == G == B:
2921 h = math.atan2(math.sqrt(3) * (G - B), 2 * R - G - B) / math.pi / 2
2922 if h < 0:
2923 h += 1.0
2924 if h > 1:
2925 h -= 1.0
2926 else:
2927 h = 0
2928 return h * scale, s * scale, i * scale
2929
2930
2931 def RGB2HSL( # noqa: N802
2932 R: float, # noqa: N803
2933 G: float, # noqa: N803
2934 B: float, # noqa: N803
2935 scale: float = 1.0,
2936 ) -> tuple[float, float, float]:
2937 """Convert from RGB to HSL.
2938
2939 The input RGB values need to be in the nominal range [0.0, 1.0] and
2940 the output HSL values are in the nominal range [0.0, scale].
2941
2942 Args:
2943 R (float): The red value of the color.
2944 G (float): The green value of the color.
2945 B (float): The blue value of the color.
2946 scale (float): The scale factor to apply to the output values.
2947 Defaults to 1.0.
2948
2949 Returns:
2950 tuple[float, float, float]: The HSL values.
2951 """
2952 h, l, s = colorsys.rgb_to_hls(R, G, B)
2953 return tuple(v * scale for v in (h, s, l))
2954
2955
2956 def RGB2HSV( # noqa: N802
2957 R: float, # noqa: N803
2958 G: float, # noqa: N803
2959 B: float, # noqa: N803
2960 scale: float = 1.0,
2961 ) -> tuple[float, float, float]:
2962 """Convert from RGB to HSV.
2963
2964 The input RGB values need to be in the nominal range [0.0, 1.0] and
2965 the output HSV values are in the nominal range [0.0, scale].
2966
2967 Args:
2968 R (float): The red value of the color.
2969 G (float): The green value of the color.
2970 B (float): The blue value of the color.
2971 scale (float): The scale factor to apply to the output values.
2972 Defaults to 1.0.
2973
2974 Returns:
2975 tuple[float, float, float]: The HSV values.
2976 """
2977 return tuple(v * scale for v in colorsys.rgb_to_hsv(R, G, B))
2978
2979
2980 def LinearRGB2ICtCp( # noqa: N802
2981 R: float, # noqa: N803
2982 G: float, # noqa: N803
2983 B: float, # noqa: N803
2984 oetf: None | Callable = None,
2985 ) -> tuple[float, float, float]:
2986 """Rec. 2020 linear RGB to non-linear ICtCp.
2987
2988 http://www.dolby.com/us/en/technologies/dolby-vision/ICtCp-white-paper.pdf
2989 """
2990 if oetf is None:
2991
2992 def oetf(FD: float) -> float: # noqa: N803
2993 """Default OETF for Rec. 2020.
2994
2995 Args:
2996 FD (float): The value to apply the OETF to.
2997
2998 Returns:
2999 float: The transformed value.
3000 """
3001 return special_pow(FD, 1.0 / -2084)
3002
3003 lms = LinearRGB2LMS_matrix * (R, G, B)
3004 l_, m_, s_ = (oetf(FD) for FD in lms)
3005 i, ct, cp = L_M_S_2ICtCp_matrix * (l_, m_, s_)
3006 return i, ct, cp
3007
3008
3009 def ICtCp2LinearRGB( # noqa: N802
3010 I: float, # noqa: N803
3011 Ct: float, # noqa: N803
3012 Cp: float, # noqa: N803
3013 eotf: None | Callable = None,
3014 ) -> tuple[float, float, float]:
3015 """Non-linear ICtCp to Rec. 2020 linear RGB.
3016
3017 http://www.dolby.com/us/en/technologies/dolby-vision/ICtCp-white-paper.pdf
3018
3019 Args:
3020 I (float): The I value of the color.
3021 Ct (float): The Ct value of the color.
3022 Cp (float): The Cp value of the color.
3023 eotf (function): The electro-optical transfer function to use.
3024 Defaults to the Rec. 2020 EOTF.
3025 This function should take a single argument and return a float.
3026 The default function is the Rec. 2020 OETF.
3027 See the `special_pow` function for more details.
3028
3029 Returns:
3030 tuple[float, float, float]: The RGB values.
3031 """
3032 if eotf is None:
3033
3034 def eotf(v: float) -> float:
3035 """Default EOTF for Rec. 2020.
3036
3037 Args:
3038 v (float): The value to apply the EOTF to.
3039
3040 Returns:
3041 float: The transformed value.
3042 """
3043 return special_pow(v, -2084)
3044
3045 l_m_s_ = ICtCp2L_M_S__matrix * (I, Ct, Cp)
3046 l, m, s = (eotf(v) for v in l_m_s_)
3047 return LMS2LinearRGB_matrix * (l, m, s)
3048
3049
3050 def RGB2ICtCp( # noqa: N802
3051 R: float, # noqa: N803
3052 G: float, # noqa: N803
3053 B: float, # noqa: N803
3054 rgb_space: None | str | list | tuple = "Rec. 2020",
3055 eotf: None | Callable = None,
3056 clamp: bool = False,
3057 oetf: None | Callable = None,
3058 ) -> tuple[float, float, float]:
3059 """R'G'B' to ICtCp.
3060
3061 Args:
3062 R (float): The R' value of the color.
3063 G (float): The G' value of the color.
3064 B (float): The B' value of the color.
3065 rgb_space (str): The RGB space to use for conversion. Defaults to
3066 "Rec. 2020".
3067 eotf (None | callable): The electro-optical transfer function to use.
3068 Defaults to the Rec. 2020 EOTF.
3069 This function should take a single argument and return a float.
3070 The default function is the inverse of the Rec. 2020 EOTF.
3071 See the `special_pow` function for more details.
3072 clamp (bool): If True, clamp the output values to [0, 1].
3073 Defaults to False.
3074 oetf (None | callable): The opto-electrical transfer function to use.
3075 Defaults to the Rec. 2020 OETF.
3076 This function should take a single argument and return a float.
3077 The default function is the Rec. 2020 OETF.
3078 See the `special_pow` function for more details.
3079
3080 Returns:
3081 tuple[float, float, float]: The ICtCp values.
3082 """
3083 if eotf is None:
3084
3085 def eotf(v: float) -> float:
3086 """Default EOTF for Rec. 2020.
3087
3088 Args:
3089 v (float): The value to apply the EOTF to.
3090
3091 Returns:
3092 float: The transformed value.
3093 """
3094 return special_pow(v, -2084)
3095
3096 if oetf is None:
3097
3098 def oetf(E: float) -> float: # noqa: N803
3099 """Default OETF for Rec. 2020.
3100
3101 Args:
3102 E (float): The value to apply the OETF to.
3103
3104 Returns:
3105 float: The transformed value.
3106 """
3107 return special_pow(E, 1.0 / -2084)
3108
3109 return XYZ2ICtCp(*RGB2XYZ(R, G, B, rgb_space, eotf=eotf), clamp, oetf)
3110
3111
3112 def ICtCp2RGB( # noqa: N802
3113 I: float, # noqa: N803
3114 Ct: float, # noqa: N803
3115 Cp: float, # noqa: N803
3116 rgb_space: None | str | list | tuple = "Rec. 2020",
3117 eotf: None | Callable = None,
3118 clamp: bool = False,
3119 oetf: None | Callable = None,
3120 ) -> list[float]:
3121 """ICtCp to R'G'B'.
3122
3123 Args:
3124 I (float): The I value of the color.
3125 Ct (float): The Ct value of the color.
3126 Cp (float): The Cp value of the color.
3127 rgb_space (str): The RGB space to use for conversion. Defaults to
3128 "Rec. 2020".
3129 eotf (None | callable): The electro-optical transfer function to use.
3130 Defaults to the Rec. 2020 EOTF.
3131 This function should take a single argument and return a float.
3132 The default function is the inverse of the Rec. 2020 EOTF.
3133 See the `special_pow` function for more details.
3134 clamp (bool): If True, clamp the output values to [0, 1].
3135 Defaults to False.
3136 oetf (None | callable): The opto-electrical transfer function to use.
3137 Defaults to the Rec. 2020 OETF.
3138 This function should take a single argument and return a float.
3139 The default function is the Rec. 2020 OETF.
3140 See the `special_pow` function for more details.
3141
3142 Returns:
3143 tuple: The RGB values.
3144 """
3145 if eotf is None:
3146
3147 def eotf(v: float) -> float:
3148 """Default EOTF for Rec. 2020.
3149
3150 Args:
3151 v (float): The value to apply the EOTF to.
3152
3153 Returns:
3154 float: The transformed value.
3155 """
3156 return special_pow(v, -2084)
3157
3158 if oetf is None:
3159
3160 def oetf(E: float) -> float: # noqa: N803
3161 """Default OETF for Rec. 2020.
3162
3163 Args:
3164 E (float): The value to apply the OETF to.
3165
3166 Returns:
3167 float: The transformed value.
3168 """
3169 return special_pow(E, 1.0 / -2084)
3170
3171 return XYZ2RGB(*ICtCp2XYZ(I, Ct, Cp, eotf), rgb_space, clamp=clamp, oetf=oetf)
3172
3173
3174 def XYZ2ICtCp( # noqa: N802
3175 X: float, # noqa: N803
3176 Y: float, # noqa: N803
3177 Z: float, # noqa: N803
3178 clamp: bool = False,
3179 oetf: None | Callable = None,
3180 ) -> tuple[float, float, float]:
3181 """XYZ to ICtCp.
3182
3183 Args:
3184 X (float): The X value of the color.
3185 Y (float): The Y value of the color.
3186 Z (float): The Z value of the color.
3187 clamp (bool): If True, clamp the output values to [0, 1].
3188 Defaults to False.
3189 oetf (function): The opto-electrical transfer function to use.
3190 Defaults to the Rec. 2020 OETF.
3191 This function should take a single argument and return a float.
3192 The default function is the Rec. 2020 OETF.
3193 See the `special_pow` function for more details.
3194
3195 Returns:
3196 tuple: The ICtCp values.
3197 """
3198 if oetf is None:
3199
3200 def oetf(E: float) -> float: # noqa: N803
3201 """Default OETF for Rec. 2020.
3202
3203 Args:
3204 E (float): The value to apply the OETF to.
3205
3206 Returns:
3207 float: The transformed value.
3208 """
3209 return special_pow(E, 1.0 / -2084)
3210
3211 return LinearRGB2ICtCp(
3212 *XYZ2RGB(X, Y, Z, "Rec. 2020", clamp=clamp, oetf=lambda v: v), oetf
3213 )
3214
3215
3216 def ICtCp2XYZ(I: float, Ct: float, Cp: float, eotf: None | Callable = None) -> tuple: # noqa: N802, N803
3217 """ICtCp to XYZ.
3218
3219 Args:
3220 I (float): The I value of the color.
3221 Ct (float): The Ct value of the color.
3222 Cp (float): The Cp value of the color.
3223 eotf (function): The electro-optical transfer function to use.
3224 Defaults to the Rec. 2020 EOTF.
3225 This function should take a single argument and return a float.
3226 The default function is the inverse of the Rec. 2020 EOTF.
3227 See the `special_pow` function for more details.
3228
3229 Returns:
3230 tuple: The XYZ values.
3231 """
3232 if eotf is None:
3233
3234 def eotf(v: float) -> float:
3235 """Default EOTF for Rec. 2020.
3236
3237 Args:
3238 v (float): The value to apply the EOTF to.
3239
3240 Returns:
3241 float: The transformed value.
3242 """
3243 return special_pow(v, -2084)
3244
3245 return RGB2XYZ(*ICtCp2LinearRGB(I, Ct, Cp, eotf), "Rec. 2020", eotf=lambda v: v)
3246
3247
3248 def RGB2Lab( # noqa: N802
3249 R: float, # noqa: N803
3250 G: float, # noqa: N803
3251 B: float, # noqa: N803
3252 rgb_space: None | str | list | tuple = None,
3253 whitepoint: None | float | str | list | tuple = None,
3254 noadapt: bool = False,
3255 cat: str = "Bradford",
3256 ) -> tuple[float, float, float]:
3257 """Convert from RGB to Lab.
3258
3259 Args:
3260 R (float): The R' value of the color.
3261 G (float): The G' value of the color.
3262 B (float): The B' value of the color.
3263 rgb_space (None | str | list | tuple): The RGB space
3264 to use for conversion. Defaults to sRGB if not set.
3265 If a string is given, it must be a valid RGB space name.
3266 If a list or tuple is given, it must be in the format
3267 (gamma, whitepoint, red, green, blue).
3268 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3269 coordinates, or a color temperature in degrees K (float or
3270 int). The gamma should be a float. The RGB primaries red,
3271 green, blue should be lists or tuples of xyY coordinates
3272 (only x and y will be used, so Y can be zero or None).
3273 whitepoint (None | str | tuple): The whitepoint to use for conversion.
3274 If None, the whitepoint of the RGB space will be used.
3275 If a string is given, it must be a valid whitepoint name.
3276 If a tuple is given, it must be in the format (X, Y, Z).
3277 The whitepoint can also be a color temperature in degrees K
3278 (float or int).
3279 noadapt (bool): If True, no chromatic adaptation will be applied.
3280 Defaults to False.
3281 cat (str): The chromatic adaptation transform to use. Defaults to
3282 "Bradford". Other options include "VonKries" and "CAT02".
3283 See the `adapt` function for more details.
3284
3285 Returns:
3286 tuple[float, float, float]: The Lab values.
3287 """
3288 x, y, z = RGB2XYZ(R, G, B, rgb_space, scale=100)
3289 if not noadapt:
3290 rgb_space = get_rgb_space(rgb_space)
3291 x, y, z = adapt(x, y, z, rgb_space[1], whitepoint, cat)
3292 return XYZ2Lab(x, y, z, whitepoint=whitepoint)
3293
3294
3295 def RGB2XYZ( # noqa: N802
3296 R: float, # noqa: N803
3297 G: float, # noqa: N803
3298 B: float, # noqa: N803
3299 rgb_space: None | str | list | tuple = None,
3300 scale: float = 1.0,
3301 eotf: None | Callable = None,
3302 ) -> tuple[float, float, float]:
3303 """Convert from RGB to XYZ.
3304
3305 Use optional RGB colorspace definition, which can be a named colorspace
3306 (e.g. "CIE RGB") or must be a tuple in the following format:
3307
3308 (gamma, whitepoint, red, green, blue)
3309
3310 whitepoint can be a string (e.g. "D50"), a tuple of XYZ coordinates,
3311 or a color temperatur in degrees K (float or int). Gamma should be a float.
3312 The RGB primaries red, green, blue should be lists or tuples of xyY
3313 coordinates (only x and y will be used, so Y can be zero or None).
3314
3315 If no colorspace is given, it defaults to sRGB.
3316
3317 Based on formula from http://brucelindbloom.com/Eqn_RGB_to_XYZ.html
3318
3319 Implementation Notes:
3320 1. The transformation matrix [M] is calculated from the RGB reference
3321 primaries as discussed here:
3322 http://brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html
3323 2. The gamma values for many common RGB color spaces may be found here:
3324 http://brucelindbloom.com/WorkingSpaceInfo.html#Specifications
3325 3. Your input RGB values may need to be scaled before using the above.
3326 For example, if your values are in the range [0, 255], you must first
3327 divide each by 255.0.
3328 4. The output XYZ values are in the nominal range [0.0, scale].
3329 5. The XYZ values will be relative to the same reference white as the
3330 RGB system. If you want XYZ relative to a different reference white,
3331 you must apply a chromatic adaptation transform
3332 [http://brucelindbloom.com/Eqn_ChromAdapt.html] to the XYZ color to
3333 convert it from the reference white of the RGB system to the desired
3334 reference white.
3335 6. Sometimes the more complicated special case of sRGB shown above is
3336 replaced by a "simplified" version using a straight gamma function
3337 with gamma = 2.2.
3338
3339 Args:
3340 R (float): The R' value of the color.
3341 G (float): The G' value of the color.
3342 B (float): The B' value of the color.
3343 rgb_space (None | str | list | tuple): The RGB space
3344 to use for conversion. Defaults to sRGB if not set.
3345 If a string is given, it must be a valid RGB space name.
3346 If a list or tuple is given, it must be in the format
3347 (gamma, whitepoint, red, green, blue).
3348 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3349 coordinates, or a color temperature in degrees K (float or
3350 int). The gamma should be a float. The RGB primaries red,
3351 green, blue should be lists or tuples of xyY coordinates
3352 (only x and y will be used, so Y can be zero or None).
3353 scale (float): The scale factor for the output values. Defaults to 1.0.
3354 eotf (function): A function to apply to the RGB values before conversion.
3355 If not set, the RGB values will be treated as linear RGB values.
3356 This function should take a single argument and return a float.
3357 The default function is the inverse of the Rec. 2020 EOTF.
3358 See the `special_pow` function for more details.
3359
3360 Returns:
3361 tuple[float, float, float]: The XYZ values.
3362
3363 """
3364 trc, _, _, _, _, matrix = get_rgb_space(rgb_space)
3365 rgb = [R, G, B]
3366 is_trc = isinstance(trc, (list, tuple))
3367 for i, v in enumerate(rgb):
3368 gamma = trc[i] if is_trc else trc
3369 if eotf:
3370 rgb[i] = eotf(v)
3371 elif isinstance(gamma, (list, tuple)):
3372 rgb[i] = interp(
3373 v, [n / float(len(gamma) - 1) for n in range(len(gamma))], gamma
3374 )
3375 else:
3376 rgb[i] = special_pow(v, gamma)
3377 xyz = matrix * rgb
3378 return tuple(v * scale for v in xyz)
3379
3380
3381 def RGB2xyY( # noqa: N802
3382 R: float, # noqa: N803
3383 G: float, # noqa: N803
3384 B: float, # noqa: N803
3385 rgb_space: None | str | list | tuple = None,
3386 scale: float = 1.0,
3387 eotf: None | Callable = None,
3388 ) -> tuple[float, float, float]:
3389 """Convert RGB to xyY.
3390
3391 Args:
3392 R (float): The R' value of the color.
3393 G (float): The G' value of the color.
3394 B (float): The B' value of the color.
3395 rgb_space (None | str | list | tuple): The RGB space
3396 to use for conversion. Defaults to sRGB if not set.
3397 If a string is given, it must be a valid RGB space name.
3398 If a list or tuple is given, it must be in the format
3399 (gamma, whitepoint, red, green, blue).
3400 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3401 coordinates, or a color temperature in degrees K (float or
3402 int). The gamma should be a float. The RGB primaries red,
3403 green, blue should be lists or tuples of xyY coordinates
3404 (only x and y will be used, so Y can be zero or None).
3405 scale (float): The scale factor for the output values. Defaults to 1.0.
3406 eotf (function): A function to apply to the RGB values before conversion.
3407
3408 Returns:
3409 tuple[float, float, float]: The xyY values.
3410 """
3411 return XYZ2xyY(
3412 *RGB2XYZ(R, G, B, rgb_space, scale, eotf),
3413 whitepoint=RGB2XYZ(1, 1, 1, rgb_space, scale, eotf),
3414 )
3415
3416
3417 def RGB2YCbCr( # noqa: N802
3418 R: float, # noqa: N803
3419 G: float, # noqa: N803
3420 B: float, # noqa: N803
3421 rgb_space: None | str | list | tuple = "NTSC 1953",
3422 bits: int = 8,
3423 fullrange: bool = False,
3424 ) -> tuple[float, float, float]:
3425 """R'G'B' to Y'CbCr quantized to n bits.
3426
3427 Args:
3428 R (float): The R' value of the color.
3429 G (float): The G' value of the color.
3430 B (float): The B' value of the color.
3431 rgb_space (None | str | list | tuple): The RGB space
3432 to use for conversion. Defaults to sRGB if not set.
3433 If a string is given, it must be a valid RGB space name.
3434 If a list or tuple is given, it must be in the format
3435 (gamma, whitepoint, red, green, blue).
3436 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3437 coordinates, or a color temperature in degrees K (float or
3438 int). The gamma should be a float. The RGB primaries red,
3439 green, blue should be lists or tuples of xyY coordinates
3440 (only x and y will be used, so Y can be zero or None).
3441 bits (int): The number of bits to quantize to. Defaults to 8.
3442 fullrange (bool): Whether to use full range or limited range. Defaults to False.
3443
3444 Returns:
3445 tuple: The Y'CbCr values.
3446 """
3447 return YPbPr2YCbCr(*RGB2YPbPr(R, G, B, rgb_space), bits=bits, fullrange=fullrange)
3448
3449
3450 def RGB2YPbPr( # noqa: N802
3451 R: float, # noqa: N803
3452 G: float, # noqa: N803
3453 B: float, # noqa: N803
3454 rgb_space: None | str | list | tuple = "NTSC 1953",
3455 ) -> tuple[float, float, float]:
3456 """R'G'B' to Y'PbPr.
3457
3458 Args:
3459 R (float): The R' value of the color.
3460 G (float): The G' value of the color.
3461 B (float): The B' value of the color.
3462 rgb_space (None | str | list | tuple): The RGB space
3463 to use for conversion. Defaults to sRGB if not set.
3464 If a string is given, it must be a valid RGB space name.
3465 If a list or tuple is given, it must be in the format
3466 (gamma, whitepoint, red, green, blue).
3467 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3468 coordinates, or a color temperature in degrees K (float or int).
3469 The gamma should be a float. The RGB primaries red, green,
3470 blue should be lists or tuples of xyY coordinates (only x and
3471 y will be used, so Y can be zero or None).
3472
3473 Returns:
3474 tuple: The Y'PbPr values.
3475 """
3476 return RGB2YPbPr_matrix(rgb_space) * (R, G, B)
3477
3478
3479 def RGB2YPbPr_matrix(rgb_space: None | str | list | tuple = "NTSC 1953") -> Matrix3x3: # noqa: N802
3480 """Get the RGB to Y'PbPr matrix for the given RGB space.
3481
3482 Args:
3483 rgb_space (None | str | list | tuple): The RGB space
3484 to use for conversion. Defaults to sRGB if not set.
3485 If a string is given, it must be a valid RGB space name.
3486 If a list or tuple is given, it must be in the format
3487 (gamma, whitepoint, red, green, blue).
3488 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3489 coordinates, or a color temperature in degrees K (float or int).
3490 The gamma should be a float. The RGB primaries red, green,
3491 blue should be lists or tuples of xyY coordinates (only x and
3492 y will be used, so Y can be zero or None).
3493
3494 Returns:
3495 Matrix3x3: The RGB to Y'PbPr matrix.
3496 """
3497 matrix = get_rgb_space(rgb_space)[-1]
3498 ndigits = 3 if matrix == get_rgb_space("NTSC 1953")[-1] else 4
3499 kr = round((matrix * (1, 0, 0))[1], ndigits)
3500 kb = round((matrix * (0, 0, 1))[1], ndigits)
3501 kg = 1.0 - kr - kb
3502 pb_scale = (1 - kb) / 0.5
3503 pr_scale = (1 - kr) / 0.5
3504 return Matrix3x3(
3505 [
3506 [kr, kg, kb],
3507 [-kr / pb_scale, -kg / pb_scale, 0.5],
3508 [0.5, -kg / pr_scale, -kb / pr_scale],
3509 ]
3510 )
3511
3512
3513 def YCbCr2YPbPr( # noqa: N802
3514 Y: float, # noqa: N803
3515 Cb: float, # noqa: N803
3516 Cr: float, # noqa: N803
3517 bits: int = 8,
3518 fullrange: bool = False,
3519 ) -> tuple[float, float, float]:
3520 """Y'CbCr to Y'PbPr.
3521
3522 Args:
3523 Y (float): The Y value of the color.
3524 Cb (float): The Cb value of the color.
3525 Cr (float): The Cr value of the color.
3526 bits (int, optional): The number of bits to quantize to. Defaults to 8.
3527 fullrange (bool, optional): Whether to use full range or limited range.
3528 Defaults to False.
3529
3530 Returns:
3531 tuple[float, float, float]: The Y'PbPr values.
3532 """
3533 bitlevels = 2**bits
3534 if not fullrange:
3535 yblack = 16
3536 ywhite = 235
3537 cmax = 240
3538 else:
3539 yblack = 0
3540 ywhite = 255
3541 cmax = 255
3542 yscale = (ywhite - yblack) / 256.0 * bitlevels
3543 Y -= yblack / 256.0 * bitlevels # noqa: N806
3544 Y /= yscale # noqa: N806
3545 cneutral = 128 / 256.0 * bitlevels
3546 cscale = (cmax - yblack) / 256.0 * bitlevels
3547 pb = Cb - cneutral
3548 pb /= cscale
3549 pr = Cr - cneutral
3550 pr /= cscale
3551 return Y, pb, pr
3552
3553
3554 def YCbCr2RGB( # noqa: N802
3555 Y: float, # noqa: N803
3556 Cb: float, # noqa: N803
3557 Cr: float, # noqa: N803
3558 rgb_space: None | str | list | tuple = "NTSC 1953",
3559 bits: int = 8,
3560 fullrange: bool = False,
3561 scale: float = 1.0,
3562 round_: bool = False,
3563 clamp: bool = True,
3564 ) -> list[float]:
3565 """Y'CbCr to R'G'B'.
3566
3567 Args:
3568 Y (float): The Y value of the color.
3569 Cb (float): The Cb value of the color.
3570 Cr (float): The Cr value of the color.
3571 rgb_space (None | str | list | tuple): The RGB space
3572 to use for conversion. Defaults to sRGB if not set.
3573 If a string is given, it must be a valid RGB space name.
3574 If a list or tuple is given, it must be in the format
3575 (gamma, whitepoint, red, green, blue).
3576 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3577 coordinates, or a color temperature in degrees K (float or int).
3578 The gamma should be a float. The RGB primaries red, green,
3579 blue should be lists or tuples of xyY coordinates (only x and
3580 y will be used, so Y can be zero or None).
3581 bits (int): The number of bits to quantize to. Defaults to 8.
3582 fullrange (bool): Whether to use full range or limited range. Defaults to False.
3583 scale (float): The scale factor to apply to the output values.
3584 round_ (int | bool): The number of decimal places to round to.
3585 If False, no rounding is applied. Defaults to False.
3586 clamp (bool): Whether to clamp the output values to [0.0, 1.0].
3587 Defaults to True.
3588
3589 Returns:
3590 list[float]: The R'G'B' values.
3591 """
3592 return YPbPr2RGB(
3593 *YCbCr2YPbPr(Y, Cb, Cr, bits, fullrange), rgb_space, scale, round_, clamp
3594 )
3595
3596
3597 def YPbPr2RGB( # noqa: N802
3598 Y: float, # noqa: N803
3599 Pb: float, # noqa: N803
3600 Pr: float, # noqa: N803
3601 rgb_space: None | str | list | tuple = "NTSC 1953",
3602 scale: float = 1.0,
3603 round_: bool = False,
3604 clamp: bool = True,
3605 ) -> list[float]:
3606 """Y'PbPr to R'G'B'.
3607
3608 Args:
3609 Y (float): The Y value of the color.
3610 Pb (float): The Pb value of the color.
3611 Pr (float): The Pr value of the color.
3612 rgb_space (None | str | list | tuple): The RGB space
3613 to use for conversion. Defaults to sRGB if not set.
3614 If a string is given, it must be a valid RGB space name.
3615 If a list or tuple is given, it must be in the format
3616 (gamma, whitepoint, red, green, blue).
3617 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3618 coordinates, or a color temperature in degrees K (float or int).
3619 The gamma should be a float. The RGB primaries red, green,
3620 blue should be lists or tuples of xyY coordinates (only x and
3621 y will be used, so Y can be zero or None).
3622 scale (float): The scale factor to apply to the output values.
3623 round_ (int | bool): The number of decimal places to round to.
3624 If False, no rounding is applied. Defaults to False.
3625 clamp (bool): Whether to clamp the output values to [0.0, 1.0].
3626 Defaults to True.
3627
3628 Returns:
3629 list[float]: The R'G'B' values.
3630 """
3631 rgb = RGB2YPbPr_matrix(rgb_space).inverted() * (Y, Pb, Pr)
3632 for i in range(3):
3633 if clamp:
3634 rgb[i] = min(1.0, max(0.0, rgb[i]))
3635 rgb[i] *= scale
3636 if round_ is not False:
3637 rgb[i] = round(rgb[i], round_)
3638 return rgb
3639
3640
3641 def YPbPr2YCbCr( # noqa: N802
3642 Y: float, # noqa: N803
3643 Pb: float, # noqa: N803
3644 Pr: float, # noqa: N803
3645 bits: int = 8,
3646 fullrange: bool = False,
3647 ) -> tuple[float, float, float]:
3648 """Y'PbPr to Y'CbCr quantized to n bits.
3649
3650 Args:
3651 Y (float): The Y value of the color.
3652 Pb (float): The Pb value of the color.
3653 Pr (float): The Pr value of the color.
3654 bits (int): The number of bits to quantize to. Defaults to 8.
3655 fullrange (bool): Whether to use full range or limited range. Defaults to False.
3656
3657 Returns:
3658 tuple[float, float, float]: The Y'CbCr values.
3659 """
3660 bitlevels = 2**bits
3661 if not fullrange:
3662 yblack = 16
3663 ywhite = 235
3664 cmax = 240
3665 else:
3666 yblack = 0
3667 ywhite = 255
3668 cmax = 255
3669 yscale = (ywhite - yblack) / 256.0 * bitlevels
3670 Y = yblack / 256.0 * bitlevels + yscale * Y # noqa: N806
3671 cneutral = 128 / 256.0 * bitlevels
3672 cscale = (cmax - yblack) / 256.0 * bitlevels
3673 cb = cneutral + cscale * Pb # noqa: N806
3674 cr = cneutral + cscale * Pr # noqa: N806
3675 # In fullrange mode, Cb and Cr can reach 255.5, so we need to clamp
3676 # Follow ITU-T Rec. T.871 (JPEG)
3677 return (min(max(round(v), 0), bitlevels - 1) for v in (Y, cb, cr))
3678
3679
3680 def RGBsaturation( # noqa: N802
3681 R: float, # noqa: N803
3682 G: float, # noqa: N803
3683 B: float, # noqa: N803
3684 saturation: float,
3685 rgb_space: None | str | list | tuple = None,
3686 ) -> tuple[float, float, float]:
3687 """(De)saturate a RGB color in CIE xy and return the RGB and xyY values.
3688
3689 Args:
3690 R (float): The red value of the color.
3691 G (float): The green value of the color.
3692 B (float): The blue value of the color.
3693 saturation (float): The saturation factor.
3694 0.0 = grayscale, 1.0 = original color, >1.0 = oversaturated.
3695 <0.0 = undersaturated.
3696 rgb_space (None | str | list | tuple): The RGB space
3697 to use for conversion. Defaults to sRGB if not set.
3698 If a string is given, it must be a valid RGB space name.
3699 If a list or tuple is given, it must be in the format
3700 (gamma, whitepoint, red, green, blue).
3701 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3702 coordinates, or a color temperature in degrees K (float or int).
3703 The gamma should be a float. The RGB primaries red, green,
3704 blue should be lists or tuples of xyY coordinates (only x and
3705 y will be used, so Y can be zero or None).
3706
3707 Returns:
3708 tuple: The new RGB values after saturation adjustment.
3709 tuple: The new xyY values after saturation adjustment.
3710 """
3711 whitepoint = RGB2XYZ(1, 1, 1, rgb_space=rgb_space)
3712 X, Y, Z = RGB2XYZ(R, G, B, rgb_space=rgb_space) # noqa: N806
3713 XYZ, xyY = XYZsaturation(X, Y, Z, saturation, whitepoint) # noqa: N806
3714 return XYZ2RGB(*XYZ, rgb_space=rgb_space), xyY
3715
3716
3717 def XYZsaturation( # noqa: N802
3718 X: float, # noqa: N803
3719 Y: float, # noqa: N803
3720 Z: float, # noqa: N803
3721 saturation: float,
3722 whitepoint: None | float | str | list | tuple = None,
3723 ) -> tuple[tuple[float, float, float], tuple[float, float, float]]:
3724 """(De)saturate a XYZ color in CIE xy and return the RGB and xyY values.
3725
3726 Args:
3727 X (float): The X value of the color.
3728 Y (float): The Y value of the color.
3729 Z (float): The Z value of the color.
3730 saturation (float): The saturation factor.
3731 0.0 = grayscale, 1.0 = original color, >1.0 = oversaturated.
3732 <0.0 = undersaturated.
3733 whitepoint (None | float | str | list | tuple): The white point
3734 to use for conversion. Defaults to D65 if not set.
3735
3736 Returns:
3737 tuple[tuple[float, float, float], tuple[float, float, float]]: The new
3738 XYZ values after saturation adjustment.
3739 """
3740 wx, wy, wY = XYZ2xyY(*get_whitepoint(whitepoint)) # noqa: N806
3741 x, y, Y = XYZ2xyY(X, Y, Z) # noqa: N806
3742 x, y, Y = xyYsaturation(x, y, Y, wx, wy, saturation) # noqa: N806
3743 return xyY2XYZ(x, y, Y), (x, y, Y)
3744
3745
3746 def xyYsaturation( # noqa: N802
3747 x: float,
3748 y: float,
3749 Y: float, # noqa: N803
3750 wx: float,
3751 wy: float,
3752 saturation: float,
3753 ) -> tuple[float, float, float]:
3754 """(De)saturate a color in CIE xy and return the RGB and xyY values.
3755
3756 Args:
3757 x (float): The x coordinate of the color.
3758 y (float): The y coordinate of the color.
3759 Y (float): The Y value of the color.
3760 wx (float): The x coordinate of the white point.
3761 wy (float): The y coordinate of the white point.
3762 saturation (float): The saturation factor.
3763 0.0 = grayscale, 1.0 = original color, >1.0 = oversaturated.
3764 <0.0 = undersaturated.
3765
3766 Returns:
3767 tuple[float, float, float]: The new x, y, and Y values after saturation
3768 adjustment.
3769 """
3770 return wx + (x - wx) * saturation, wy + (y - wy) * saturation, Y
3771
3772
3773 def convert_range(
3774 v: float, oldmin: float = 0, oldmax: float = 1, newmin: float = 0, newmax: float = 1
3775 ) -> float:
3776 """Convert a value from one range to another.
3777
3778 Args:
3779 v (float): The value to convert.
3780 oldmin (float): The minimum of the old range.
3781 oldmax (float): The maximum of the old range.
3782 newmin (float): The minimum of the new range.
3783 newmax (float): The maximum of the new range.
3784
3785 Returns:
3786 float: The converted value in the new range.
3787 """
3788 oldrange = float(oldmax - oldmin)
3789 newrange = newmax - newmin
3790 return (((v - oldmin) * newrange) / oldrange) + newmin
3791
3792
3793 def rgb_to_xyz_matrix(
3794 rx: float,
3795 ry: float,
3796 gx: float,
3797 gy: float,
3798 bx: float,
3799 by: float,
3800 whitepoint: None | float | str | list | tuple = None,
3801 scale: float = 1.0,
3802 ) -> Matrix3x3:
3803 """Create and return an RGB to XYZ matrix.
3804
3805 Args:
3806 rx (float): The x coordinate of the red primary.
3807 ry (float): The y coordinate of the red primary.
3808 gx (float): The x coordinate of the green primary.
3809 gy (float): The y coordinate of the green primary.
3810 bx (float): The x coordinate of the blue primary.
3811 by (float): The y coordinate of the blue primary.
3812 whitepoint (None | float | str | list | tuple): The white point
3813 to use for conversion. If None, the default white point will be
3814 used.
3815 scale (float): The scale factor for the XYZ values. Defaults to 1.0.
3816
3817 Returns:
3818 Matrix3x3: The RGB to XYZ matrix.
3819 """
3820 whitepoint = get_whitepoint(whitepoint, scale)
3821 Xr, Yr, Zr = xyY2XYZ(rx, ry, scale) # noqa: N806
3822 Xg, Yg, Zg = xyY2XYZ(gx, gy, scale) # noqa: N806
3823 Xb, Yb, Zb = xyY2XYZ(bx, by, scale) # noqa: N806
3824 Sr, Sg, Sb = ( # noqa: N806
3825 Matrix3x3(((Xr, Xg, Xb), (Yr, Yg, Yb), (Zr, Zg, Zb))).inverted() * whitepoint
3826 )
3827 return Matrix3x3(
3828 (
3829 (Sr * Xr, Sg * Xg, Sb * Xb),
3830 (Sr * Yr, Sg * Yg, Sb * Yb),
3831 (Sr * Zr, Sg * Zg, Sb * Zb),
3832 )
3833 )
3834
3835
3836 def find_primaries_wp_xy_rgb_space_name(
3837 xy: list | tuple, rgb_space_names: None | list | tuple = None, digits: int = 4
3838 ) -> None | str:
3839 """Find the RGB space name matching given primaries and whitepoint xy.
3840
3841 Args:
3842 xy (list | tuple): The xy coordinates of the primaries and whitepoint.
3843 rgb_space_names (None | list | tuple): A list of RGB space names to
3844 search in. If None, all RGB spaces will be searched.
3845 Defaults to None.
3846 digits (int): The number of digits to round to. Defaults to 4.
3847
3848 Returns:
3849 None | str: The name of the RGB space matching the given xy
3850 coordinates, or None if no match is found.
3851 """
3852 for _i, rgb_space_name in enumerate(rgb_space_names or iter(rgb_spaces.keys())):
3853 if not rgb_space_names and rgb_space_name in (
3854 "ECI RGB",
3855 "ECI RGB v2",
3856 "SMPTE 240M",
3857 "sRGB",
3858 ):
3859 # Skip in favor of base color space (i.e. NTSC 1953, SMPTE-C and
3860 # Rec. 709)
3861 continue
3862 if get_rgb_space_primaries_wp_xy(rgb_space_name, digits)[: len(xy)] == xy:
3863 return rgb_space_name
3864 return None
3865
3866
3867 @cache
3868 def get_rgb_space(
3869 rgb_space: None | str | list | tuple = None, scale: float = 1.0
3870 ) -> tuple[float,]:
3871 """Return gamma, whitepoint, primaries and RGB -> XYZ matrix.
3872
3873 Args:
3874 rgb_space (None | str | list | tuple): The RGB space
3875 to use for conversion. Defaults to sRGB if not set.
3876 If a string is given, it must be a valid RGB space name.
3877 If a list or tuple is given, it must be in the format
3878 (gamma, whitepoint, red, green, blue).
3879 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3880 coordinates, or a color temperature in degrees K (float or int).
3881 The gamma should be a float. The RGB primaries red, green,
3882 blue should be lists or tuples of xyY coordinates (only x and
3883 y will be used, so Y can be zero or None).
3884 scale (float): Scale factor for the XYZ values. Defaults to 1.0.
3885
3886 Returns:
3887 tuple: A tuple containing the gamma, whitepoint, red, green, blue
3888 primaries in xyY format, and the RGB to XYZ matrix.
3889 """
3890 if not rgb_space:
3891 rgb_space = "sRGB"
3892 if isinstance(rgb_space, str):
3893 rgb_space = rgb_spaces[rgb_space]
3894 gamma = rgb_space[0] or rgb_spaces["sRGB"][0]
3895 whitepoint = get_whitepoint(rgb_space[1] or rgb_spaces["sRGB"][1], scale)
3896 rx, ry, rY = rxyY = rgb_space[2] or rgb_spaces["sRGB"][2] # noqa: N806
3897 gx, gy, gY = gxyY = rgb_space[3] or rgb_spaces["sRGB"][3] # noqa: N806
3898 bx, by, bY = bxyY = rgb_space[4] or rgb_spaces["sRGB"][4] # noqa: N806
3899 matrix = rgb_to_xyz_matrix(rx, ry, gx, gy, bx, by, whitepoint, scale)
3900 return gamma, whitepoint, rxyY, gxyY, bxyY, matrix
3901
3902
3903 def get_rgb_space_primaries_wp_xy(
3904 rgb_space: None | str | list | tuple = None, digits: int = 4
3905 ) -> list:
3906 """Return primaries and whitepoint xy for a given RGB space, rounded to n digits.
3907
3908 Args:
3909 rgb_space (None | str | list | tuple): The RGB space
3910 to use for conversion. Defaults to sRGB if not set.
3911 If a string is given, it must be a valid RGB space name.
3912 If a list or tuple is given, it must be in the format
3913 (gamma, whitepoint, red, green, blue).
3914 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3915 coordinates, or a color temperature in degrees K (float or int).
3916 The gamma should be a float. The RGB primaries red, green,
3917 blue should be lists or tuples of xyY coordinates (only x and
3918 y will be used, so Y can be zero or None).
3919 digits (int): The number of digits to round to. Defaults to 4.
3920
3921 Returns:
3922 list: A list of xy coordinates for the RGB primaries and whitepoint,
3923 rounded to the specified number of digits.
3924 """
3925 rgb_space = get_rgb_space(rgb_space)
3926 xy = []
3927 for i in range(3):
3928 xy.extend(rgb_space[2:][i][:2])
3929 xy.extend(XYZ2xyY(*get_whitepoint(rgb_space[1]))[:2])
3930 if digits:
3931 xy = [round(v, digits) for v in xy]
3932 return xy
3933
3934
3935 @cache
3936 def get_standard_illuminant(
3937 illuminant_name: str = "D50",
3938 priority: tuple = (
3939 "ISO 11664-2:2007",
3940 "ICC",
3941 "ASTM E308-01",
3942 "Wyszecki & Stiles",
3943 None,
3944 ),
3945 scale: float = 1.0,
3946 ) -> tuple[float, float, float]:
3947 """Return a standard illuminant as XYZ coordinates.
3948
3949 Args:
3950 illuminant_name (str): The name of the standard illuminant to return.
3951 Defaults to "D50".
3952 priority (tuple): A tuple of standard names to search for the
3953 illuminant. The first one found will be returned.
3954 Defaults to ("ISO 11664-2:2007", "ICC", "ASTM E308-01",
3955 "Wyszecki & Stiles", None).
3956 scale (float): Scale factor for the XYZ values. Defaults to 1.0.
3957
3958 Raises:
3959 ValueError: If the illuminant name is not recognized or if no
3960 illuminant is found in the given priority list.
3961
3962 Returns:
3963 tuple[float, float, float]: A tuple of XYZ coordinates scaled by the
3964 given scale factor.
3965 """
3966 illuminant = None
3967 for standard_name in priority:
3968 if standard_name not in standard_illuminants:
3969 raise ValueError(f'Unrecognized standard "{standard_name}"')
3970 illuminant = standard_illuminants.get(standard_name).get(
3971 illuminant_name.upper(), None
3972 )
3973 if illuminant:
3974 return illuminant["X"] * scale, 1.0 * scale, illuminant["Z"] * scale
3975 raise ValueError(f'Unrecognized illuminant "{illuminant_name}"')
3976
3977
3978 @overload
3979 def get_whitepoint(
3980 whitepoint: list,
3981 scale: float = 1.0,
3982 planckian: bool = False,
3983 ) -> list[float]: ...
3984
3985
3986 @overload
3987 def get_whitepoint(
3988 whitepoint: None | float | str | tuple,
3989 scale: float = 1.0,
3990 planckian: bool = False,
3991 ) -> tuple[float, float, float]: ...
3992
3993
3994 @cache
3995 def get_whitepoint(
3996 whitepoint: None | float | str | list | tuple = None,
3997 scale: float = 1.0,
3998 planckian: bool = False,
3999 ) -> tuple[float, float, float]:
4000 """Return a whitepoint as XYZ coordinates.
4001
4002 Args:
4003 whitepoint: A string (e.g. "D50"), a tuple of XYZ coordinates, or a
4004 color temperature in degrees K (float or int). Defaults to D50 if
4005 not set.
4006 scale: Scale factor for the XYZ values. Defaults to 1.0.
4007 planckian: If True, interpret the whitepoint as a Planckian color
4008 temperature. Defaults to False.
4009
4010 Returns:
4011 tuple: A tuple of XYZ coordinates scaled by the given scale factor.
4012 """
4013 if isinstance(whitepoint, (list, tuple)):
4014 return whitepoint
4015 if not whitepoint:
4016 whitepoint = "D50"
4017 if isinstance(whitepoint, str):
4018 whitepoint = get_standard_illuminant(whitepoint)
4019 elif isinstance(whitepoint, (float, int)):
4020 cct = whitepoint
4021 if planckian:
4022 whitepoint = planckianCT2XYZ(cct)
4023 if not whitepoint:
4024 raise ValueError(
4025 f"Planckian color temperature {cct} out of range (1667, 25000)"
4026 )
4027 else:
4028 whitepoint = CIEDCCT2XYZ(cct)
4029 if not whitepoint:
4030 raise ValueError(
4031 f"Daylight color temperature {cct} out of range (2500, 25000)"
4032 )
4033 if scale > 1.0 and whitepoint[1] == 100:
4034 scale = 1.0
4035 return tuple(v * scale for v in whitepoint)
4036
4037
4038 def make_monotonically_increasing(
4039 iterable: tuple | list | dict,
4040 passes: int = 0,
4041 window: None | int = None,
4042 ) -> list | dict:
4043 """Make values in iterable strictly monotonically increasing by linear interpolation.
4044
4045 If iterable is a dict, keep the keys of the original.
4046
4047 If passes is non-zero, apply moving average smoothing to the values
4048 before making them monotonically increasing.
4049
4050 Args:
4051 iterable (tuple | list | dict): The input iterable or sequence.
4052 passes (int): The number of smoothing passes to apply.
4053 Defaults to 0 (no smoothing).
4054 window (int): The window size for smoothing. Defaults to None.
4055 If None, the window size is set to 3.
4056 If passes is 0, this argument is ignored.
4057
4058 Returns:
4059 list: A list of tuples containing the original keys and the
4060 monotonically increasing values.
4061 """ # noqa: E501
4062 if isinstance(iterable, dict):
4063 keys = list(iterable.keys())
4064 values = list(iterable.values())
4065 else:
4066 values = list(iterable) if hasattr(iterable, "next") else iterable
4067 keys = range(len(values))
4068 if passes:
4069 values = smooth_avg(values, passes, window)
4070 sequence = list(zip(keys, values))
4071 numvalues = len(sequence)
4072 s_new = []
4073 y_min = sequence[0][1]
4074 while sequence:
4075 x, y = sequence.pop()
4076 if (not s_new or y < s_new[0][1]) and (y > y_min or not sequence):
4077 s_new.insert(0, (x, y))
4078 sequence = s_new
4079 # Interpolate to original size
4080 x_new = [item[0] for item in sequence]
4081 y = [item[1] for item in sequence]
4082 values = []
4083 for i in range(numvalues):
4084 values.append(interp(i, x_new, y))
4085 if isinstance(iterable, dict):
4086 # Add in original keys
4087 return iterable.__class__(list(zip(keys, values)))
4088 return values
4089
4090
4091 def matmul(
4092 XYZ: tuple[float, float, float], # noqa: N803
4093 m1: Matrix3x3,
4094 m2: Matrix3x3,
4095 ) -> tuple[float, float, float]:
4096 """Matrix multiplication of two matrices.
4097
4098 Args:
4099 XYZ (tuple[float, float, float]): A tuple of XYZ coordinates (X, Y, Z).
4100 m1 (Matrix3x3): The first matrix.
4101 m2 (Matrix3x3): The second matrix.
4102
4103 Returns:
4104 tuple[float, float, float]: A tuple of the resulting coordinates
4105 (X', Y', Z').
4106 """
4107 return m1 * (m2 * XYZ)
4108
4109
4110 def planckianCT2XYZ(T: float, scale: float = 1.0) -> None | tuple[float, float, float]: # noqa: N802, N803
4111 """Convert from planckian temperature to XYZ.
4112
4113 T = temperature in Kelvin.
4114
4115 Args:
4116 T (float): Temperature in Kelvin.
4117 scale (float): Scale factor for the XYZ values.
4118 Defaults to 1.0.
4119
4120 Returns:
4121 None | tuple[float, float, float]: A tuple of XYZ coordinates (X, Y, Z)
4122 if xyY is not None, None otherwise.
4123 """
4124 xyY = planckianCT2xyY(T, scale) # noqa: N806
4125 return xyY2XYZ(*xyY) if xyY else None
4126
4127
4128 def planckianCT2xyY(T: float, scale: float = 1.0) -> tuple[float, float, float]: # noqa: N802, N803
4129 """Convert from planckian temperature to xyY.
4130
4131 T = temperature in Kelvin.
4132
4133 Formula from http://en.wikipedia.org/wiki/Planckian_locus
4134
4135 Args:
4136 T (float): Temperature in Kelvin.
4137 scale (float, optional): Scale factor for the xyY values.
4138 Defaults to 1.0.
4139
4140 Returns:
4141 tuple[float, float, float]: A tuple of xyY coordinates (x, y, Y).
4142 """
4143 if 1667 <= T <= 4000:
4144 x = (
4145 -0.2661239 * (math.pow(10, 9) / math.pow(T, 3))
4146 - 0.2343580 * (math.pow(10, 6) / math.pow(T, 2))
4147 + 0.8776956 * (math.pow(10, 3) / T)
4148 + 0.179910
4149 )
4150 elif 4000 <= T <= 25000:
4151 x = (
4152 -3.0258469 * (math.pow(10, 9) / math.pow(T, 3))
4153 + 2.1070379 * (math.pow(10, 6) / math.pow(T, 2))
4154 + 0.2226347 * (math.pow(10, 3) / T)
4155 + 0.24039
4156 )
4157 else:
4158 return None
4159 if 1667 <= T <= 2222:
4160 y = (
4161 -1.1063814 * math.pow(x, 3)
4162 - 1.34811020 * math.pow(x, 2)
4163 + 2.18555832 * x
4164 - 0.20219683
4165 )
4166 elif 2222 <= T <= 4000:
4167 y = (
4168 -0.9549476 * math.pow(x, 3)
4169 - 1.37418593 * math.pow(x, 2)
4170 + 2.09137015 * x
4171 - 0.16748867
4172 )
4173 elif 4000 <= T <= 25000:
4174 y = (
4175 3.0817580 * math.pow(x, 3)
4176 - 5.87338670 * math.pow(x, 2)
4177 + 3.75112997 * x
4178 - 0.37001483
4179 )
4180 return x, y, scale
4181
4182
4183 def xyY2CCT(x: float, y: float, Y: float = 1.0) -> None | float: # noqa: N802, N803
4184 """Convert from xyY to correlated color temperature.
4185
4186 Args:
4187 x (float): x coordinate in xyY color space.
4188 y (float): y coordinate in xyY color space.
4189 Y (float, optional): Y coordinate in xyY color space.
4190
4191 Returns:
4192 None | float: Correlated color temperature in Kelvin.
4193 """
4194 return XYZ2CCT(*xyY2XYZ(x, y, Y))
4195
4196
4197 def xyY2Lab( # noqa: N802
4198 x: float,
4199 y: float,
4200 Y: float = 1.0, # noqa: N803
4201 whitepoint: None | float | str | tuple | list = None,
4202 ) -> tuple[float, float, float]:
4203 """Convert from xyY to Lab color space.
4204
4205 Args:
4206 x (float): x coordinate in xyY color space.
4207 y (float): y coordinate in xyY color space.
4208 Y (float, optional): Y coordinate in xyY color space.
4209 whitepoint ( None | float | str | tuple | list): Whitepoint to
4210 use for conversion. Defaults to D50 if not set.
4211
4212 Returns:
4213 tuple[float, float, float]: A tuple of Lab coordinates (L, a, b).
4214 """
4215 return XYZ2Lab(*xyY2XYZ(x, y, Y), whitepoint)
4216
4217
4218 def xyY2Lu_v_( # noqa: N802
4219 x: float,
4220 y: float,
4221 Y: float = 1.0, # noqa: N803
4222 whitepoint: None | float | str | tuple | list = None,
4223 ) -> tuple[float, float, float]:
4224 """Convert from xyY to Lu'v' color space.
4225
4226 Args:
4227 x (float): x coordinate in xyY color space.
4228 y (float): y coordinate in xyY color space.
4229 Y (float, optional): Y coordinate in xyY color space.
4230 whitepoint ( None | float | str | tuple | list): Whitepoint to
4231 use for conversion. Defaults to D50 if not set.
4232
4233 Returns:
4234 tuple[float, float, float]: A tuple of Lu'v' coordinates (L, u', v').
4235 """
4236 return XYZ2Lu_v_(*xyY2XYZ(x, y, Y), whitepoint)
4237
4238
4239 def xyY2RGB( # noqa: N802
4240 x: float, # noqa: N803
4241 y: float, # noqa: N803
4242 Y: float, # noqa: N803
4243 rgb_space: None | str | list | tuple = None,
4244 scale: float = 1.0,
4245 round_: bool = False,
4246 clamp: bool = True,
4247 ) -> tuple[float, float, float]:
4248 """Convert from xyY to RGB.
4249
4250 Args:
4251 x (float): x coordinate in xyY color space.
4252 y (float): y coordinate in xyY color space.
4253 Y (float): Y coordinate in xyY color space.
4254 rgb_space (str | tuple): RGB color space to use for conversion.
4255 scale (float): Scale factor for the RGB values.
4256 round_ (bool): If True, round the RGB values to integers.
4257 clamp (bool): If True, clamp the RGB values to [0, 1].
4258
4259 Returns:
4260 tuple: A tuple of RGB coordinates (R, G, B).
4261 """
4262 return XYZ2RGB(*xyY2XYZ(x, y, Y), rgb_space, scale, round_, clamp)
4263
4264
4265 def xyY2XYZ(x: float, y: float, Y: float = 1.0) -> tuple[float, float, float]: # noqa: N802, N803
4266 """Convert from xyY to XYZ.
4267
4268 Based on formula from http://brucelindbloom.com/Eqn_xyY_to_XYZ.html
4269
4270 Implementation Notes:
4271 1. Watch out for the case where y = 0. In that case, X = Y = Z = 0 is
4272 returned.
4273 2. The output XYZ values are in the nominal range [0.0, Y[xyY]].
4274
4275 Args:
4276 x (float): x coordinate in xyY color space.
4277 y (float): y coordinate in xyY color space.
4278 Y (float, optional): Y coordinate in xyY color space. The default is 1.0.
4279
4280 Returns:
4281 tuple[float, float, float]: A tuple of XYZ coordinates (X, Y, Z).
4282 """
4283 if y == 0:
4284 return 0, 0, 0
4285 return (float(x * Y) / y), Y, (float((1 - x - y) * Y) / y)
4286
4287
4288 def LERP(a: float, b: float, c: float) -> float: # noqa: N802
4289 """Linear interpolation macro.
4290
4291 Is 'a' when c == 0.0 and 'b' when c == 1.0
4292
4293 Args:
4294 a (float): Start value.
4295 b (float): End value.
4296 c (float): Interpolation factor (0.0 to 1.0).
4297
4298 Returns:
4299 float: Interpolated value.
4300 """
4301 return (b - a) * c + a
4302
4303
4304 def XYZ2CCT(X: float, Y: float, Z: float) -> None | float: # noqa: N802, N803
4305 """Convert from XYZ to correlated color temperature.
4306
4307 Derived from ANSI C implementation by Bruce Lindbloom
4308 http://brucelindbloom.com/Eqn_XYZ_to_T.html
4309
4310 Return: correlated color temperature if successful, else None.
4311
4312 Description:
4313 This is an implementation of Robertson's method of computing the
4314 correlated color temperature of an XYZ color. It can compute correlated
4315 color temperatures in the range [1666.7K, infinity].
4316
4317 Reference:
4318 "Color Science: Concepts and Methods, Quantitative Data and Formulae",
4319 Second Edition, Gunter Wyszecki and W. S. Stiles, John Wiley & Sons,
4320 1982, pp. 227, 228.
4321
4322
4323 Args:
4324 X (float): X coordinate in XYZ color space.
4325 Y (float): Y coordinate in XYZ color space.
4326 Z (float): Z coordinate in XYZ color space.
4327
4328 Returns:
4329 None | float: Correlated color temperature in Kelvin if successful,
4330 else None.
4331 """
4332 rt = [ # reciprocal temperature (K)
4333 DBL_MIN,
4334 10.0e-6,
4335 20.0e-6,
4336 30.0e-6,
4337 40.0e-6,
4338 50.0e-6,
4339 60.0e-6,
4340 70.0e-6,
4341 80.0e-6,
4342 90.0e-6,
4343 100.0e-6,
4344 125.0e-6,
4345 150.0e-6,
4346 175.0e-6,
4347 200.0e-6,
4348 225.0e-6,
4349 250.0e-6,
4350 275.0e-6,
4351 300.0e-6,
4352 325.0e-6,
4353 350.0e-6,
4354 375.0e-6,
4355 400.0e-6,
4356 425.0e-6,
4357 450.0e-6,
4358 475.0e-6,
4359 500.0e-6,
4360 525.0e-6,
4361 550.0e-6,
4362 575.0e-6,
4363 600.0e-6,
4364 ]
4365 uvt = [
4366 [0.18006, 0.26352, -0.24341],
4367 [0.18066, 0.26589, -0.25479],
4368 [0.18133, 0.26846, -0.26876],
4369 [0.18208, 0.27119, -0.28539],
4370 [0.18293, 0.27407, -0.30470],
4371 [0.18388, 0.27709, -0.32675],
4372 [0.18494, 0.28021, -0.35156],
4373 [0.18611, 0.28342, -0.37915],
4374 [0.18740, 0.28668, -0.40955],
4375 [0.18880, 0.28997, -0.44278],
4376 [0.19032, 0.29326, -0.47888],
4377 [0.19462, 0.30141, -0.58204],
4378 [0.19962, 0.30921, -0.70471],
4379 [0.20525, 0.31647, -0.84901],
4380 [0.21142, 0.32312, -1.0182],
4381 [0.21807, 0.32909, -1.2168],
4382 [0.22511, 0.33439, -1.4512],
4383 [0.23247, 0.33904, -1.7298],
4384 [0.24010, 0.34308, -2.0637],
4385 [0.24792, 0.34655, -2.4681], # Note: 0.24792 is a corrected value
4386 # for the error found in W&S as 0.24702
4387 [0.25591, 0.34951, -2.9641],
4388 [0.26400, 0.35200, -3.5814],
4389 [0.27218, 0.35407, -4.3633],
4390 [0.28039, 0.35577, -5.3762],
4391 [0.28863, 0.35714, -6.7262],
4392 [0.29685, 0.35823, -8.5955],
4393 [0.30505, 0.35907, -11.324],
4394 [0.31320, 0.35968, -15.628],
4395 [0.32129, 0.36011, -23.325],
4396 [0.32931, 0.36038, -40.770],
4397 [0.33724, 0.36051, -116.45],
4398 ]
4399 if (X < 1.0e-20 and Y < 1.0e-20 and Z < 1.0e-20) or X + 15.0 * Y + 3.0 * Z == 0:
4400 return None # protect against possible divide-by-zero failure
4401 us = (4.0 * X) / (X + 15.0 * Y + 3.0 * Z)
4402 vs = (6.0 * Y) / (X + 15.0 * Y + 3.0 * Z)
4403 dm = 0.0
4404 i = 0
4405 while i < 31:
4406 di = (vs - uvt[i][1]) - uvt[i][2] * (us - uvt[i][0])
4407 if i > 0 and ((di < 0.0 <= dm) or (di >= 0.0 > dm)):
4408 break # found lines bounding (us, vs) : i-1 and i
4409 dm = di
4410 i += 1
4411 if i == 31:
4412 # bad XYZ input, color temp would be less than minimum of 1666.7
4413 # degrees, or too far towards blue
4414 return None
4415 di = di / math.sqrt(1.0 + uvt[i][2] * uvt[i][2])
4416 dm = dm / math.sqrt(1.0 + uvt[i - 1][2] * uvt[i - 1][2])
4417 p = dm / (dm - di) # p = interpolation parameter, 0.0 : i-1, 1.0 : i
4418 p = 1.0 / (LERP(rt[i - 1], rt[i], p))
4419 return p # noqa: RET504
4420
4421
4422 def XYZ2DIN99( # noqa: N802
4423 X: float, # noqa: N803
4424 Y: float, # noqa: N803
4425 Z: float, # noqa: N803
4426 whitepoint: None | float | str | tuple | list = None,
4427 ) -> tuple[float, float, float]:
4428 """Convert from XYZ to DIN99.
4429
4430 Args:
4431 X (float): X value.
4432 Y (float): Y value.
4433 Z (float): Z value.
4434 whitepoint (None | float | str | tuple | list): Whitepoint.
4435 Defaults to D50.
4436
4437 Returns:
4438 tuple[float, float, float]: DIN99 values.
4439 """
4440 return Lab2DIN99(*XYZ2Lab(*(max(v, 0) for v in (X, Y, Z)), whitepoint))
4441
4442
4443 def XYZ2DIN99b( # noqa: N802
4444 X: float, # noqa: N803
4445 Y: float, # noqa: N803
4446 Z: float, # noqa: N803
4447 whitepoint: None | float | str | tuple | list = None,
4448 ) -> tuple[float, float, float]:
4449 """Convert from XYZ to DIN99b.
4450
4451 Args:
4452 X (float): X value.
4453 Y (float): Y value.
4454 Z (float): Z value.
4455 whitepoint (None | float | str | tuple | list): Whitepoint.
4456 Defaults to D50.
4457
4458 Returns:
4459 tuple[float, float, float]: DIN99b values.
4460 """
4461 return Lab2DIN99b(*XYZ2Lab(X, Y, Z, whitepoint))
4462
4463
4464 def XYZ2DIN99o( # noqa: N802
4465 X: float, # noqa: N803
4466 Y: float, # noqa: N803
4467 Z: float, # noqa: N803
4468 whitepoint: None | float | str | tuple | list = None,
4469 ) -> tuple[float, float, float]:
4470 """Convert from XYZ to DIN99o.
4471
4472 Args:
4473 X (float): X value.
4474 Y (float): Y value.
4475 Z (float): Z value.
4476 whitepoint (None | float | str | tuple | list): Whitepoint.
4477 Defaults to D50.
4478
4479 Returns:
4480 tuple[float]: DIN99o values.
4481 """
4482 return Lab2DIN99o(*XYZ2Lab(X, Y, Z, whitepoint))
4483
4484
4485 def XYZ2DIN99bLCH( # noqa: N802
4486 X: float, # noqa: N803
4487 Y: float, # noqa: N803
4488 Z: float, # noqa: N803
4489 whitepoint: None | float | str | tuple | list = None,
4490 ) -> tuple[float, float, float]:
4491 """Convert from XYZ to DIN99b LCH.
4492
4493 Args:
4494 X (float): X value.
4495 Y (float): Y value.
4496 Z (float): Z value.
4497 whitepoint (None | float | str | tuple | list): Whitepoint.
4498 Defaults to D50.
4499
4500 Returns:
4501 tuple[float, float, float]: DIN99b LCH values.
4502 """
4503 return Lab2DIN99bLCH(*XYZ2Lab(X, Y, Z, whitepoint))
4504
4505
4506 def XYZ2DIN99oLCH( # noqa: N802
4507 X: float, # noqa: N803
4508 Y: float, # noqa: N803
4509 Z: float, # noqa: N803
4510 whitepoint: None | float | str | tuple | list = None,
4511 ) -> tuple[float, float, float]:
4512 """Convert from XYZ to DIN99o LCH.
4513
4514 Args:
4515 X (float): X value.
4516 Y (float): Y value.
4517 Z (float): Z value.
4518 whitepoint (None | float | str | tuple | list): Whitepoint.
4519 Defaults to D50.
4520
4521 Returns:
4522 tuple[float, float, float]: DIN99o LCH values.
4523 """
4524 return Lab2DIN99oLCH(*XYZ2Lab(X, Y, Z, whitepoint))
4525
4526
4527 def XYZ2DIN99c( # noqa: N802
4528 X: float, # noqa: N803
4529 Y: float, # noqa: N803
4530 Z: float, # noqa: N803
4531 whitepoint: None | float | str | tuple | list = None,
4532 ) -> tuple[float, float, float]:
4533 """Convert from XYZ to DIN99c.
4534
4535 Args:
4536 X (float): X value.
4537 Y (float): Y value.
4538 Z (float): Z value.
4539 whitepoint (None | float | str | tuple | list): Whitepoint.
4540 Defaults to D50.
4541
4542 Returns:
4543 tuple[float, float, float]: DIN99c values.
4544 """
4545 return XYZ2DIN99cd(X, Y, Z, 0.1, 317.651, 0.0037, 0, 0.94, 23, 0.066, whitepoint)
4546
4547
4548 def XYZ2DIN99cd( # noqa: N802
4549 X: float, # noqa: N803
4550 Y: float, # noqa: N803
4551 Z: float, # noqa: N803
4552 x: float,
4553 l1: float,
4554 l2: float,
4555 deg: float,
4556 f1: float,
4557 c1: float,
4558 c2: float,
4559 whitepoint: None | float | str | tuple | list = None,
4560 ) -> tuple[float, float, float]:
4561 """Convert from XYZ to DIN99cd.
4562
4563 Args:
4564 X (float): X value.
4565 Y (float): Y value.
4566 Z (float): Z value.
4567 x (float): Chromatic adaptation factor.
4568 l1 (float): L1 parameter.
4569 l2 (float): L2 parameter.
4570 deg (float): Deg parameter.
4571 f1 (float): F1 parameter.
4572 c1 (float): C1 parameter.
4573 c2 (float): C2 parameter.
4574 whitepoint (None | float | str | tuple | list): Whitepoint.
4575 Defaults to D50.
4576
4577 Returns:
4578 tuple[float]: DIN99cd values.
4579 """
4580 l99, c99, h99 = XYZ2DIN99cdLCH(X, Y, Z, x, l1, l2, deg, f1, c1, c2, whitepoint)
4581 a99, b99 = DIN99familyCH2DIN99ab(c99, h99)
4582 return l99, a99, b99
4583
4584
4585 def XYZ2DIN99cdLCH( # noqa: N802
4586 X: float, # noqa: N803
4587 Y: float, # noqa: N803
4588 Z: float, # noqa: N803
4589 x: float,
4590 l1: float,
4591 l2: float,
4592 deg: float,
4593 f1: float,
4594 c1: float,
4595 c2: float,
4596 whitepoint: None | float | str | tuple | list = None,
4597 ) -> tuple[float, float, float]:
4598 """Convert from XYZ to DIN99cd LCH.
4599
4600 Args:
4601 X (float): X value.
4602 Y (float): Y value.
4603 Z (float): Z value.
4604 x (float): Chromatic adaptation factor.
4605 l1 (float): L1 parameter.
4606 l2 (float): L2 parameter.
4607 deg (float): Deg parameter.
4608 f1 (float): F1 parameter.
4609 c1 (float): C1 parameter.
4610 c2 (float): C2 parameter.
4611 whitepoint (None | float | str | tuple | list): Whitepoint.
4612 Defaults to D50.
4613
4614 Returns:
4615 tuple[float, float, float]: DIN99cd LCH values.
4616 """
4617 X, Y, Z = XYZ2DIN99cdXYZ(X, Y, Z, x) # noqa: N806
4618 whitepoint99d = XYZ2DIN99cdXYZ(*get_whitepoint(whitepoint, 100), x=x)
4619 l, a, b = XYZ2Lab(X, Y, Z, whitepoint99d)
4620 return Lab2DIN99familyLCH(l, a, b, l1, l2, deg, f1, c1, c2)
4621
4622
4623 def XYZ2DIN99cdXYZ( # noqa: N802
4624 X: float, # noqa: N803
4625 Y: float, # noqa: N803
4626 Z: float, # noqa: N803
4627 x: float,
4628 ) -> tuple[float, float, float]:
4629 """Convert from XYZ to DIN99cd.
4630
4631 Args:
4632 X (float): X value.
4633 Y (float): Y value.
4634 Z (float): Z value.
4635 x (float): Chromatic adaptation factor.
4636
4637 Returns:
4638 tuple[float]: DIN99cd values.
4639 """
4640 X = (1 + x) * X - x * Z # noqa: N806
4641 return X, Y, Z
4642
4643
4644 def XYZ2DIN99d( # noqa: N802
4645 X: float, # noqa: N803
4646 Y: float, # noqa: N803
4647 Z: float, # noqa: N803
4648 whitepoint: None | float | str | tuple | list = None,
4649 ) -> tuple[float, float, float]:
4650 """Convert from XYZ to DIN99d.
4651
4652 Args:
4653 X (float): X value.
4654 Y (float): Y value.
4655 Z (float): Z value.
4656 whitepoint (None | float | str | tuple | list): Whitepoint.
4657 Defaults to D50.
4658
4659 Returns:
4660 tuple[float, float, float]: DIN99d values.
4661 """
4662 return XYZ2DIN99cd(X, Y, Z, 0.12, 325.221, 0.0036, 50, 1.14, 22.5, 0.06, whitepoint)
4663
4664
4665 def XYZ2DIN99dLCH( # noqa: N802
4666 X: float, # noqa: N803
4667 Y: float, # noqa: N803
4668 Z: float, # noqa: N803
4669 whitepoint: None | float | str | tuple | list = None,
4670 ) -> tuple[float]:
4671 """Convert from XYZ to DIN99d LCH.
4672
4673 Args:
4674 X (float): X value.
4675 Y (float): Y value.
4676 Z (float): Z value.
4677 whitepoint (None | float | str | tuple | list): Whitepoint.
4678 Defaults to D50.
4679
4680 Returns:
4681 tuple[float]: DIN99d LCH values.
4682 """
4683 return XYZ2DIN99cdLCH(
4684 X, Y, Z, 0.12, 325.221, 0.0036, 50, 1.14, 22.5, 0.06, whitepoint
4685 )
4686
4687
4688 def XYZ2IPT(X: float, Y: float, Z: float) -> Matrix3x3: # noqa: N802, N803
4689 """Convert from XYZ to IPT.
4690
4691 The input Y value needs to be in the nominal range [0.0, 100.0] and
4692 other input values scaled accordingly.
4693 The output I value is in the nominal range [0.0, 100.0].
4694
4695 Args:
4696 X (float): X value.
4697 Y (float): Y value.
4698 Z (float): Z value.
4699
4700 Returns:
4701 Matrix3x3: IPT values.
4702 """
4703 xyz2lms_matrix = get_cat_matrix("IPT")
4704 lms = xyz2lms_matrix * (X, Y, Z)
4705 for i, component in enumerate(lms):
4706 if component >= 0:
4707 lms[i] **= 0.43
4708 else:
4709 lms[i] = -((-component) ** 0.43)
4710 return LMS2IPT_matrix * lms
4711
4712
4713 def IPT2XYZ(I: float, P: float, T: float) -> Matrix3x3: # noqa: N802, N803
4714 """Convert from IPT to XYZ.
4715
4716 Args:
4717 I (float): I value.
4718 P (float): P value.
4719 T (float): T value.
4720
4721 Returns:
4722 Matrix3x3: XYZ values.
4723 """
4724 xyz2lms_matrix = get_cat_matrix("IPT")
4725 lms2xyz_matrix = xyz2lms_matrix.inverted()
4726 lms = IPT2LMS_matrix * (I, P, T)
4727 for i, component in enumerate(lms):
4728 if component >= 0:
4729 lms[i] **= 1 / 0.43
4730 else:
4731 lms[i] = -((-component) ** (1 / 0.43))
4732 return lms2xyz_matrix * lms
4733
4734
4735 def XYZ2Lab( # noqa: N802
4736 X: float, # noqa: N803
4737 Y: float, # noqa: N803
4738 Z: float, # noqa: N803
4739 whitepoint: None | float | str | tuple | list = None,
4740 scale: float = 100,
4741 ) -> tuple[float, float, float]:
4742 """Convert from XYZ to Lab.
4743
4744 The input Y value needs to be in the nominal range [0.0, scale] and
4745 other input values scaled accordingly.
4746 The output L value is in the nominal range [0.0, 100.0].
4747
4748 whitepoint can be string (e.g. "D50"), a tuple of XYZ coordinates or
4749 color temperature as float or int. Defaults to D50 if not set.
4750
4751 Based on formula from http://brucelindbloom.com/Eqn_XYZ_to_Lab.html
4752
4753 Args:
4754 X (float): X value.
4755 Y (float): Y value.
4756 Z (float): Z value.
4757 whitepoint (None | float | str | tuple | list): Whitepoint.
4758 Defaults to D50.
4759 scale (float): Scale factor. Defaults to 100.
4760
4761 Returns:
4762 tuple[float, float, float]: L, a, b values.
4763 """
4764 Xr, Yr, Zr = get_whitepoint(whitepoint, scale) # noqa: N806
4765
4766 xr = X / Xr
4767 yr = Y / Yr
4768 zr = Z / Zr
4769 fx = cbrt(xr) if xr > LSTAR_E else (LSTAR_K * xr + 16) / 116.0
4770 fy = cbrt(yr) if yr > LSTAR_E else (LSTAR_K * yr + 16) / 116.0
4771 fz = cbrt(zr) if zr > LSTAR_E else (LSTAR_K * zr + 16) / 116.0
4772 l = 116 * fy - 16
4773 a = 500 * (fx - fy)
4774 b = 200 * (fy - fz)
4775
4776 return l, a, b
4777
4778
4779 def XYZ2Lpt( # noqa: N802
4780 X: float, # noqa: N803
4781 Y: float, # noqa: N803
4782 Z: float, # noqa: N803
4783 whitepoint: None | float | str | tuple | list = None,
4784 ) -> Matrix3x3:
4785 """Convert from XYZ to Lpt.
4786
4787 This is a modern update to L*a*b*, based on IPT space.
4788
4789 Differences to L*a*b* and IPT:
4790 - Using inverse CIE 2012 2degree LMS to XYZ matrix instead of
4791 Hunt-Pointer-Estevez Von Kries chromatic adapation in LMS space.
4792 - Using L* compression rather than IPT pure 0.43 power.
4793 - Tweaked LMS' to IPT matrix to account for change in XYZ to LMS matrix.
4794 - Output scaled to L*a*b* type ranges, to maintain 1 JND scale.
4795 - L* value is not a non-linear Y value.
4796
4797 The input Y value needs to be in the nominal range [0.0, 100.0] and
4798 other input values scaled accordingly.
4799 The output L value is in the nominal range [0.0, 100.0].
4800
4801 whitepoint can be string (e.g. "D50"), a tuple of XYZ coordinates or
4802 color temperature as float or int. Defaults to D50 if not set.
4803
4804 Args:
4805 X (float): X value.
4806 Y (float): Y value.
4807 Z (float): Z value.
4808 whitepoint (None | float | str | tuple | list): Whitepoint.
4809 Defaults to D50.
4810
4811 Returns:
4812 Matrix3x3: Lpt values.
4813 """
4814 # Adapted from Argyll/icc/icc.c
4815 from DisplayCAL import argyll
4816
4817 if argyll.get_argyll_version("dispwin") < [3, 4, 0]:
4818 observer_name = "CIE2012_2"
4819 else:
4820 observer_name = "CIE2015_2"
4821 xyz2lms = get_cat_matrix(observer_name)
4822
4823 wlms = xyz2lms * get_whitepoint(whitepoint, 100)
4824
4825 lms = xyz2lms * (X, Y, Z)
4826
4827 for j in range(3):
4828 lms[j] /= wlms[j]
4829
4830 if lms[j] > 0.008856451586:
4831 lms[j] = pow(lms[j], 1.0 / 3.0)
4832 else:
4833 lms[j] = 7.787036979 * lms[j] + 16.0 / 116.0
4834 lms[j] = 116.0 * lms[j] - 16.0
4835
4836 return LMS2Lpt_matrix * lms
4837
4838
4839 def Lpt2XYZ( # noqa: N802
4840 L: float, # noqa: N803
4841 p: float,
4842 t: float,
4843 whitepoint: None | float | str | tuple | list = None,
4844 scale: float = 1.0,
4845 ) -> Matrix3x3:
4846 """Convert from Lpt to XYZ.
4847
4848 This is a modern update to L*a*b*, based on IPT space.
4849
4850 Differences to L*a*b* and IPT:
4851 - Using inverse CIE 2012 2degree LMS to XYZ matrix instead of
4852 Hunt-Pointer-Estevez Von Kries chromatic adapation in LMS space.
4853 - Using L* compression rather than IPT pure 0.43 power.
4854 - Tweaked LMS' to IPT matrix to account for change in XYZ to LMS matrix.
4855 - Output scaled to L*a*b* type ranges, to maintain 1 JND scale.
4856 - L* value is not a non-linear Y value.
4857
4858 The input L* value needs to be in the nominal range [0.0, 100.0] and
4859 other input values scaled accordingly.
4860 The output XYZ values are in the nominal range [0.0, 1.0].
4861
4862 whitepoint can be string (e.g. "D50"), a tuple of XYZ coordinates or
4863 color temperature as float or int. Defaults to D50 if not set.
4864
4865 Args:
4866 L (float): L* value.
4867 p (float): p value.
4868 t (float): t value.
4869 whitepoint (None | float | str | tuple | list): Whitepoint.
4870 Defaults to D50.
4871 scale (float): Scale factor for the XYZ values. Defaults to 1.0.
4872
4873 Returns:
4874 Matrix3x3: XYZ values.
4875 """
4876 # Adapted from Argyll/icc/icc.c
4877
4878 from DisplayCAL import argyll
4879
4880 if argyll.get_argyll_version("dispwin") < [3, 4, 0]:
4881 observer_name = "CIE2012_2"
4882 else:
4883 observer_name = "CIE2015_2"
4884
4885 xyz2lms = get_cat_matrix(observer_name)
4886 lms2xyz = xyz2lms.inverted()
4887
4888 wlms = xyz2lms * get_whitepoint(whitepoint, scale)
4889
4890 lms = Lpt2LMS_matrix * (L, p, t)
4891
4892 for j in range(3):
4893 lms[j] = (lms[j] + 16.0) / 116.0
4894
4895 if lms[j] > 24.0 / 116.0:
4896 lms[j] = pow(lms[j], 3.0)
4897 else:
4898 lms[j] = (lms[j] - 16.0 / 116.0) / 7.787036979
4899
4900 lms[j] *= wlms[j]
4901
4902 return lms2xyz * lms
4903
4904
4905 def XYZ2Lu_v_( # noqa: N802
4906 X: float, # noqa: N803
4907 Y: float, # noqa: N803
4908 Z: float, # noqa: N803
4909 whitepoint: None | float | str | tuple | list = None,
4910 ) -> tuple[float, float, float]:
4911 """Convert from XYZ to CIE Lu'v'.
4912
4913 Args:
4914 X (float): X value.
4915 Y (float): Y value.
4916 Z (float): Z value.
4917 whitepoint (None | float | str | tuple | list): Whitepoint to
4918 use for conversion. Defaults to D50 if not set.
4919
4920 Returns:
4921 tuple[float, float, float]: A tuple of Lu'v' coordinates (L, u', v').
4922 """
4923 if X + Y + Z == 0:
4924 # We can't check for X == Y == Z == 0 because they may actually add up
4925 # to 0, thus resulting in ZeroDivisionError later
4926 l, u_, v_ = XYZ2Lu_v_(*get_whitepoint(whitepoint))
4927 return 0.0, u_, v_
4928
4929 Xr, Yr, Zr = get_whitepoint(whitepoint, 100) # noqa: N806
4930
4931 yr = Y / Yr
4932
4933 l = 116.0 * cbrt(yr) - 16.0 if yr > LSTAR_E else LSTAR_K * yr
4934
4935 u_ = (4.0 * X) / (X + 15.0 * Y + 3.0 * Z)
4936 v_ = (9.0 * Y) / (X + 15.0 * Y + 3.0 * Z)
4937
4938 return l, u_, v_
4939
4940
4941 def XYZ2Luv( # noqa: N802
4942 X: float, # noqa: N803
4943 Y: float, # noqa: N803
4944 Z: float, # noqa: N803
4945 whitepoint: None | float | str | tuple | list = None,
4946 ) -> tuple[float, float, float]:
4947 """Convert from XYZ to Luv.
4948
4949 Args:
4950 X (float): X value.
4951 Y (float): Y value.
4952 Z (float): Z value.
4953 whitepoint (None | float | str | tuple | list): Whitepoint to use
4954 for conversion. Defaults to D50 if not set.
4955
4956 Returns:
4957 tuple[float, float, float]: A tuple of Luv coordinates (L, u, v).
4958 """
4959 if X + Y + Z == 0: # noqa: N806
4960 # We can't check for X == Y == Z == 0 because they may actually add up
4961 # to 0, thus resulting in ZeroDivisionError later
4962 l, u, v = XYZ2Luv(*get_whitepoint(whitepoint))
4963 return 0.0, u, v
4964
4965 Xr, Yr, Zr = get_whitepoint(whitepoint, 100) # noqa: N806
4966
4967 yr = Y / Yr
4968
4969 l = 116.0 * cbrt(yr) - 16.0 if yr > LSTAR_E else LSTAR_K * yr
4970
4971 u_ = (4.0 * X) / (X + 15.0 * Y + 3.0 * Z)
4972 v_ = (9.0 * Y) / (X + 15.0 * Y + 3.0 * Z)
4973
4974 u_r = (4.0 * Xr) / (Xr + 15.0 * Yr + 3.0 * Zr)
4975 v_r = (9.0 * Yr) / (Xr + 15.0 * Yr + 3.0 * Zr)
4976
4977 u = 13.0 * l * (u_ - u_r)
4978 v = 13.0 * l * (v_ - v_r)
4979
4980 return l, u, v
4981
4982
4983 def XYZ2RGB( # noqa: N802
4984 X: float, # noqa: N803
4985 Y: float, # noqa: N803
4986 Z: float, # noqa: N803
4987 rgb_space: None | str | list | tuple = None,
4988 scale: float = 1.0,
4989 round_: bool = False,
4990 clamp: bool = True,
4991 oetf: None | Callable = None,
4992 ) -> list[float]:
4993 """Convert from XYZ to RGB.
4994
4995 Use optional RGB colorspace definition, which can be a named colorspace
4996 (e.g. "CIE RGB") or must be a tuple in the following format:
4997
4998 (gamma, whitepoint, red, green, blue)
4999
5000 whitepoint can be a string (e.g. "D50"), a tuple of XYZ coordinates,
5001 or a color temperatur in degrees K (float or int). Gamma should be a float.
5002 The RGB primaries red, green, blue should be lists or tuples of xyY
5003 coordinates (only x and y will be used, so Y can be zero or None).
5004
5005 If no colorspace is given, it defaults to sRGB.
5006
5007 Based on formula from http://brucelindbloom.com/Eqn_XYZ_to_RGB.html
5008
5009 Implementation Notes:
5010 1. The transformation matrix [M] is calculated from the RGB reference
5011 primaries as discussed here:
5012 http://brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html
5013 2. gamma is the gamma value of the RGB color system used. Many common ones
5014 may be found here:
5015 http://brucelindbloom.com/WorkingSpaceInfo.html#Specifications
5016 3. The output RGB values are in the nominal range [0.0, scale].
5017 4. If the input XYZ color is not relative to the same reference white as
5018 the RGB system, you must first apply a chromatic adaptation transform
5019 [http://brucelindbloom.com/Eqn_ChromAdapt.html] to the XYZ color to
5020 convert it from its own reference white to the reference white of the
5021 RGB system.
5022 5. Sometimes the more complicated special case of sRGB shown above is
5023 replaced by a "simplified" version using a straight gamma function with
5024 gamma = 2.2.
5025
5026 Args:
5027 X (float): X value.
5028 Y (float): Y value.
5029 Z (float): Z value.
5030 rgb_space (None | str | list | tuple): RGB colorspace definition.
5031 Defaults to sRGB.
5032 scale (float): Scale factor for RGB output. Defaults to 1.0.
5033 round_ (int | bool): Number of decimal places to round the output to.
5034 If False, no rounding is applied. Defaults to False.
5035 clamp (bool): If True, clamps the RGB values to the range [0.0, 1.0].
5036 Defaults to True.
5037 oetf (None | callable): Optional opto-electronic transfer function
5038 to apply to the RGB values. If None, no OETF is applied.
5039 Defaults to None.
5040
5041 Returns:
5042 list[float]: RGB values in the range [0.0, scale].
5043 """
5044 trc, _whitepoint, _rxyY, _gxyY, _bxyY, matrix = get_rgb_space(rgb_space) # noqa: N806
5045 rgb = matrix.inverted() * [X, Y, Z]
5046 is_trc = isinstance(trc, (list, tuple))
5047 for i, v in enumerate(rgb):
5048 gamma = trc[i] if is_trc else trc
5049 if clamp:
5050 v = min(1.0, max(0.0, v))
5051 if oetf:
5052 rgb[i] = oetf(v)
5053 elif isinstance(gamma, (list, tuple)):
5054 key = id(gamma)
5055 if key not in XYZ2RGB.interp:
5056 ginterp = Interp(
5057 gamma,
5058 [n / float(len(gamma) - 1) for n in range(len(gamma))],
5059 use_numpy=True,
5060 )
5061 XYZ2RGB.interp[key] = ginterp
5062 else:
5063 ginterp = XYZ2RGB.interp[key]
5064 rgb[i] = ginterp(v)
5065 else:
5066 rgb[i] = special_pow(v, 1.0 / gamma)
5067 rgb[i] *= scale
5068 if round_ is not False:
5069 rgb[i] = round(rgb[i], round_)
5070 return rgb
5071
5072
5073 XYZ2RGB.interp = {}
5074
5075
5076 def XYZ2xyY( # noqa: N802
5077 X: float, # noqa: N803
5078 Y: float, # noqa: N803
5079 Z: float, # noqa: N803
5080 whitepoint: None | float | str | tuple | list = None,
5081 ) -> tuple[float, float, float]:
5082 """Convert from XYZ to xyY.
5083
5084 Based on formula from http://brucelindbloom.com/Eqn_XYZ_to_xyY.html
5085
5086 Implementation Notes:
5087 1. Watch out for black, where X = Y = Z = 0. In that case, x and y are set
5088 to the chromaticity coordinates of the reference whitepoint.
5089 2. The output Y value is in the nominal range [0.0, Y[XYZ]].
5090
5091 Args:
5092 X (float): X value.
5093 Y (float): Y value.
5094 Z (float): Z value.
5095 whitepoint (None | float | str | tuple | list): Whitepoint.
5096 Defaults to D50.
5097
5098 Returns:
5099 tuple[float, float, float]: x, y, Y values.
5100 """
5101 if X + Y + Z == 0:
5102 # We can't check for X == Y == Z == 0 because they may actually add up
5103 # to 0, thus resulting in ZeroDivisionError later
5104 x, y, Y = XYZ2xyY(*get_whitepoint(whitepoint)) # noqa: N806
5105 return x, y, 0.0
5106 x = X / float(X + Y + Z)
5107 y = Y / float(X + Y + Z)
5108 return x, y, Y
5109
5110
5111 def xy_CCT_delta( # noqa: N802
5112 x: float, y: float, daylight: bool = True, method: int = 2000
5113 ) -> tuple[float, float]:
5114 """Return CCT and delta to locus.
5115
5116 Args:
5117 x (float): x chromaticity coordinate
5118 y (float): y chromaticity coordinate
5119 daylight (bool): True for daylight locus, False for planckian locus
5120 method (int): Method to use for delta calculation
5121
5122 Returns:
5123 tuple[float, float]: CCT and delta to locus.
5124 """
5125 cct = xyY2CCT(x, y)
5126 d = None
5127 if cct:
5128 locus = None
5129 if daylight:
5130 # Daylight locus
5131 if 2500 <= cct <= 25000:
5132 locus = CIEDCCT2XYZ(cct, 100.0)
5133 # Planckian locus
5134 elif 1667 <= cct <= 25000:
5135 locus = planckianCT2XYZ(cct, 100.0)
5136 if locus:
5137 l2, a2, b2 = xyY2Lab(x, y, 100.0, locus)
5138 d = delta(l2, 0, 0, l2, a2, b2, method)
5139 return cct, d
5140
5141
5142 def dmatrixz(nrl: int, nrh: int, ncl: int, nch: int) -> dict:
5143 """Create a 2D matrix of dictionaries.
5144
5145 Adapted from ArgyllCMS numlib/numsup.c
5146
5147 Args:
5148 nrl (int): Row low index
5149 nrh (int): Row high index
5150 ncl (int): Col low index
5151 nch (int): Col high index
5152
5153 Returns:
5154 dict: A dictionary containing the matrix.
5155 """
5156 m = {}
5157
5158 nrh = max(nrh, nrl) # Prevent failure for 0 dimension
5159 nch = max(nch, ncl)
5160
5161 rows = nrh - nrl + 1
5162 cols = nch - ncl + 1
5163
5164 for i in range(rows):
5165 m[i + nrl] = {}
5166 for j in range(cols):
5167 m[i][j + ncl] = 0
5168
5169 return m
5170
5171
5172 def dvector(nl: int, nh: int) -> dict:
5173 """Adapted from ArgyllCMS numlib/numsup.c.
5174
5175 Args:
5176 nl: Lowest index
5177 nh: Highest index
5178
5179 Returns:
5180 dict: Empty dictionary.
5181 """
5182 return {}
5183
5184
5185 def gam_fit(gf: GammaFits, v: list[float]) -> float:
5186 """Gamma + input offset function handed to powell().
5187
5188 Adapted from ArgyllCMS xicc/xicc.c
5189
5190 Args:
5191 gf (GammaFits): Gamma fit object containing parameters.
5192 v (list[float]): List of gamma values to fit.
5193
5194 Returns:
5195 float: Squared error value for the fit.
5196 """
5197 gamma = v[0]
5198 rv = 0.0
5199
5200 if gamma < 0.0:
5201 rv += 100.0 * -gamma
5202 gamma = 1e-4
5203
5204 t1 = math.pow(gf.bp, 1.0 / gamma)
5205 t2 = math.pow(gf.wp, 1.0 / gamma)
5206 b = t1 / (t2 - t1) # Offset
5207 a = math.pow(t2 - t1, gamma) # Gain
5208
5209 # Comput 50% output for this technical gamma
5210 # (All values are without output offset being added in)
5211 t1 = a * math.pow(0.5 + b, gamma)
5212 t1 = t1 - gf.thyr
5213 rv += t1 * t1
5214
5215 return rv
5216
5217
5218 def linmin(
5219 cp: list[float],
5220 xi: list[float],
5221 di: int,
5222 ftol: float,
5223 func: Callable,
5224 fdata: Any, # noqa: ANN401
5225 ) -> float:
5226 """Line bracketing and minimisation routine.
5227
5228 Return value at minimum.
5229
5230 Adapted from ArgyllCMS numlib/powell.c
5231
5232 Args:
5233 cp (list[float]): Start point, and returned value.
5234 xi (list[float]): Search vector.
5235 di (int): Dimensionality.
5236 ftol (float): Tolerance to stop on.
5237 func (callable): Error function to evaluate.
5238 fdata: Opaque data for func().
5239
5240 Returns:
5241 float: Value at minimum.
5242 """
5243 # ax, xx, bx # Search vector multipliers
5244 # af, xf, bf # Function values at those points
5245 # xt # Trial point
5246
5247 xt = {} if di <= 10 else dvector(0, di - 1) # Vector for trial point
5248
5249 # --------------------------
5250 # First bracket the solution
5251
5252 ax, xx, bx, af, xf, bf = _linmin_bracket_solution(cp, xi, xt, di, func, fdata)
5253
5254 # ---------------------------------------
5255 # Now use brent minimiser bewteen a and b
5256
5257 return _linmin_use_brent_minimiser(
5258 ax,
5259 xx,
5260 bx,
5261 af,
5262 xf,
5263 bf,
5264 cp,
5265 xi,
5266 di,
5267 ftol,
5268 func,
5269 fdata,
5270 xt,
5271 )
5272
5273
5274 def _linmin_bracket_solution( # noqa: C901
5275 cp: list[float],
5276 xi: list[float],
5277 xt: dict | list[float], # Vector for trial point
5278 di: int,
5279 func: Callable,
5280 fdata: Any, # noqa: ANN401
5281 ) -> tuple[float, float, float, float, float, float]:
5282 """Bracket the solution for the line minimisation.
5283
5284 Args:
5285 cp (list[float]): Start point, and returned value.
5286 xi (list[float]): Search vector.
5287 xt (dict | list[float]): Vector for trial point.
5288 di (int): Dimensionality.
5289 func (callable): Error function to evaluate.
5290 fdata: Opaque data for func().
5291
5292 Returns:
5293 tuple[float, float, float, float, float, float]: ax, xx, bx, af, xf,
5294 bf - Search vector multipliers and function values at those points.
5295 """
5296 powell_gold = 1.618034
5297 logger.debug("linmin: Bracketing solution")
5298
5299 # The line is measured as startpoint + offset * search vector.
5300 # (Search isn't symetric, but it seems to depend on cp being
5301 # best current solution ?)
5302 ax = 0.0
5303 for i in range(di):
5304 xt[i] = cp[i] + ax * xi[i]
5305 af = func(fdata, xt)
5306
5307 # xx being vector offset 0.618
5308 xx = 1.0 / powell_gold
5309 for i in range(di):
5310 xt[i] = cp[i] + xx * xi[i]
5311 xf = func(fdata, xt)
5312
5313 logger.debug(f"linmin: Initial points a:{ax:f}:{af:f} -> b:{xx:f}:{xf:f}")
5314
5315 # Fix it so that we are decreasing from point a -> x
5316 if xf > af:
5317 tt = ax
5318 ax = xx
5319 xx = tt
5320 tt = af
5321 af = xf
5322 xf = tt
5323
5324 logger.debug(f"linmin: Ordered Initial points a:{ax:f}:{af:f} -> b:{xx:f}:{xf:f}")
5325
5326 bx = xx + powell_gold * (xx - ax) # Guess b beyond a -> x
5327 for i in range(di):
5328 xt[i] = cp[i] + bx * xi[i]
5329 bf = func(fdata, xt)
5330
5331 logger.debug(
5332 f"linmin: Initial bracket a:{ax:f}:{af:f} x:{xx:f}:{xf:f} b:{bx:f}:{bf:f}"
5333 )
5334
5335 # While not bracketed
5336 while xf > bf:
5337 logger.debug(f"linmin: Not bracketed because xf {xf:f} > bf {bf:f}")
5338 logger.debug(f" ax = {ax:f}, xx = {xx:f}, bx = {bx:f}")
5339
5340 # Compute ux by parabolic interpolation from a, x & b
5341 q = (xx - bx) * (xf - af)
5342 r = (xx - ax) * (xf - bf)
5343 tt = q - r
5344 if 0.0 <= tt < 1e-20: # If +ve too small
5345 tt = 1e-20
5346 elif 0.0 >= tt > -1e-20: # If -ve too small
5347 tt = -1e-20
5348 ux = xx - ((xx - bx) * q - (xx - ax) * r) / (2.0 * tt)
5349 ulim = xx + 100.0 * (bx - xx) # Extrapolation limit
5350
5351 if (xx - ux) * (ux - bx) > 0.0: # u is between x and b
5352 for i in range(di): # Evaluate u
5353 xt[i] = cp[i] + ux * xi[i]
5354 uf = func(fdata, xt)
5355
5356 if uf < bf: # Minimum is between x and b
5357 ax = xx
5358 af = xf
5359 xx = ux
5360 xf = uf
5361 break
5362 if uf > xf: # Minimum is between a and u
5363 bx = ux
5364 bf = uf
5365 break
5366
5367 # Parabolic fit didn't work, look further out in direction of b
5368 ux = bx + powell_gold * (bx - xx)
5369
5370 elif (bx - ux) * (ux - ulim) > 0.0: # u is between b and limit
5371 for i in range(di): # Evaluate u
5372 xt[i] = cp[i] + ux * xi[i]
5373 uf = func(fdata, xt)
5374
5375 if uf > bf: # Minimum is between x and u
5376 ax = xx
5377 af = xf
5378 xx = bx
5379 xf = bf
5380 bx = ux
5381 bf = uf
5382 break
5383 xx = bx
5384 xf = bf # Continue looking
5385 bx = ux
5386 bf = uf
5387 ux = bx + powell_gold * (bx - xx) # Test beyond b
5388
5389 elif (ux - ulim) * (ulim - bx) >= 0.0: # u is beyond limit
5390 ux = ulim
5391 else: # u is to left side of x ?
5392 ux = bx + powell_gold * (bx - xx)
5393 # Evaluate u, and move into place at b
5394 for i in range(di):
5395 xt[i] = cp[i] + ux * xi[i]
5396 uf = func(fdata, xt)
5397 ax = xx
5398 af = xf
5399 xx = bx
5400 xf = bf
5401 bx = ux
5402 bf = uf
5403 logger.debug(f"linmin: Got bracket a:{ax:f}:{af:f} x:{xx:f}:{xf:f} b:{bx:f}:{bf:f}")
5404 # Got bracketed minimum between a -> x -> b
5405
5406 return ax, xx, bx, af, xf, bf # noqa: N806
5407
5408
5409 def _linmin_use_brent_minimiser( # noqa: C901
5410 ax: float,
5411 xx: float,
5412 bx: float,
5413 af: float,
5414 xf: float,
5415 bf: float,
5416 cp: list[float],
5417 xi: list[float],
5418 di: int,
5419 ftol: float,
5420 func: Callable,
5421 fdata: Any, # noqa: ANN401
5422 xt: dict | list[float], # Vector for trial point
5423 ) -> float:
5424 """Use Brent's method to find the minimum between a and b.
5425
5426 Adapted from ArgyllCMS numlib/powell.c
5427
5428 Args:
5429 ax (float): Lower bound of the bracket.
5430 xx (float): Current best point.
5431 bx (float): Upper bound of the bracket.
5432 af (float): Function value at ax.
5433 xf (float): Function value at xx.
5434 bf (float): Function value at bx.
5435 cp (list[float]): Current point.
5436 xi (list[float]): Search vector.
5437 di (int): Dimensionality of the problem.
5438 ftol (float): Tolerance for convergence.
5439 func (Callable): Function to minimize.
5440 fdata (Any): Opaque data for func().
5441 xt (dict | list[float]): Vector for trial point.
5442
5443 Returns:
5444 float: Value at minimum.
5445 """
5446 powell_cgold = 0.3819660
5447 powell_max_iterations = 100
5448
5449 # a and b bracket solution
5450 # x is best function value so far
5451 # w is second best function value so far
5452 # v is previous second best, or third best
5453 # u is most recently tested point
5454 # wx, vx, ux # Search vector multipliers
5455 # wf
5456 vf = 0.0
5457 # uf # Function values at those points
5458 de = 0.0 # Distance moved on previous step
5459 e = 0.0 # Distance moved on 2nd previous step
5460
5461 # Make sure a and b are in ascending order
5462 if ax > bx:
5463 tt = ax
5464 ax = bx
5465 bx = tt
5466 tt = af
5467 af = bf
5468 bf = tt
5469
5470 wx = vx = xx # Initial values of other center points
5471 wf = xf = xf
5472
5473 for _iter in range(1, powell_max_iterations + 1):
5474 mx = 0.5 * (ax + bx) # m is center of bracket values
5475 # if ABSTOL:
5476 # tol1 = ftol # Absolute tollerance
5477 # else:
5478 tol1 = ftol * abs(xx) + 1e-10
5479 tol2 = 2.0 * tol1
5480
5481 logger.debug(
5482 f"linmin: Got bracket a:{ax:f}:{af:f} x:{xx:f}:{xf:f} b:{bx:f}:{bf:f}"
5483 )
5484
5485 # See if we're done
5486 if abs(xx - mx) <= (tol2 - 0.5 * (bx - ax)):
5487 logger.debug(
5488 "linmin: We're done because "
5489 f"{abs(xx - mx):f} <= {tol2 - 0.5 * (bx - ax):f}"
5490 )
5491 break
5492
5493 if abs(e) > tol1: # Do a trial parabolic fit
5494 r = (xx - wx) * (xf - vf)
5495 q = (xx - vx) * (xf - wf)
5496 p = (xx - vx) * q - (xx - wx) * r
5497 q = 2.0 * (q - r)
5498 if q > 0.0:
5499 p = -p
5500 else:
5501 q = -q
5502 te = e # Save previous e value
5503 e = de # Previous steps distance moved
5504
5505 logger.debug("linmin: Trial parabolic fit")
5506
5507 if abs(p) >= abs(0.5 * q * te) or p <= q * (ax - xx) or p >= q * (bx - xx):
5508 # Give up on the parabolic fit, and use the golden section search
5509 e = (
5510 ax - xx if xx >= mx else bx - xx
5511 ) # Override previous distance moved */
5512 de = powell_cgold * e
5513 logger.debug("linmin: Moving to golden section search")
5514 else: # Use parabolic fit
5515 de = p / q # Change in xb
5516 ux = xx + de # Trial point according to parabolic fit
5517 if (ux - ax) < tol2 or (bx - ux) < tol2:
5518 # Don't use parabolic, use tol1 if (mx - xx) > 0.0: tol1 is +ve
5519 de = tol1 if (mx - xx) > 0.0 else -tol1
5520 logger.debug("linmin: Using parabolic fit")
5521 else: # Keep using the golden section search
5522 e = ax - xx if xx >= mx else bx - xx # Override previous distance moved
5523 de = powell_cgold * e
5524 logger.debug("linmin: Continuing golden section search")
5525
5526 if abs(de) >= tol1: # If de moves as much as tol1 would
5527 ux = xx + de # use it
5528 logger.debug(f"linmin: ux = {ux:f} = xx {xx:f} + de {de:f}")
5529 elif de > 0.0:
5530 ux = xx + tol1
5531 logger.debug(f"linmin: ux = {ux:f} = xx {xx:f} + tol1 {tol1:f}")
5532 else:
5533 ux = xx - tol1
5534 logger.debug(f"linmin: ux = {ux:f} = xx {xx:f} - tol1 {tol1:f}")
5535
5536 # Evaluate function
5537 for i in range(di):
5538 xt[i] = cp[i] + ux * xi[i]
5539 uf = func(fdata, xt)
5540
5541 if uf <= xf: # Found new best solution
5542 if ux >= xx:
5543 ax = xx
5544 af = xf # New lower bracket
5545 else:
5546 bx = xx
5547 bf = xf # New upper bracket
5548 vx = wx
5549 vf = wf # New previous 2nd best solution
5550 wx = xx
5551 wf = xf # New 2nd best solution from previous best
5552 xx = ux
5553 xf = uf # New best solution from latest
5554 logger.debug("linmin: found new best solution")
5555 else: # Found a worse solution
5556 if ux < xx:
5557 ax = ux
5558 af = uf # New lower bracket
5559 else:
5560 bx = ux
5561 bf = uf # New upper bracket
5562 if uf <= wf or wx == xx: # New 2nd best solution, or equal best
5563 vx = wx
5564 vf = wf # New previous 2nd best solution
5565 wx = ux
5566 wf = uf # New 2nd best from latest
5567 elif uf <= vf or vx in [xx, wx]: # New 3rd best, or equal 1st & 2nd
5568 vx = ux
5569 vf = uf # New previous 2nd best from latest
5570 logger.debug("linmin: found new worse solution")
5571 # !!! should do something if iter > POWELL_MAXIT !!!!
5572 # Solution is at xx, xf
5573
5574 # Compute solution vector
5575 for i in range(di):
5576 cp[i] += xx * xi[i]
5577
5578 return xf # Return value at minimum
5579
5580
5581 def powell( # noqa: C901
5582 di: int,
5583 cp: list[float],
5584 s: list[float],
5585 ftol: float,
5586 maxit: int,
5587 func: Callable,
5588 fdata: list,
5589 prog: None | Callable = None,
5590 pdata: None | list = None,
5591 ) -> bool:
5592 """Standard interface for powell function.
5593
5594 Adapted from ArgyllCMS `powell.c`.
5595
5596 Args:
5597 di (int): Dimensionality of the problem.
5598 cp (list[float]): Initial starting point, will be modified to the
5599 solution.
5600 s (list[float]): Size of initial search area, must be same length as
5601 cp.
5602 ftol (float): Tolerance of error change to stop on.
5603 maxit (int): Maximum iterations allowed.
5604 func (Callable): Error function to evaluate.
5605 fdata (list): Opaque data needed by function.
5606 prog (Callable | None): Optional progress percentage callback.
5607 pdata: Opaque data needed by prog().
5608
5609 Returns:
5610 bool: True on sucess, False on failure due to excessive iterions, result
5611 will be in cp
5612 """
5613 if prog is None:
5614
5615 def prog(*args, **kwargs) -> None:
5616 """Dummy progress function."""
5617
5618 dbl_epsilon = 2.2204460492503131e-016
5619 # dmtx # Direction vector
5620 # sp # Sarting point before exploring all the directions
5621 # xpt # Extrapolated point
5622 # svec # Search vector
5623 # retv # Returned function value at p
5624 # stopth # Current stop threshold */
5625 startdel = -1.0 # Initial change in function value
5626 # curdel # Current change in function value
5627 pc = 0 # Percentage complete
5628
5629 dmtx = dmatrixz(0, di - 1, 0, di - 1) # Zero filled
5630 spt = dvector(0, di - 1)
5631 xpt = dvector(0, di - 1)
5632 svec = dvector(0, di - 1)
5633
5634 # Create initial direction matrix by
5635 # placing search start on diagonal
5636 for i in range(di):
5637 dmtx[i][i] = s[i]
5638 # Save the starting point
5639 spt[i] = cp[i]
5640
5641 # Report initial progress
5642 prog(pdata, pc)
5643
5644 # Initial function evaluation
5645 retv = func(fdata, cp)
5646
5647 # Iterate untill we converge on a solution, or give up.
5648 for iter_ in range(1, maxit):
5649 # lretv # Last function return value
5650 ibig = 0 # Index of biggest delta
5651 del_ = 0.0 # Biggest function value decrease
5652 # pretv # Previous function return value
5653
5654 pretv = retv # Save return value at top of iteration
5655
5656 # Loop over all directions in the set
5657 for i in range(di):
5658 logger.debug(f"Looping over direction {i}")
5659
5660 for j in range(di): # Extract this direction to make search vector
5661 svec[j] = dmtx[j][i]
5662
5663 # Minimize in that direction
5664 lretv = retv
5665 retv = linmin(cp, svec, di, ftol, func, fdata)
5666
5667 # Record bigest function decrease, and dimension it occurred on
5668 if abs(lretv - retv) > del_:
5669 del_ = abs(lretv - retv)
5670 ibig = i
5671
5672 # if ABSTOL:
5673 # stopth = ftol # Absolute tollerance
5674 # else
5675 stopth = ftol * 0.5 * (abs(pretv) + abs(retv) + dbl_epsilon)
5676 curdel = abs(pretv - retv)
5677 if startdel < 0.0:
5678 startdel = curdel
5679 elif curdel > 0 and startdel > 0:
5680 tt = (
5681 100.0
5682 * math.pow(
5683 (math.log(curdel) - math.log(startdel))
5684 / (math.log(stopth) - math.log(startdel)),
5685 4.0,
5686 )
5687 + 0.5
5688 )
5689 if pc < tt < 100:
5690 pc = tt
5691 # Report initial progress
5692 prog(pdata, pc)
5693
5694 # If we have had at least one change of direction and
5695 # reached a suitable tollerance, then finish
5696 if iter_ > 1 and curdel <= stopth:
5697 logger.debug(
5698 f"Reached stop tollerance because curdel {curdel:f} <= stopth "
5699 f"{stopth:f}"
5700 )
5701 break
5702 logger.debug(f"Not stopping because curdel {curdel:f} > stopth {stopth:f}")
5703
5704 for i in range(di):
5705 svec[i] = cp[i] - spt[i] # Average direction moved after minimization round
5706 xpt[i] = cp[i] + svec[i] # Extrapolated point after round of minimization
5707 spt[i] = cp[i] # New start point for next round
5708
5709 # Function value at extrapolated point
5710 lretv = func(fdata, xpt)
5711
5712 if lretv >= pretv: # If extrapolation is not an improvement
5713 continue
5714 t1 = pretv - retv - del_
5715 t2 = pretv - lretv
5716 t = 2.0 * (pretv - 2.0 * retv + lretv) * t1 * t1 - del_ * t2 * t2
5717 if t >= 0.0:
5718 continue
5719 # Move to the minimum of the new direction
5720 retv = linmin(cp, svec, di, ftol, func, fdata)
5721
5722 for i in range(di): # Save the new direction
5723 dmtx[i][ibig] = svec[i] # by replacing best previous
5724
5725 # Report final progress
5726 prog(pdata, 100)
5727
5728 if iter_ < maxit:
5729 return True
5730
5731 logger.debug("powell: returning False due to excessive iterations")
5732 return False # Failed due to execessive iterations
5733
5734
5735 def xicc_tech_gamma(
5736 egamma: float, input_offset: float, output_offset: float = 0.0
5737 ) -> float:
5738 """Compute technical gamma for correct 50% response.
5739
5740 Adapted from ArgyllCMS xicc.c
5741
5742 Args:
5743 egamma (float): The effective gamma.
5744 input_offset (float): The input offset.
5745 output_offset (float, optional): The output offset. Defaults to 0.0.
5746
5747 Returns:
5748 float: The technical gamma.
5749 """
5750 gf = GammaFits()
5751 op = {}
5752 sa = {}
5753
5754 if input_offset <= 0.0:
5755 return egamma
5756
5757 # We set up targets without outo being added
5758 outo = input_offset * output_offset # Offset acounted for in output
5759 gf.bp = input_offset - outo # Black value for 0 % input
5760 gf.wp = 1.0 - outo # White value for 100% input
5761 gf.thyr = math.pow(0.5, egamma) - outo # Advetised 50% target
5762
5763 op[0] = egamma
5764 sa[0] = 0.1
5765
5766 if not powell(1, op, sa, 1e-6, 500, gam_fit, gf):
5767 logger.warning("Computing effective gamma and input offset is inaccurate!")
5768
5769 return op[0]
5770
5771
5772 class GammaFits:
5773 """Gamma fits class for xicc technical gamma computation.
5774
5775 Adapted from ArgyllCMS xicc/xicc.c.
5776
5777 Args:
5778 wp (float): 100% input target.
5779 thyr (float): 50% input target.
5780 bp (float): 0% input target.
5781 """
5782
5783 def __init__(self, wp: float = 1.0, thyr: float = 0.2, bp: float = 0.0) -> None:
5784 self.wp = wp # 100% input target
5785 self.thyr = thyr # 50% input target
5786 self.bp = bp # 0% input target
5787
5788
5789 class Interp:
5790 """Interpolation class.
5791
5792 Args:
5793 xp (list): x values for interpolation.
5794 fp (list): f(x) values for interpolation.
5795 left (float, optional): Value to return for x < min(xp). Defaults to
5796 None.
5797 right (float, optional): Value to return for x > max(xp). Defaults to
5798 None.
5799 use_numpy (bool, optional): Use numpy for speed. Defaults to False.
5800 """
5801
5802 def __init__(
5803 self,
5804 xp: list[float],
5805 fp: list[float],
5806 left: None | float = None,
5807 right: None | float = None,
5808 use_numpy: bool = False,
5809 ) -> None:
5810 if use_numpy:
5811 # Use numpy for speed
5812 xp = numpy.array(xp)
5813 fp = numpy.array(fp)
5814 self.xp = xp
5815 self.fp = fp
5816 self.left = left
5817 self.right = right
5818 self.lookup = {}
5819 self.use_numpy = use_numpy
5820
5821 def __call__(self, x: float) -> float:
5822 """Return the interpolated value for x.
5823
5824 Args:
5825 x (float): The x value to interpolate.
5826
5827 Returns:
5828 float: The interpolated value at x.
5829 """
5830 if x not in self.lookup:
5831 self.lookup[x] = self._interp(x)
5832 return self.lookup[x]
5833
5834 def _interp(self, x: float) -> float:
5835 """Perform the interpolation.
5836
5837 Args:
5838 x (float): The x value to interpolate.
5839
5840 Returns:
5841 float: The interpolated value at x.
5842 """
5843 if self.use_numpy:
5844 return numpy.interp(x, self.xp, self.fp, self.left, self.right)
5845 return interp(x, self.xp, self.fp, self.left, self.right)
5846
5847
5848 class BT1886:
5849 """BT.1886 like transfer function.
5850
5851 Adapted from ArgyllCMS xicc/xicc.c
5852
5853 Args:
5854 matrix (Matrix): Matrix to use for forward and backward transformations.
5855 XYZbp (tuple[float, float, float]): Black point in XYZ coordinates.
5856 outoffset (float): Output offset. Defaults to 0.0.
5857 gamma (float): Gamma value. Defaults to 2.4.
5858 apply_trc (bool): Whether to apply the transfer curve. Defaults to True.
5859 """
5860
5861 def __init__(
5862 self,
5863 matrix: Matrix3x3,
5864 XYZbp: tuple[float, float, float], # noqa: N803
5865 outoffset: float = 0.0,
5866 gamma: float = 2.4,
5867 apply_trc: bool = True,
5868 ) -> None:
5869 """Setup BT.1886 for the given target.
5870
5871 If apply_trc is False, apply only the black point blending portion of
5872 BT.1886 mapping. Note that this will only work correctly for an output
5873 offset of 1.0
5874
5875 """
5876 if not apply_trc and outoffset < 1:
5877 raise ValueError("Output offset must be 1.0 when not applying gamma")
5878
5879 self.bwd_matrix = matrix.inverted()
5880 self.fwd_matrix = matrix
5881 self.gamma = gamma
5882
5883 lab = XYZ2Lab(*[v * 100 for v in XYZbp])
5884
5885 # For bp blend
5886 self.outL = lab[0]
5887 # a* b* correction needed
5888 self.tab = list(lab)
5889 self.tab[0] = 0 # 0 because bt1886 maps L to target
5890
5891 if XYZbp[1] < 0:
5892 XYZbp = list(XYZbp) # noqa: N806
5893 XYZbp[1] = 0.0
5894
5895 # Offset acounted for in output
5896 self.outo = XYZbp[1] * outoffset
5897 # Balance of offset accounted for in input
5898 ino = XYZbp[1] - self.outo
5899
5900 # Input offset black to 1/pow
5901 bkipow = math.pow(ino, 1.0 / self.gamma)
5902 # Input offset white to 1/pow
5903 wtipow = math.pow(1.0 - self.outo, 1.0 / self.gamma)
5904 # non-linear Y that makes input offset proportion of black point
5905 self.ingo = bkipow / (wtipow - bkipow)
5906 # Scale to make input of 1 map to 1.0 - self.outo
5907 self.outsc = pow(wtipow - bkipow, self.gamma)
5908 self.apply_trc = apply_trc
5909
5910 def apply(self, X: float, Y: float, Z: float) -> tuple[float, float, float]: # noqa: N803
5911 """Apply BT.1886 black offset + gamma curve to the XYZ out of the input profile.
5912
5913 Do this in the colorspace defined by the input profile matrix lookup,
5914 so it will be relative XYZ. We assume that BT.1886 does a Rec709 to gamma
5915 viewing adjustment, on top of any source profile transfer curve
5916 (i.e. BT.1886 viewing adjustment is assumed to be the mismatch between
5917 Rec709 curve and the output offset pure 2.4 gamma curve)
5918
5919 Args:
5920 X (float): X value in XYZ
5921 Y (float): Y value in XYZ
5922 Z (float): Z value in XYZ
5923
5924 Returns:
5925 tuple[float, float, float]: Adjusted XYZ values as a tuple (X, Y, Z).
5926 """
5927 logger.debug(f"bt1886 XYZ in {X:f} {Y:f} {Z:f}")
5928
5929 out = self.bwd_matrix * (X, Y, Z)
5930
5931 logger.debug(f"bt1886 RGB in {out[0]:f} {out[1]:f} {out[2]:f}")
5932
5933 for j in range(3):
5934 vv = out[j]
5935
5936 if self.apply_trc:
5937 # Convert linear light to Rec709 transfer curve
5938 vv = 4.5 * vv if vv < 0.018 else 1.099 * math.pow(vv, 0.45) - 0.099
5939
5940 # Apply input offset
5941 vv = vv + self.ingo
5942
5943 # Apply power and scale
5944 if vv > 0.0:
5945 if self.apply_trc:
5946 vv = self.outsc * math.pow(vv, self.gamma)
5947 else:
5948 vv *= self.outsc
5949
5950 # Apply output portion of offset
5951 vv += self.outo
5952
5953 out[j] = vv
5954
5955 out = self.fwd_matrix * out
5956
5957 logger.debug(f"bt1886 RGB bt.1886 {out[0]:f} {out[1]:f} {out[2]:f}")
5958
5959 out = list(XYZ2Lab(*[v * 100 for v in out]))
5960
5961 logger.debug(f"bt1886 Lab after Y adj. {out[0]:f} {out[1]:f} {out[2]:f}")
5962
5963 # Blend ab to required black point offset self.tab[] as L approaches black.
5964 vv = (out[0] - self.outL) / (100.0 - self.outL) # 0 at bp, 1 at wp
5965 vv = 1.0 - vv
5966
5967 if vv < 0.0:
5968 vv = 0.0
5969 elif vv > 1.0:
5970 vv = 1.0
5971 vv = math.pow(vv, 40.0)
5972 out[0] += vv * self.tab[0]
5973 out[1] += vv * self.tab[1]
5974 out[2] += vv * self.tab[2]
5975
5976 logger.debug(f"bt1886 Lab after wp adj. {out[0]:f} {out[1]:f} {out[2]:f}")
5977 out = Lab2XYZ(*out)
5978 logger.debug(f"bt1886 XYZ out {out[0]:f} {out[1]:f} {out[2]:f}")
5979 return out
5980
5981
5982 class BT2390:
5983 """Roll-off for SMPTE 2084 (PQ) according to Report ITU-R BT.2390-2 HDR TV.
5984
5985 Args:
5986 black_cdm2 (float): Black level in cd/m^2.
5987 white_cdm2 (float): White level in cd/m^2.
5988 master_black_cdm2 (float, optional): Mastering black level in cd/m^2.
5989 Defaults to 0.
5990 master_white_cdm2 (float, optional): Mastering white level in cd/m^2.
5991 Defaults to 10000.
5992 use_alternate_master_white_clip (bool, optional): If True, use an
5993 alternate method for mastering white clipping. Defaults to True.
5994 """
5995
5996 def __init__(
5997 self,
5998 black_cdm2: float,
5999 white_cdm2: float,
6000 master_black_cdm2: float = 0,
6001 master_white_cdm2: float = 10000,
6002 use_alternate_master_white_clip: bool = True,
6003 ) -> None:
6004 """Master black and white level are used to tweak the roll-off and clip.
6005
6006 If use_alternate_master_white_clip is True, do not follow BT.2390 for
6007 the mastering white adjustment (allows to preserve more detail in
6008 rolled-off highlights)
6009
6010 Args:
6011 black_cdm2 (float): Black level in cd/m^2.
6012 white_cdm2 (float): White level in cd/m^2.
6013 master_black_cdm2 (float, optional): Mastering black level in
6014 cd/m^2. Defaults to 0.
6015 master_white_cdm2 (float, optional): Mastering white level in
6016 cd/m^2. Defaults to 10000.
6017 use_alternate_master_white_clip (bool, optional): If True, use an
6018 alternate method for mastering white clipping. Defaults to
6019 True.
6020 """
6021 self.black_cdm2 = black_cdm2
6022 self.white_cdm2 = white_cdm2
6023 self.master_black_cdm2 = master_black_cdm2
6024 self.master_white_cdm2 = master_white_cdm2
6025
6026 self.ominv = black_cdm2 / 10000.0 # Lmin
6027 self.omini = special_pow(self.ominv, 1.0 / -2084) # Original minLum
6028 self.omaxv = white_cdm2 / 10000.0 # Lmax
6029 self.omaxi = special_pow(self.omaxv, 1.0 / -2084) # Original maxLum
6030
6031 self.oKS = 1.5 * self.omaxi - 0.5
6032
6033 # BT.2390-2
6034 self.mminv = master_black_cdm2 / 10000.0 # LB
6035 self.mmini = special_pow(self.mminv, 1.0 / -2084)
6036 self.mmaxv = master_white_cdm2 / 10000.0 # LW
6037 mmaxi = special_pow(self.mmaxv, 1.0 / -2084)
6038 if use_alternate_master_white_clip:
6039 self.maxci = (mmaxi - self.mmini) / (1 - self.mmini)
6040 self.mmaxi = 1.0
6041 else:
6042 self.maxci = 1.0
6043 self.mmaxi = mmaxi
6044 self.mini = (self.omini - self.mmini) / (
6045 self.mmaxi - self.mmini
6046 ) # Normalized minLum
6047 self.minv = special_pow(self.mini, -2084)
6048 self.maxi = (self.omaxi - self.mmini) / (
6049 self.mmaxi - self.mmini
6050 ) # Normalized maxLum
6051 self.maxv = special_pow(self.maxi, -2084)
6052
6053 self.KS = 1.5 * self.maxi - 0.5
6054
6055 if self.maxi <= self.maxci < 1:
6056 e2 = self.P(self.maxci, self.KS, self.maxi)
6057 diff = self.maxci - e2
6058 self.s = (self.maxci - self.maxi) / diff
6059
6060 def P(self, B: float, KS: float, maxi: float, maxci: float = 1.0) -> float: # noqa: N802, N803
6061 """Apply the roll-off function P(E1) to the input value E1.
6062
6063 Args:
6064 B (float): Input value E1 to apply the roll-off to.
6065 KS (float): The KS value.
6066 maxi (float): The maximum input value.
6067 maxci (float, optional): The maximum clip input value. Defaults to
6068 1.0.
6069
6070 Returns:
6071 float: The output value after applying the roll-off.
6072 """ # noqa: D402
6073 t = (B - KS) / (1 - KS)
6074 e2 = (
6075 (2 * t**3 - 3 * t**2 + 1) * KS
6076 + (t**3 - 2 * t**2 + t) * (1 - KS)
6077 + (-2 * t**3 + 3 * t**2) * maxi
6078 )
6079 if maxci < 1:
6080 # (Old) Clipping for better target display peak luminance usage
6081 # XXX: Only kept for backwards compatibility
6082 s = min(((B - KS) / (maxci - KS)) ** 4, 1)
6083 e2 = e2 * (1 - s) + maxi * s
6084 return e2
6085
6086 def apply(
6087 self,
6088 v: float,
6089 KS: None | float = None, # noqa: N803
6090 maxi: None | float = None,
6091 maxci: None | float = None,
6092 mini: None | float = None,
6093 mmaxi: None | float = None,
6094 mmini: None | float = None,
6095 bpc: bool = False,
6096 normalize: bool = True,
6097 ) -> float:
6098 """Apply roll-off (E' in, E' out) maxci if < 1.0 applies alterante clip.
6099
6100 Args:
6101 v (float): Input value to apply roll-off to.
6102 KS (float, optional): The KS value. Defaults to self.KS.
6103 maxi (float, optional): The maximum input value. Defaults to
6104 self.maxi.
6105 maxci (float, optional): The maximum clip input value. Defaults to
6106 self.maxci.
6107 mini (float, optional): The minimum input value. Defaults to
6108 self.mini.
6109 mmaxi (float, optional): The mastering maximum input value.
6110 Defaults to self.mmaxi.
6111 mmini (float, optional): The mastering minimum input value.
6112 Defaults to self.mmini.
6113 bpc (bool, optional): If True, apply black point compensation.
6114 Defaults to False.
6115 normalize (bool, optional): If True, normalize PQ values based on
6116 mastering display black/white levels. Defaults to True.
6117
6118 Returns:
6119 float: The output value after applying the roll-off.
6120 """
6121 KS = self.KS if KS is None else KS # noqa: N806
6122 maxi = self.maxi if maxi is None else maxi
6123 mini = self.mini if mini is None else mini
6124 mmaxi = self.mmaxi if mmaxi is None else mmaxi
6125 mmini = self.mmini if mmini is None else mmini
6126 maxci = self.maxci if maxci is None else maxci
6127 if normalize and mmini is not None and mmaxi is not None:
6128 # Normalize PQ values based on mastering display black/white levels
6129 e1 = min(max((v - mmini) / (mmaxi - mmini), 0), 1.0)
6130 else:
6131 e1 = v
6132 # BT.2390-3 suggests P[E1] if KS <= E1 <=1, but this results in
6133 # division by zero if KS = 1. The correct way is to check for
6134 # KS < E1 <=1
6135 if KS < e1 <= 1:
6136 e2 = self.P(e1, KS, maxi)
6137 if maxi <= maxci < 1:
6138 # (New) Clipping for better target display peak luminance usage
6139 s = self.s
6140 diff = e1 - e2
6141 e2 = min(e1 - diff * s, maxi)
6142 elif maxci < 1:
6143 e2 = min(e1, maxci)
6144 else:
6145 e2 = e1
6146 # BT.2390-3 suggests 0 <= E2 <= 1, but this results in a discontinuity
6147 # if KS < 0 (high LB > Lmin, low Lmax, high LW). To avoid this, check
6148 # for E2 <= 1 instead
6149 if mini and e2 <= 1:
6150 # Apply black level lift
6151 min_lum = mini
6152 # maxLum = maxi
6153 b = min_lum
6154 # BT.2390-3 suggests E2 + b * (1 - E2) ** 4, but this clips, if
6155 # minLum > 0.25, due to a 'dip' in the function. The solution is to
6156 # adjust the exponent according to minLum. For minLum <= 0.25
6157 # (< 5.15 cd/m2), this will give the same result as 'pure' BT.2390-3
6158 # Only for positive b i.e. minLum >= LB if b >= 0,
6159 # otherwise for negative b i.e. minLum < LB
6160 p = min(1.0 / b, 4) if b >= 0 else 4
6161 e3 = e2 + b * (1 - e2) ** p
6162 # If maxLum < 1, and the input value reaches maxLum, the resulting
6163 # output value will be higher than maxLum after applying the black
6164 # level lift (note that this is *not* a side effect of the above
6165 # exponent adjustment). Undo this by re-scaling to the nominal output
6166 # range [minLum, maxLum].
6167 if maxi < 1:
6168 # Only re-scale if maxLum < 1. Note that maxLum can be > 1
6169 # if Lmax > LW despite E2 <= 1
6170 e3 = convert_range(e3, b, maxi + b * (1 - maxi) ** p, b, maxi)
6171 else:
6172 e3 = e2
6173 if bpc:
6174 e3 = convert_range(e3, mini, maxi, 0, maxi)
6175 if normalize and mmini is not None and mmaxi is not None:
6176 # Invert the normalization of the PQ values
6177 e3 = e3 * (mmaxi - mmini) + mmini
6178 return max(e3, 0)
6179
6180
6181 class Matrix3x3(list):
6182 """Simple 3x3 matrix.
6183
6184 Args:
6185 matrix (list tuple, optional): A 3x3 matrix to initialize with.
6186 Defaults to None.
6187 """
6188
6189 def __init__(self, matrix: None | list | tuple = None) -> None:
6190 super().__init__()
6191 self._reset()
6192
6193 # TODO: Matrix should initialize to identity matrix if None or empty.
6194 # if matrix is None or (isinstance(matrix, (list, tuple)) and len(matrix) == 0):
6195 # matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
6196
6197 if matrix:
6198 self.update(matrix)
6199
6200 def update(self, matrix: list | tuple) -> None:
6201 """Update the matrix with a new 3x3 matrix.
6202
6203 Args:
6204 matrix (list | tuple): A 3x3 matrix to update with.
6205
6206 Raises:
6207 ValueError: If the matrix is not 3x3.
6208 ValueError: If the rows or columns of the matrix are not of length 3.
6209 """
6210 if len(matrix) != 3:
6211 raise ValueError(f"Invalid number of rows for 3x3 matrix: {len(matrix)}")
6212 self._reset()
6213 while len(self):
6214 self.pop()
6215 for row in matrix:
6216 if len(row) != 3:
6217 raise ValueError(
6218 f"Invalid number of columns for 3x3 matrix: {len(row)}"
6219 )
6220 self.append([])
6221 for column in row:
6222 self[-1].append(column)
6223
6224 def _reset(self) -> None:
6225 self._inverted = None
6226 self._transposed = None
6227 self._rounded = {}
6228 self._applied = {}
6229
6230 def __add__(self, matrix: list | tuple | Matrix3x3) -> Matrix3x3:
6231 """Matrix addition.
6232
6233 Args:
6234 matrix (Matrix3x3 or list or tuple): The matrix to add.
6235
6236 Returns:
6237 Matrix3x3: The result of the addition.
6238 """
6239 instance = self.__class__()
6240 instance.update(
6241 [
6242 [
6243 self[0][0] + matrix[0][0],
6244 self[0][1] + matrix[0][1],
6245 self[0][2] + matrix[0][2],
6246 ],
6247 [
6248 self[1][0] + matrix[1][0],
6249 self[1][1] + matrix[1][1],
6250 self[1][2] + matrix[1][2],
6251 ],
6252 [
6253 self[2][0] + matrix[2][0],
6254 self[2][1] + matrix[2][1],
6255 self[2][2] + matrix[2][2],
6256 ],
6257 ]
6258 )
6259 return instance
6260
6261 def __iadd__(self, matrix: list | tuple | Matrix3x3) -> Self:
6262 """Matrix addition in place."""
6263 # inplace
6264 self.update(self.__add__(matrix))
6265 return self
6266
6267 @overload
6268 def __imul__(
6269 self, matrix: list[float, float, float]
6270 ) -> list[float, float, float]: ...
6271
6272 @overload
6273 def __imul__(
6274 self, matrix: tuple[float, float, float]
6275 ) -> list[float, float, float]: ...
6276
6277 @overload
6278 def __imul__(self, matrix: Matrix3x3) -> Self: ...
6279
6280 def __imul__(self, matrix) -> Self:
6281 """Matrix multiplication.
6282
6283 Args:
6284 matrix (Matrix3x3 or list or tuple): The matrix to multiply with.
6285 """
6286 # inplace
6287 self.update(self.__mul__(matrix))
6288 return self
6289
6290 @overload
6291 def __mul__(
6292 self, matrix: list[float, float, float]
6293 ) -> list[float, float, float]: ...
6294
6295 @overload
6296 def __mul__(
6297 self, matrix: tuple[float, float, float]
6298 ) -> list[float, float, float]: ...
6299
6300 @overload
6301 def __mul__(self, matrix: Matrix3x3) -> Matrix3x3: ...
6302
6303 def __mul__(self, matrix):
6304 """Matrix multiplication.
6305
6306 Args:
6307 matrix (Matrix3x3 or list or tuple): The matrix to multiply with.
6308 """
6309 if not isinstance(matrix[0], (list, tuple)):
6310 return [
6311 self[0][0] * matrix[0]
6312 + self[0][1] * matrix[1]
6313 + self[0][2] * matrix[2],
6314 self[1][0] * matrix[0]
6315 + self[1][1] * matrix[1]
6316 + self[1][2] * matrix[2],
6317 self[2][0] * matrix[0]
6318 + self[2][1] * matrix[1]
6319 + self[2][2] * matrix[2],
6320 ]
6321 instance = self.__class__()
6322 instance.update(
6323 [
6324 [
6325 self[0][0] * matrix[0][0]
6326 + self[0][1] * matrix[1][0]
6327 + self[0][2] * matrix[2][0],
6328 self[0][0] * matrix[0][1]
6329 + self[0][1] * matrix[1][1]
6330 + self[0][2] * matrix[2][1],
6331 self[0][0] * matrix[0][2]
6332 + self[0][1] * matrix[1][2]
6333 + self[0][2] * matrix[2][2],
6334 ],
6335 [
6336 self[1][0] * matrix[0][0]
6337 + self[1][1] * matrix[1][0]
6338 + self[1][2] * matrix[2][0],
6339 self[1][0] * matrix[0][1]
6340 + self[1][1] * matrix[1][1]
6341 + self[1][2] * matrix[2][1],
6342 self[1][0] * matrix[0][2]
6343 + self[1][1] * matrix[1][2]
6344 + self[1][2] * matrix[2][2],
6345 ],
6346 [
6347 self[2][0] * matrix[0][0]
6348 + self[2][1] * matrix[1][0]
6349 + self[2][2] * matrix[2][0],
6350 self[2][0] * matrix[0][1]
6351 + self[2][1] * matrix[1][1]
6352 + self[2][2] * matrix[2][1],
6353 self[2][0] * matrix[0][2]
6354 + self[2][1] * matrix[1][2]
6355 + self[2][2] * matrix[2][2],
6356 ],
6357 ]
6358 )
6359 return instance
6360
6361 def adjoint(self) -> Matrix3x3:
6362 """Return adjoint matrix.
6363
6364 Returns:
6365 Matrix3x3: Adjoint matrix.
6366 """
6367 return self.cofactors().transposed()
6368
6369 def applied(self, fn: Callable) -> Matrix3x3:
6370 """Apply function to every element, return new matrix.
6371
6372 Args:
6373 fn (callable): Function to apply to each element of the matrix.
6374
6375 Returns:
6376 Matrix3x3: A new Matrix3x3 with the function applied to each element.
6377 """
6378 if fn in self._applied:
6379 return self._applied[fn]
6380 matrix = self.__class__()
6381 for row in self:
6382 matrix.append([])
6383 for column in row:
6384 matrix[-1].append(fn(column))
6385 self._applied[fn] = matrix
6386 return matrix
6387
6388 def cofactors(self) -> Matrix3x3:
6389 """Return cofactor matrix.
6390
6391 Returns:
6392 Matrix3x3: Cofactor matrix.
6393 """
6394 instance = self.__class__()
6395 instance.update(
6396 [
6397 [
6398 (self[1][1] * self[2][2] - self[1][2] * self[2][1]),
6399 -1 * (self[1][0] * self[2][2] - self[1][2] * self[2][0]),
6400 (self[1][0] * self[2][1] - self[1][1] * self[2][0]),
6401 ],
6402 [
6403 -1 * (self[0][1] * self[2][2] - self[0][2] * self[2][1]),
6404 (self[0][0] * self[2][2] - self[0][2] * self[2][0]),
6405 -1 * (self[0][0] * self[2][1] - self[0][1] * self[2][0]),
6406 ],
6407 [
6408 (self[0][1] * self[1][2] - self[0][2] * self[1][1]),
6409 -1 * (self[0][0] * self[1][2] - self[1][0] * self[0][2]),
6410 (self[0][0] * self[1][1] - self[0][1] * self[1][0]),
6411 ],
6412 ]
6413 )
6414 return instance
6415
6416 def determinant(self) -> float:
6417 """Return determinant of the matrix.
6418
6419 Returns:
6420 float: Determinant of the matrix.
6421 """
6422 return (
6423 self[0][0] * self[1][1] * self[2][2]
6424 + self[1][0] * self[2][1] * self[0][2]
6425 + self[0][1] * self[1][2] * self[2][0]
6426 ) - (
6427 self[2][0] * self[1][1] * self[0][2]
6428 + self[1][0] * self[0][1] * self[2][2]
6429 + self[2][1] * self[1][2] * self[0][0]
6430 )
6431
6432 def invert(self) -> None:
6433 """Invert the matrix in place."""
6434 # inplace
6435 self.update(self.inverted())
6436
6437 def inverted(self) -> Matrix3x3:
6438 """Return inverted matrix.
6439
6440 Returns:
6441 Matrix3x3: Inverted matrix.
6442 """
6443 if self._inverted:
6444 return self._inverted
6445 determinant = self.determinant()
6446 matrix = self.adjoint()
6447 instance = self.__class__()
6448 instance.update(
6449 [
6450 [
6451 matrix[0][0] / determinant,
6452 matrix[0][1] / determinant,
6453 matrix[0][2] / determinant,
6454 ],
6455 [
6456 matrix[1][0] / determinant,
6457 matrix[1][1] / determinant,
6458 matrix[1][2] / determinant,
6459 ],
6460 [
6461 matrix[2][0] / determinant,
6462 matrix[2][1] / determinant,
6463 matrix[2][2] / determinant,
6464 ],
6465 ]
6466 )
6467 self._inverted = instance
6468 return instance
6469
6470 def rounded(self, digits: int = 3) -> Matrix3x3:
6471 """Round each element of the matrix to the specified number of digits.
6472
6473 Args:
6474 digits (int): Number of digits to round to. Default is 3.
6475
6476 Returns:
6477 Matrix3x3: A new Matrix3x3 with each element rounded to the
6478 specified number of digits.
6479 """
6480 if digits in self._rounded:
6481 return self._rounded[digits]
6482 matrix = self.__class__()
6483 for row in self:
6484 matrix.append([])
6485 for column in row:
6486 matrix[-1].append(round(column, digits))
6487 self._rounded[digits] = matrix
6488 return matrix
6489
6490 def transpose(self) -> None:
6491 """Transpose the matrix in place."""
6492 self.update(self.transposed())
6493
6494 def transposed(self) -> Matrix3x3:
6495 """Return transposed matrix.
6496
6497 Returns:
6498 Matrix3x3: Transposed matrix.
6499 """
6500 if self._transposed:
6501 return self._transposed
6502 instance = self.__class__()
6503 instance.update(
6504 [
6505 [self[0][0], self[1][0], self[2][0]],
6506 [self[0][1], self[1][1], self[2][1]],
6507 [self[0][2], self[1][2], self[2][2]],
6508 ]
6509 )
6510 self._transposed = instance
6511 return instance
6512
6513 def __hash__(self) -> int:
6514 """Make the Matrix3x3 hashable."""
6515 return hash(
6516 f"{self[0][0]},{self[1][0]},{self[2][0]},"
6517 f"{self[0][1]},{self[1][1]},{self[2][1]},"
6518 f"{self[0][2]},{self[1][2]},{self[2][2]}"
6519 )
6520
6521 def __eq__(self, other: list | tuple | Matrix3x3) -> bool:
6522 """Check if two matrices are equal.
6523
6524 Args:
6525 other (Matrix3x3): The other matrix to compare with.
6526
6527 Returns:
6528 bool: True if the matrices are equal, False otherwise.
6529 """
6530 if not isinstance(other, (list, tuple, Matrix3x3)):
6531 return False
6532 return (
6533 self[0][0] == other[0][0]
6534 and self[0][1] == other[0][1]
6535 and self[0][2] == other[0][2]
6536 and self[1][0] == other[1][0]
6537 and self[1][1] == other[1][1]
6538 and self[1][2] == other[1][2]
6539 and self[2][0] == other[2][0]
6540 and self[2][1] == other[2][1]
6541 and self[2][2] == other[2][2]
6542 )
6543
6544
6545 class NumberTuple(tuple):
6546 """Simple tuple with a few extra methods."""
6547
6548 __slots__ = ()
6549
6550 def __repr__(self) -> str:
6551 """Return a string representation of the tuple.
6552
6553 Returns:
6554 str: String representation of the tuple.
6555 """
6556 return "({})".format(", ".join(str(value) for value in self))
6557
6558 def round(self, digits: int = 4) -> NumberTuple:
6559 """Round each element of the tuple to the specified number of digits.
6560
6561 Args:
6562 digits (int): Number of digits to round to. Default is 4.
6563
6564 Returns:
6565 NumberTuple: A new NumberTuple with each element rounded to the
6566 specified number of digits.
6567 """
6568 return self.__class__(round(value, digits) for value in self)
6569
6570
6571 # Chromatic adaption transform matrices
6572 # Bradford, von Kries (= HPE normalized to D65) from http://brucelindbloom.com/Eqn_ChromAdapt.html
6573 # CAT02 from http://en.wikipedia.org/wiki/CIECAM02#CAT02
6574 # HPE normalized to illuminant E, CAT97s from http://en.wikipedia.org/wiki/LMS_color_space#CAT97s
6575 # CMCCAT2000, Sharp from 'Computational colour science using MATLAB'
6576 # ISBN 0470845627, http://books.google.com/books?isbn=0470845627
6577 # Cross-verification of the matrix numbers has been done using various sources,
6578 # most notably 'Chromatic Adaptation Performance of Different RGB Sensors'
6579 # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.14.918&rep=rep1&type=pdf
6580 CAT_MATRICES = {
6581 "Bradford": Matrix3x3(
6582 [
6583 [0.89510, 0.26640, -0.16140],
6584 [-0.75020, 1.71350, 0.03670],
6585 [0.03890, -0.06850, 1.02960],
6586 ]
6587 ),
6588 "CAT02": Matrix3x3(
6589 [[0.7328, 0.4296, -0.1624], [-0.7036, 1.6975, 0.0061], [0.0030, 0.0136, 0.9834]]
6590 ),
6591 # Brill & Süsstrunk modification also found in ArgyllCMS
6592 "CAT02BS": Matrix3x3(
6593 [[0.7328, 0.4296, -0.1624], [-0.7036, 1.6975, 0.0061], [0.0000, 0.0000, 1.0000]]
6594 ),
6595 "CAT97s": Matrix3x3(
6596 [
6597 [0.8562, 0.3372, -0.1934],
6598 [-0.8360, 1.8327, 0.0033],
6599 [0.0357, -0.0469, 1.0112],
6600 ]
6601 ),
6602 "CMCCAT2000": Matrix3x3(
6603 [[0.7982, 0.3389, -0.1371], [-0.5918, 1.5512, 0.0406], [0.0008, 0.0239, 0.9753]]
6604 ),
6605 # Hunt-Pointer-Estevez, equal-energy illuminant
6606 "HPE E": Matrix3x3(
6607 [
6608 [0.38971, 0.68898, -0.07868],
6609 [-0.22981, 1.18340, 0.04641],
6610 [0.00000, 0.00000, 1.00000],
6611 ]
6612 ),
6613 # Süsstrunk et al.15 optimized spectrally sharpened matrix
6614 "Sharp": Matrix3x3(
6615 [
6616 [1.2694, -0.0988, -0.1706],
6617 [-0.8364, 1.8006, 0.0357],
6618 [0.0297, -0.0315, 1.0018],
6619 ]
6620 ),
6621 # 'Von Kries' as found on Bruce Lindbloom's site:
6622 # Hunt-Pointer-Estevez normalized to D65
6623 # (maybe I should call it that instead of 'Von Kries'
6624 # to avoid ambiguity?)
6625 "HPE D65": Matrix3x3(
6626 [
6627 [0.40024, 0.70760, -0.08081],
6628 [-0.22630, 1.16532, 0.04570],
6629 [0.00000, 0.00000, 0.91822],
6630 ]
6631 ),
6632 "XYZ scaling": Matrix3x3([[1, 0, 0], [0, 1, 0], [0, 0, 1]]),
6633 "IPT": Matrix3x3(
6634 [[0.4002, 0.7075, -0.0807], [-0.2280, 1.1500, 0.0612], [0.0000, 0.0000, 0.9184]]
6635 ),
6636 # Inverse CIE 2012 2deg LMS to XYZ matrix from Argyll/icc/icc.c
6637 "CIE2012_2": Matrix3x3(
6638 [
6639 [0.2052445519046028, 0.8334486497310412, -0.0386932016356441],
6640 [-0.4972221301804286, 1.4034846060306130, 0.0937375241498157],
6641 [0.0000000000000000, 0.0000000000000000, 1.0000000000000000],
6642 ]
6643 ),
6644 # Inverse CIE 2015 2deg LMS to XYZ matrix from Argyll/icc/icc.c
6645 "CIE2015_2": Matrix3x3(
6646 [
6647 [0.2052445519046028, 0.8334486497310412, -0.0386932016356441],
6648 [-0.4972221301804286, 1.4034846060306130, 0.0937375241498157],
6649 [0.0000000000000000, 0.0000000000000000, 1.0000000000000000],
6650 ]
6651 ),
6652 # Bianco and Schettini (2010)
6653 "BS": Matrix3x3(
6654 [
6655 [0.8752, 0.2787, -0.1539],
6656 [-0.8904, 1.8709, 0.0195],
6657 [-0.0061, 0.0162, 0.9899],
6658 ]
6659 ),
6660 # Bianco and Schettini (2010) with positivity constraint
6661 "BS-PC": Matrix3x3(
6662 [
6663 [0.6489, 0.3915, -0.0404],
6664 [-0.3775, 1.3055, 0.0720],
6665 [-0.0271, 0.0888, 0.9383],
6666 ]
6667 ),
6668 }
6669
6670 LMS2IPT_matrix = Matrix3x3(
6671 [[0.4000, 0.4000, 0.2000], [4.4550, -4.8510, 0.3960], [0.8056, 0.3572, -1.1628]]
6672 )
6673 IPT2LMS_matrix = LMS2IPT_matrix.inverted()
6674
6675 LinearRGB2LMS_matrix = Matrix3x3(
6676 [
6677 [1688 / 4096.0, 2146 / 4096.0, 262 / 4096.0],
6678 [683 / 4096.0, 2951 / 4096.0, 462 / 4096.0],
6679 [99 / 4096.0, 309 / 4096.0, 3688 / 4096.0],
6680 ]
6681 )
6682 LMS2LinearRGB_matrix = LinearRGB2LMS_matrix.inverted()
6683 L_M_S_2ICtCp_matrix = Matrix3x3(
6684 [
6685 [0.5, 0.5, 0],
6686 [6610 / 4096.0, -13613 / 4096.0, 7003 / 4096.0],
6687 [17933 / 4096.0, -17390 / 4096.0, -543 / 4096.0],
6688 ]
6689 )
6690 ICtCp2L_M_S__matrix = L_M_S_2ICtCp_matrix.inverted()
6691
6692 # Tweaked LMS to IPT matrix to account for CIE 2012 2deg XYZ to LMS matrix
6693 # From Argyll/icc/icc.c
6694 LMS2Lpt_matrix = Matrix3x3(
6695 [
6696 [0.6585034777870502, 0.1424555300344579, 0.1990409921784920],
6697 [5.6413505933276049, -6.1697985811414187, 0.5284479878138138],
6698 [1.6370552576322106, 0.0192823194340315, -1.6563375770662419],
6699 ]
6700 )
6701 Lpt2LMS_matrix = LMS2Lpt_matrix.inverted()
6702
6703 standard_illuminants = {
6704 # 1st level is the standard name => illuminant definitions
6705 # 2nd level is the illuminant name => CIE XYZ coordinates
6706 # (Y should always assumed to be 1.0 and is not explicitly defined)
6707 None: {"E": {"X": 1.00000, "Z": 1.00000}},
6708 "ASTM E308-01": {
6709 "A": {"X": 1.09850, "Z": 0.35585},
6710 "C": {"X": 0.98074, "Z": 1.18232},
6711 "D50": {"X": 0.96422, "Z": 0.82521},
6712 "D55": {"X": 0.95682, "Z": 0.92149},
6713 "D65": {"X": 0.95047, "Z": 1.08883},
6714 "D75": {"X": 0.94972, "Z": 1.22638},
6715 "F2": {"X": 0.99186, "Z": 0.67393},
6716 "F7": {"X": 0.95041, "Z": 1.08747},
6717 "F11": {"X": 1.00962, "Z": 0.64350},
6718 },
6719 "ICC": {"D50": {"X": 0.9642, "Z": 0.8249}, "D65": {"X": 0.9505, "Z": 1.0890}},
6720 "ISO 11664-2:2007": {
6721 "D65": {"X": xyY2XYZ(0.3127, 0.329)[0], "Z": xyY2XYZ(0.3127, 0.329)[2]}
6722 },
6723 "Wyszecki & Stiles": {
6724 "A": {"X": 1.09828, "Z": 0.35547},
6725 "B": {"X": 0.99072, "Z": 0.85223},
6726 "C": {"X": 0.98041, "Z": 1.18103},
6727 "D55": {"X": 0.95642, "Z": 0.92085},
6728 "D65": {"X": 0.95017, "Z": 1.08813},
6729 "D75": {"X": 0.94939, "Z": 1.22558},
6730 },
6731 }
6732
6733 # CIE 1931 2-deg chromaticity coordinates
6734 # http://www.cvrl.org/offercsvccs.php
6735 cie1931_2_xy = [
6736 (0.175560, 0.005294),
6737 (0.175161, 0.005256),
6738 (0.174821, 0.005221),
6739 (0.174510, 0.005182),
6740 (0.174112, 0.004964),
6741 (0.174008, 0.004981),
6742 (0.173801, 0.004915),
6743 (0.173560, 0.004923),
6744 (0.173337, 0.004797),
6745 (0.173021, 0.004775),
6746 (0.172577, 0.004799),
6747 (0.172087, 0.004833),
6748 (0.171407, 0.005102),
6749 (0.170301, 0.005789),
6750 (0.168878, 0.006900),
6751 (0.166895, 0.008556),
6752 (0.164412, 0.010858),
6753 (0.161105, 0.013793),
6754 (0.156641, 0.017705),
6755 (0.150985, 0.022740),
6756 (0.143960, 0.029703),
6757 (0.135503, 0.039879),
6758 (0.124118, 0.057803),
6759 (0.109594, 0.086843),
6760 (0.091294, 0.132702),
6761 (0.068706, 0.200723),
6762 (0.045391, 0.294976),
6763 (0.023460, 0.412703),
6764 (0.008168, 0.538423),
6765 (0.003859, 0.654823),
6766 (0.013870, 0.750186),
6767 (0.038852, 0.812016),
6768 (0.074302, 0.833803),
6769 (0.114161, 0.826207),
6770 (0.154722, 0.805864),
6771 (0.192876, 0.781629),
6772 (0.229620, 0.754329),
6773 (0.265775, 0.724324),
6774 (0.301604, 0.692308),
6775 (0.337363, 0.658848),
6776 (0.373102, 0.624451),
6777 (0.408736, 0.589607),
6778 (0.444062, 0.554714),
6779 (0.478775, 0.520202),
6780 (0.512486, 0.486591),
6781 (0.544787, 0.454434),
6782 (0.575151, 0.424232),
6783 (0.602933, 0.396497),
6784 (0.627037, 0.372491),
6785 (0.648233, 0.351395),
6786 (0.665764, 0.334011),
6787 (0.680079, 0.319747),
6788 (0.691504, 0.308342),
6789 (0.700606, 0.299301),
6790 (0.707918, 0.292027),
6791 (0.714032, 0.285929),
6792 (0.719033, 0.280935),
6793 (0.723032, 0.276948),
6794 (0.725992, 0.274008),
6795 (0.728272, 0.271728),
6796 (0.729969, 0.270031),
6797 (0.731089, 0.268911),
6798 (0.731993, 0.268007),
6799 (0.732719, 0.267281),
6800 (0.733417, 0.266583),
6801 (0.734047, 0.265953),
6802 (0.734390, 0.265610),
6803 (0.734592, 0.265408),
6804 (0.734690, 0.265310),
6805 (0.734690, 0.265310),
6806 (0.734690, 0.265310),
6807 (0.734548, 0.265452),
6808 (0.734690, 0.265310),
6809 (0.734690, 0.265310),
6810 (0.734690, 0.265310),
6811 (0.734690, 0.265310),
6812 (0.734690, 0.265310),
6813 (0.734690, 0.265310),
6814 (0.734690, 0.265310),
6815 (0.734690, 0.265310),
6816 (0.734690, 0.265310),
6817 (0.734690, 0.265310),
6818 (0.734690, 0.265310),
6819 (0.734690, 0.265310),
6820 (0.734690, 0.265310),
6821 (0.734690, 0.265310),
6822 (0.734690, 0.265310),
6823 (0.734690, 0.265310),
6824 (0.734690, 0.265310),
6825 (0.734690, 0.265310),
6826 (0.734690, 0.265310),
6827 (0.734690, 0.265310),
6828 (0.734690, 0.265310),
6829 (0.734690, 0.265310),
6830 (0.734690, 0.265310),
6831 ]
6832
6833 OPTIMAL_COLORS_LAB = [
6834 (52.40, 95.40, 10.58),
6835 (52.33, 91.23, 38.56),
6836 (52.31, 89.09, 65.80),
6837 (52.30, 88.24, 89.93),
6838 (59.11, 84.13, 101.46),
6839 (66.02, 75.66, 113.09),
6840 (72.36, 64.33, 123.65),
6841 (78.27, 50.88, 132.94),
6842 (83.64, 36.33, 140.63),
6843 (88.22, 22.05, 145.02),
6844 (92.09, 8.49, 143.95),
6845 (90.38, -4.04, 141.05),
6846 (87.54, -23.02, 136.16),
6847 (85.18, -37.06, 132.16),
6848 (82.10, -52.65, 126.97),
6849 (85.53, -65.59, 122.51),
6850 (82.01, -81.46, 116.55),
6851 (77.35, -97.06, 108.72),
6852 (74.76, -122.57, 90.91),
6853 (68.33, -134.27, 80.11),
6854 (63.07, -152.99, 56.41),
6855 (54.57, -159.74, 42.75),
6856 (44.43, -162.58, 27.45),
6857 (46.92, -162.26, 13.87),
6858 (48.53, -144.04, -4.73),
6859 (49.50, -115.82, -25.38),
6860 (59.18, -85.50, -47.00),
6861 (59.33, -68.64, -58.79),
6862 (59.41, -52.73, -69.57),
6863 (50.80, -25.33, -84.08),
6864 (42.05, 8.67, -98.57),
6865 (33.79, 43.74, -111.63),
6866 (26.63, 74.31, -121.90),
6867 (20.61, 98.44, -128.77),
6868 (14.87, 117.34, -131.97),
6869 (9.74, 127.16, -129.59),
6870 (5.20, 125.79, -120.43),
6871 (7.59, 122.01, -116.33),
6872 (10.21, 117.89, -111.81),
6873 (26.35, 115.11, -100.95),
6874 (40.68, 115.59, -87.47),
6875 (39.37, 115.48, -78.51),
6876 (46.49, 114.84, -66.24),
6877 (53.49, 111.63, -54.17),
6878 (52.93, 107.54, -38.16),
6879 (52.58, 101.53, -16.45),
6880 (52.40, 95.40, 10.58),
6881 ]
6882
6883
6884 def debug_caches() -> None:
6885 """Debug caches for duplicate entries."""
6886 for cache_name in (
6887 "XYZ2RGB.interp",
6888 "wp_adaption_matrix.cache",
6889 "get_rgb_space.cache",
6890 "get_standard_illuminant.cache",
6891 "get_whitepoint.cache",
6892 ):
6893 cn, ck = cache_name.split(".")
6894 c = getattr(globals()[cn], ck)
6895 count = 0
6896 seen = {}
6897 for k in c:
6898 v = c[k]
6899 for kk in c:
6900 vv = c[kk]
6901 # Check for equality, not identity
6902 if k != kk and v == vv and kk not in seen:
6903 count += 1
6904 seen[kk] = True
6905 print(cache_name, len(c), "entries", max(count - 1, 0), "duplicates")
6906 if count > 1:
6907 for k in c:
6908 v = c[k]
6909 print(k, v)
6910
6911
6912 if "--debug-caches" in sys.argv[1:]:
6913 import atexit
6914
6915 atexit.register(debug_caches)