Debian Codegraph @

DisplayCAL/icc_profile.py

raw
1 """ICC profile utilities for color management across devices.
2
3 ICC profiles describe device or color space color characteristics for
4 consistent color reproduction. This module provides, utilities for parsing,
5 validating, and manipulating ICC profile data.
6 """
7
8 from __future__ import annotations
9
10 import binascii
11 import contextlib
12 import ctypes
13 import datetime
14 import functools
15 import json
16 import math
17 import operator
18 import os
19 import pathlib
20 import platform
21 import re
22 import struct
23 import subprocess as sp
24 import sys
25 import warnings
26 from collections import UserString
27 from copy import copy
28 from hashlib import md5
29 from typing import (
30 TYPE_CHECKING,
31 Any,
32 BinaryIO,
33 Callable,
34 ClassVar,
35 SupportsIndex,
36 TextIO,
37 )
38 from weakref import WeakValueDictionary
39
40 from DisplayCAL.util_dict import dict_sort
41
42
43 if sys.platform == "win32":
44 import winreg
45
46 import pywintypes
47
48 try:
49 import win32api
50 import win32gui
51 except ImportError:
52 pass
53
54 try:
55 from DisplayCAL import colord
56 except ImportError:
57
58 class Colord:
59 """Dummy class for colord support."""
60
61 Colord = None
62
63 def quirk_manufacturer(self, manufacturer: str) -> str:
64 """Quirk the manufacturer name.
65
66 Args:
67 manufacturer (str): The manufacturer name to quirk.
68
69 Returns:
70 str: The quirked manufacturer name.
71 """
72 return manufacturer
73
74 def which(self, executable: str, paths: None | list[str] = None) -> None | str:
75 """Check if an executable is available in the system paths.
76
77 Args:
78 executable (str): The name of the executable to check.
79 paths (None | list[str], optional): List of paths to search for
80 the executable. If None, uses the system PATH.
81
82 Returns:
83 None | str: The full path to the executable if found, else None.
84 """
85 return
86
87 colord = Colord()
88 from DisplayCAL import colormath, edid, imfile
89 from DisplayCAL.defaultpaths import ICCPROFILES, ICCPROFILES_HOME
90 from DisplayCAL.encoding import get_encodings
91 from DisplayCAL.options import TEST_INPUT_CURVE_CLIPPING
92 from DisplayCAL.util_list import intlist
93
94 if sys.platform not in ("darwin", "win32"):
95 from DisplayCAL.defaultpaths import XDG_CONFIG_DIRS, XDG_CONFIG_HOME
96 from DisplayCAL.edid import get_edid
97 from DisplayCAL.util_x import get_display
98
99 try:
100 from DisplayCAL import xrandr
101 except ImportError:
102 xrandr = None
103 from DisplayCAL.util_os import dlopen, which
104 elif sys.platform == "win32":
105 from DisplayCAL import util_win
106 from DisplayCAL.mscms import WCSManagerProxy
107
108 if sys.getwindowsversion() < (6,):
109 # WCS only available under Vista and later
110 mscms = None
111 else:
112 mscms = WCSManagerProxy()
113
114
115 if TYPE_CHECKING:
116 import multiprocessing
117 import threading
118 from collections.abc import Iterable, Iterator
119 from typing import BinaryIO, TextIO
120
121 from DisplayCAL.worker import Worker, Xicclu # noqa: TC004
122
123 if sys.version_info >= (3, 11):
124 from typing import Self
125 else:
126 from typing_extensions import Self
127
128
129 # Gamut volumes in cubic colorspace units (L*a*b*) as reported by Argyll's
130 # iccgamut
131 GAMUT_VOLUME_SRGB = 833675.435316 # rel. col.
132 GAMUT_VOLUME_ADOBERGB = 1209986.014983 # rel. col.%
133 GAMUT_VOLUME_SMPTE431_P3 = 1176953.485921 # rel. col.
134
135 # http://msdn.microsoft.com/en-us/library/dd371953%28v=vs.85%29.aspx
136 COLOR_PROFILE_SUBTYPE = {
137 "NONE": 0x0000,
138 "RGB_WORKING_SPACE": 0x0001,
139 "PERCEPTUAL": 0x0002,
140 "ABSOLUTE_COLORIMETRIC": 0x0004,
141 "RELATIVE_COLORIMETRIC": 0x0008,
142 "SATURATION": 0x0010,
143 "CUSTOM_WORKING_SPACE": 0x0020,
144 }
145
146 # http://msdn.microsoft.com/en-us/library/dd371955%28v=vs.85%29.aspx (wrong)
147 # http://msdn.microsoft.com/en-us/library/windows/hardware/ff546018%28v=vs.85%29.aspx (ok) # noqa: E501
148 COLOR_PROFILE_TYPE = {"ICC": 0, "DMP": 1, "CAMP": 2, "GMMP": 3}
149
150 WCS_PROFILE_MANAGEMENT_SCOPE = {"SYSTEM_WIDE": 0, "CURRENT_USER": 1}
151
152 ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015
153 ERROR_SUCCESS = 0
154
155 DEBUG = False
156
157 ENC, FS_ENC = get_encodings()
158
159 CMMS = {
160 b"argl": "ArgyllCMS",
161 b"ADBE": "Adobe",
162 b"ACMS": "Agfa",
163 b"Agfa": "Agfa",
164 b"APPL": "Apple",
165 b"appl": "Apple",
166 b"CCMS": "ColorGear",
167 b"UCCM": "ColorGear Lite",
168 b"DL&C": "Digital Light & Color",
169 b"EFI ": "EFI",
170 b"FF ": "Fuji Film",
171 b"HCMM": "Harlequin RIP",
172 b"LgoS": "LogoSync",
173 b"HDM ": "Heidelberg",
174 b"Lino": "Linotype",
175 b"lino": "Linotype",
176 b"lcms": "Little CMS",
177 b"KCMS": "Kodak",
178 b"MCML": "Konica Minolta",
179 b"MSFT": "Microsoft",
180 b"SIGN": "Mutoh",
181 b"RGMS": "DeviceLink",
182 b"SICC": "SampleICC",
183 b"32BT": "the imaging factory",
184 b"WTG ": "Ware to Go",
185 b"zc00": "Zoran",
186 }
187
188 ENCODINGS = {
189 "mac": {
190 141: "africaans",
191 36: "albanian",
192 85: "amharic",
193 12: "arabic",
194 51: "armenian",
195 68: "assamese",
196 134: "aymara",
197 49: "azerbaijani-cyrllic",
198 50: "azerbaijani-arabic",
199 129: "basque",
200 67: "bengali",
201 137: "dzongkha",
202 142: "breton",
203 44: "bulgarian",
204 77: "burmese",
205 46: "byelorussian",
206 78: "khmer",
207 130: "catalan",
208 92: "chewa",
209 33: "simpchinese",
210 19: "tradchinese",
211 18: "croatian",
212 38: "czech",
213 7: "danish",
214 4: "dutch",
215 0: "roman",
216 94: "esperanto",
217 27: "estonian",
218 30: "faeroese",
219 31: "farsi",
220 13: "finnish",
221 34: "flemish",
222 1: "french",
223 140: "galician",
224 144: "scottishgaelic",
225 145: "manxgaelic",
226 52: "georgian",
227 2: "german",
228 14: "greek-monotonic",
229 148: "greek-polytonic",
230 133: "guarani",
231 69: "gujarati",
232 10: "hebrew",
233 21: "hindi",
234 26: "hungarian",
235 15: "icelandic",
236 81: "indonesian",
237 143: "inuktitut",
238 35: "irishgaelic",
239 146: "irishgaelic-dotsabove",
240 3: "italian",
241 11: "japanese",
242 138: "javaneserom",
243 73: "kannada",
244 61: "kashmiri",
245 48: "kazakh",
246 90: "kiryarwanda",
247 54: "kirghiz",
248 91: "rundi",
249 23: "korean",
250 60: "kurdish",
251 79: "lao",
252 131: "latin",
253 28: "latvian",
254 24: "lithuanian",
255 43: "macedonian",
256 93: "malagasy",
257 83: "malayroman-latin",
258 84: "malayroman-arabic",
259 72: "malayalam",
260 16: "maltese",
261 66: "marathi",
262 53: "moldavian",
263 57: "mongolian",
264 58: "mongolian-cyrillic",
265 64: "nepali",
266 9: "norwegian",
267 71: "oriya",
268 87: "oromo",
269 59: "pashto",
270 25: "polish",
271 8: "portuguese",
272 70: "punjabi",
273 132: "quechua",
274 37: "romanian",
275 32: "russian",
276 29: "sami",
277 65: "sanskrit",
278 42: "serbian",
279 62: "sindhi",
280 76: "sinhalese",
281 39: "slovak",
282 40: "slovenian",
283 88: "somali",
284 6: "spanish",
285 139: "sundaneserom",
286 89: "swahili",
287 5: "swedish",
288 82: "tagalog",
289 55: "tajiki",
290 74: "tamil",
291 135: "tatar",
292 75: "telugu",
293 22: "thai",
294 63: "tibetan",
295 86: "tigrinya",
296 147: "tongan",
297 17: "turkish",
298 56: "turkmen",
299 136: "uighur",
300 45: "ukrainian",
301 20: "urdu",
302 47: "uzbek",
303 80: "vietnamese",
304 128: "welsh",
305 41: "yiddish",
306 }
307 }
308
309 COLORANTS = {
310 0: {"description": "unknown", "channels": ()},
311 1: {
312 "description": "ITU-R BT.709",
313 "channels": ((0.64, 0.33), (0.3, 0.6), (0.15, 0.06)),
314 },
315 2: {
316 "description": "SMPTE RP145-1994",
317 "channels": ((0.63, 0.34), (0.31, 0.595), (0.155, 0.07)),
318 },
319 3: {
320 "description": "EBU Tech.3213-E",
321 "channels": ((0.64, 0.33), (0.29, 0.6), (0.15, 0.06)),
322 },
323 4: {
324 "description": "P22",
325 "channels": ((0.625, 0.34), (0.28, 0.605), (0.155, 0.07)),
326 },
327 }
328
329 GEOMETRY = {0: "unknown", 1: "0/45 or 45/0", 2: "0/d or d/0"}
330
331 ILLUMINANTS = {
332 0: "unknown",
333 1: "D50",
334 2: "D65",
335 3: "D93",
336 4: "F2",
337 5: "D55",
338 6: "A",
339 7: "E",
340 8: "F8",
341 }
342
343 OBSERVERS = {0: "unknown", 1: "CIE 1931", 2: "CIE 1964"}
344
345 MANUFACTURERS = {
346 b"ADBE": "Adobe Systems Incorporated",
347 b"APPL": "Apple Computer, Inc.",
348 b"agfa": "Agfa Graphics N.V.",
349 b"argl": "ArgyllCMS", # Not registered
350 b"DCAL": "DisplayCAL", # Not registered
351 b"bICC": "basICColor GmbH",
352 b"DL&C": "Digital Light & Color",
353 b"EPSO": "Seiko Epson Corporation",
354 b"HDM ": "Heidelberger Druckmaschinen AG",
355 b"HP ": "Hewlett-Packard",
356 b"KODA": "Kodak",
357 b"lcms": "Little CMS",
358 b"MONS": "Monaco Systems Inc.",
359 b"MSFT": "Microsoft Corporation",
360 b"qato": "QUATOGRAPHIC Technology GmbH",
361 b"XRIT": "X-Rite",
362 }
363
364 PLATFORM = {
365 b"APPL": "Apple",
366 b"MSFT": "Microsoft",
367 b"SGI ": "Silicon Graphics",
368 b"SUNW": "Sun Microsystems",
369 }
370
371 PROFILE_CLASS = {
372 b"scnr": "Input device profile",
373 b"mntr": "Display device profile",
374 b"prtr": "Output device profile",
375 b"link": "DeviceLink profile",
376 b"spac": "Color space Conversion profile",
377 b"abst": "Abstract profile",
378 b"nmcl": "Named color profile",
379 }
380
381 TAGS = {
382 "A2B0": "Device to PCS: Intent 0",
383 "A2B1": "Device to PCS: Intent 1",
384 "A2B2": "Device to PCS: Intent 2",
385 "B2A0": "PCS to device: Intent 0",
386 "B2A1": "PCS to device: Intent 1",
387 "B2A2": "PCS to device: Intent 2",
388 "CIED": "Characterization measurement values", # Non-standard
389 "DevD": "Characterization device values", # Non-standard
390 "arts": "Absolute to media relative transform", # Non-standard (Argyll)
391 "bkpt": "Media black point",
392 "bTRC": "Blue tone response curve",
393 "bXYZ": "Blue matrix column",
394 "chad": "Chromatic adaptation transform",
395 "ciis": "Colorimetric intent image state",
396 "clro": "Colorant order",
397 "cprt": "Copyright",
398 "desc": "Description",
399 "dmnd": "Device manufacturer name",
400 "dmdd": "Device model name",
401 "gamt": "Out of gamut tag",
402 "gTRC": "Green tone response curve",
403 "gXYZ": "Green matrix column",
404 "kTRC": "Gray tone response curve",
405 "lumi": "Luminance",
406 "meas": "Measurement type",
407 "mmod": "Make and model",
408 "ncl2": "Named colors",
409 "pseq": "Profile sequence description",
410 "rTRC": "Red tone response curve",
411 "rXYZ": "Red matrix column",
412 "targ": "Characterization target",
413 "tech": "Technology",
414 "vcgt": "Video card gamma table",
415 "view": "Viewing conditions",
416 "vued": "Viewing conditions description",
417 "wtpt": "Media white point",
418 }
419
420 TECH = {
421 "fscn": "Film scanner",
422 "dcam": "Digital camera",
423 "rscn": "Reflective scanner",
424 "ijet": "Ink jet printer",
425 "twax": "Thermal wax printer",
426 "epho": "Electrophotographic printer",
427 "esta": "Electrostatic printer",
428 "dsub": "Dye sublimation printer",
429 "rpho": "Photographic paper printer",
430 "fprn": "Film writer",
431 "vidm": "Video monitor",
432 "vidc": "Video camera",
433 "pjtv": "Projection television",
434 "CRT ": "Cathode ray tube display",
435 "PMD ": "Passive matrix display",
436 "AMD ": "Active matrix display",
437 "KPCD": "Photo CD",
438 "imgs": "Photographic image setter",
439 "grav": "Gravure",
440 "offs": "Offset lithography",
441 "silk": "Silkscreen",
442 "flex": "Flexography",
443 "mpfs": "Motion picture film scanner",
444 "mpfr": "Motion picture film recorder",
445 "dmpc": "Digital motion picture camera",
446 "dcpj": "Digital cinema projector",
447 }
448
449 CIIS = {
450 "scoe": "Scene colorimetry estimates",
451 "sape": "Scene appearance estimates",
452 "fpce": "Focal plane colorimetry estimates",
453 "rhoc": "Reflection hardcopy original colorimetry",
454 "rpoc": "Reflection print output colorimetry",
455 }
456
457
458 def legacy_PCSLab_dec_to_uInt16(L: float, a: float, b: float) -> list[int]: # noqa: N802, N803
459 """Convert ICCv2 (legacy) PCS L*a*b* float values to int.
460
461 Only used by LUT16Type and namedColor2Type in ICCv4.
462
463 Args:
464 L (float): L* value in float format.
465 a (float): a* value in float format.
466 b (float): b* value in float format.
467
468 Returns:
469 list[int]: List of int values representing L*, a*, and b* in 16-bit.
470 """
471 return [
472 v * (652.80, 256, 256)[i] + (0, 32768, 32768)[i]
473 for i, v in enumerate((L, a, b))
474 ]
475
476
477 def legacy_PCSLab_uInt16_to_dec( # noqa: N802
478 L_uInt16: int, # noqa: N803
479 a_uInt16: int, # noqa: N803
480 b_uInt16: int, # noqa: N803
481 ) -> list[float]:
482 """Convert ICCv2 (legacy) PCS L*a*b* to float values.
483
484 Args:
485 L_uInt16 (int): L* value in 16-bit unsigned integer format.
486 a_uInt16 (int): a* value in 16-bit unsigned integer format.
487 b_uInt16 (int): b* value in 16-bit unsigned integer format.
488
489 Returns:
490 list: List of float values representing L*, a*, and b*.
491 """
492 # ICCv2 (legacy) PCS L*a*b* encoding
493 # Only used by LUT16Type and namedColor2Type in ICCv4
494 return [
495 (v - (0, 32768, 32768)[i]) / (65280.0, 32768.0, 32768.0)[i] * (100, 128, 128)[i]
496 for i, v in enumerate((L_uInt16, a_uInt16, b_uInt16))
497 ]
498
499
500 def create_RGB_A2B_XYZ( # noqa: N802
501 input_curves: list, clut: list, logfn: Callable = print
502 ) -> LUT16Type:
503 """Create RGB device A2B from input curve XYZ values and cLUT.
504
505 Note that input curves and cLUT should already be adapted to D50.
506
507 Args:
508 input_curves (list): List of input curves for R, G, B channels.
509 clut (list): cLUT data as a list of lists, where each inner list
510 contains XYZ values for each grid point.
511 logfn (Callable, optional): Function to log messages. Defaults to
512 `print`.
513
514 Returns:
515 LUT16Type: An instance of LUT16Type representing the A2B table.
516 """
517 if len(input_curves) != 3:
518 raise ValueError(f"Wrong number of input curves: {len(input_curves)}")
519
520 white_XYZ = clut[-1][-1] # noqa: N806
521 clutres = len(clut[0])
522 itable = LUT16Type(None, "A2B0")
523 itable.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
524
525 # Input curve interpolation
526 # Normlly the input curves would either be linear (= 1:1 mapping to
527 # cLUT) or the respective tone response curve.
528 # We use a overall linear curve that is 'bent' in <clutres> intervals
529 # to accomodate the non-linear TRC. Thus, we can get away with much
530 # fewer cLUT grid points.
531
532 # Use higher interpolation size than actual number of curve entries
533 steps = 2**15 + 1
534 maxv = steps - 1.0
535
536 fwd = []
537 bwd = []
538 for input_curve in input_curves:
539 if isinstance(input_curve, (tuple, list)):
540 linear = [v / (len(input_curve) - 1.0) for v in range(len(input_curve))]
541 fwd.append(colormath.Interp(linear, input_curve, use_numpy=True))
542 bwd.append(colormath.Interp(input_curve, linear, use_numpy=True))
543 else:
544 # Gamma
545 fwd.append(lambda v, p=input_curve: colormath.special_pow(v, p))
546 bwd.append(lambda v, p=input_curve: colormath.special_pow(v, 1.0 / p))
547 itable.input.append([])
548 itable.output.append([0, 65535])
549
550 logfn("cLUT input curve segments:", clutres)
551 for i in range(3):
552 maxi = bwd[i](white_XYZ[1])
553 segment = 1.0 / (clutres - 1.0) * maxi
554 iv = 0.0
555 prevpow = fwd[i](0.0)
556 nextpow = fwd[i](segment)
557 prevv = 0
558 pprevpow = 0
559 clipped = nextpow <= prevpow
560 xp = []
561 for j in range(steps):
562 v = (j / maxv) * maxi
563 if v > iv + segment:
564 iv += segment
565 prevpow = nextpow
566 nextpow = fwd[i](iv + segment)
567 clipped = nextpow <= prevpow
568 logfn(
569 "#{:d} {}".format(int(iv * (clutres - 1)), "XYZ"[i]),
570 f"prev {prevpow:.6f}",
571 f"next {nextpow:.6f}",
572 "clip",
573 clipped,
574 )
575 if not clipped:
576 prevs = 1.0 - (v - iv) / segment
577 nexts = (v - iv) / segment
578 vv = prevs * prevpow + nexts * nextpow
579 prevv = v
580 pprevpow = prevpow
581 else:
582 # Linearly interpolate
583 vv = colormath.convert_range(v, prevv, 1, prevpow, 1)
584 out = bwd[i](vv)
585 xp.append(out)
586 # Fill input curves from interpolated values
587 interp = colormath.Interp(xp, list(range(steps)), use_numpy=True)
588 entries = 2049
589 threshold = bwd[i](pprevpow)
590 k = None
591 for j in range(entries):
592 n = j / (entries - 1.0)
593 v = interp(n) / maxv
594 if clipped and n + (1 / (entries - 1.0)) > threshold:
595 # Linear interpolate shaper for last n cLUT steps to prevent
596 # clipping in shaper
597 if k is None:
598 k = j
599 ov = v
600 v = min(ov + (1.0 - ov) * ((j - k) / (entries - k - 1.0)), 1.0)
601 # Slope limit for 16-bit encoding
602 itable.input[i].append(max(v, j / 65535.0) * 65535)
603
604 # Fill cLUT
605 clut = list(clut)
606 itable.clut = []
607 # step = 1.0 / (clutres - 1.0)
608 for _R in range(clutres): # noqa: N806
609 for _G in range(clutres): # noqa: N806
610 row = list(clut.pop(0))
611 itable.clut.append([])
612 for _B in range(clutres): # noqa: N806
613 X, Y, Z = row.pop(0) # noqa: N806
614 itable.clut[-1].append(
615 [max(v / white_XYZ[1] * 32768, 0) for v in (X, Y, Z)]
616 )
617
618 return itable
619
620
621 def create_synthetic_clut_profile(
622 rgb_space: None | str | list | tuple,
623 description: str,
624 XYZbp: None | tuple = None, # noqa: N803
625 white_Y: float = 1.0, # noqa: N803
626 clutres: int = 9,
627 entries: int = 2049,
628 cat: str = "Bradford",
629 ) -> ICCProfile:
630 """Create a synthetic cLUT profile from a colorspace definition.
631
632 Args:
633 rgb_space (None | str | list | tuple): The RGB space to use for
634 conversion. Defaults to sRGB if not set. If a string is given, it
635 must be a valid RGB space name. If a list or tuple is given, it
636 must be in the format (gamma, whitepoint, red, green, blue). The
637 whitepoint can be a string (e.g. "D50"), a tuple of XYZ
638 coordinates, or a color temperature in degrees K (float or int).
639 The gamma should be a float. The RGB primaries red, green, blue
640 should be lists or tuples of xyY coordinates (only x and y will be
641 used, so Y can be zero or None).
642 description (str): A description for the profile.
643 XYZbp (None | tuple, optional): A tuple with the black point in XYZ
644 format. If None, it will be derived from the RGB space.
645 white_Y (float, optional): The Y value of the white point, default is
646 1.0.
647 clutres (int, optional): The number of grid points in the cLUT, default
648 is 9.
649 entries (int, optional): The number of entries in the input curves,
650 default is 2049.
651 cat (str, optional): Chromatic adaptation transform, default is
652 "Bradford".
653
654 Returns:
655 ICCProfile: An instance of ICCProfile with the synthetic cLUT profile.
656 """
657 profile = ICCProfile()
658 profile.version = 2.2 # Match ArgyllCMS
659
660 profile.tags.desc = TextDescriptionType(b"", "desc")
661 profile.tags.desc.ASCII = description
662 profile.tags.cprt = TextType(b"text\0\0\0\0Public domain\0", "cprt")
663
664 profile.tags.wtpt = XYZType(profile=profile)
665 (
666 profile.tags.wtpt.X,
667 profile.tags.wtpt.Y,
668 profile.tags.wtpt.Z,
669 ) = colormath.get_whitepoint(rgb_space[1])
670
671 profile.tags.arts = ChromaticAdaptionTag()
672 profile.tags.arts.update(colormath.get_cat_matrix(cat))
673
674 itable = profile.tags.A2B0 = LUT16Type(None, "A2B0", profile)
675 itable.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
676
677 otable = profile.tags.B2A0 = LUT16Type(None, "B2A0", profile)
678 Xr, Yr, Zr = colormath.adapt( # noqa: N806
679 *colormath.RGB2XYZ(1, 0, 0, rgb_space=rgb_space),
680 whitepoint_source=rgb_space[1],
681 cat=cat,
682 )
683 Xg, Yg, Zg = colormath.adapt( # noqa: N806
684 *colormath.RGB2XYZ(0, 1, 0, rgb_space=rgb_space),
685 whitepoint_source=rgb_space[1],
686 cat=cat,
687 )
688 Xb, Yb, Zb = colormath.adapt( # noqa: N806
689 *colormath.RGB2XYZ(0, 0, 1, rgb_space=rgb_space),
690 whitepoint_source=rgb_space[1],
691 cat=cat,
692 )
693 m1 = colormath.Matrix3x3(((Xr, Xg, Xb), (Yr, Yg, Yb), (Zr, Zg, Zb))).inverted()
694 scale = 1 + (32767 / 32768.0)
695 m3 = colormath.Matrix3x3(((scale, 0, 0), (0, scale, 0), (0, 0, scale)))
696 otable.matrix = m1 * m3
697
698 # Input curve interpolation
699 # Normlly the input curves would either be linear (= 1:1 mapping to
700 # cLUT) or the respective tone response curve.
701 # We use a overall linear curve that is 'bent' in <clutres> intervals
702 # to accomodate the non-linear TRC. Thus, we can get away with much
703 # fewer cLUT grid points.
704
705 # Use higher interpolation size than actual number of curve entries
706 steps = 2**15 + 1
707 maxv = steps - 1.0
708 gammas = rgb_space[0]
709 if not isinstance(gammas, (list, tuple)):
710 gammas = [gammas]
711 for i, gamma in enumerate(gammas):
712 maxi = colormath.special_pow(white_Y, 1.0 / gamma)
713 segment = 1.0 / (clutres - 1.0) * maxi
714 iv = 0.0
715 prevpow = 0.0
716 nextpow = colormath.special_pow(segment, gamma)
717 xp = []
718 for j in range(steps):
719 v = (j / maxv) * maxi
720 if v > iv + segment:
721 iv += segment
722 prevpow = nextpow
723 nextpow = colormath.special_pow(iv + segment, gamma)
724 prevs = 1.0 - (v - iv) / segment
725 nexts = (v - iv) / segment
726 vv = prevs * prevpow + nexts * nextpow
727 out = colormath.special_pow(vv, 1.0 / gamma)
728 xp.append(out)
729 interp = colormath.Interp(xp, list(range(steps)), use_numpy=True)
730
731 # Create input curves
732 itable.input.append([])
733 otable.input.append([])
734 for j in range(4096):
735 otable.input[i].append(
736 colormath.special_pow(j / 4095.0 * white_Y, 1.0 / gamma) * 65535
737 )
738
739 # Fill input curves from interpolated values
740 for j in range(entries):
741 v = j / (entries - 1.0)
742 itable.input[i].append(interp(v) / maxv * 65535)
743
744 # Fill remaining input curves from first input curve and create output curves
745 for _ in range(3):
746 if len(itable.input) < 3:
747 itable.input.append(itable.input[0])
748 otable.input.append(otable.input[0])
749 itable.output.append([0, 65535])
750 otable.output.append([0, 65535])
751
752 # Create and fill cLUT
753 itable.clut = []
754 step = 1.0 / (clutres - 1.0)
755 for R in range(clutres): # noqa: N806
756 for G in range(clutres): # noqa: N806
757 itable.clut.append([])
758 for B in range(clutres): # noqa: N806
759 X, Y, Z = colormath.adapt( # noqa: N806
760 *colormath.RGB2XYZ(
761 *[v * step * maxi for v in (R, G, B)], rgb_space=rgb_space
762 ),
763 whitepoint_source=rgb_space[1],
764 cat=cat,
765 )
766 X, Y, Z = colormath.blend_blackpoint(X, Y, Z, None, XYZbp) # noqa: N806
767 itable.clut[-1].append([max(v / white_Y * 32768, 0) for v in (X, Y, Z)])
768
769 otable.clut = []
770 for R in range(2): # noqa: N806
771 for G in range(2): # noqa: N806
772 otable.clut.append([])
773 for B in range(2): # noqa: N806
774 otable.clut[-1].append([v * 65535 for v in (R, G, B)])
775
776 return profile
777
778
779 def create_synthetic_smpte2084_clut_profile(
780 rgb_space: None | str | list | tuple,
781 description: str,
782 black_cdm2: float = 0,
783 white_cdm2: float = 400,
784 master_black_cdm2: float = 0,
785 master_white_cdm2: float = 10000,
786 use_alternate_master_white_clip: bool = True,
787 content_rgb_space: str = "DCI P3",
788 rolloff: bool = True,
789 clutres: int = 33,
790 mode: str = "HSV_ICtCp",
791 sat: float = 1.0,
792 hue: float = 0.5,
793 forward_xicclu: None | Xicclu = None,
794 backward_xicclu: None | Xicclu = None,
795 generate_B2A: bool = False, # noqa: N803
796 worker: None | Worker = None,
797 logfile: None | TextIO = None,
798 cat: str = "Bradford",
799 ) -> ICCProfile:
800 """Create a synthetic cLUT profile with SMPTE 2084 TRC from a colorspace definition.
801
802 The roll-off saturation and hue preservation can be controlled with the
803 `hue` and `sat` arguments.
804
805 Args:
806 rgb_space (None | str | list | tuple): The RGB space to use for
807 conversion. Defaults to sRGB if not set. If a string is given, it
808 must be a valid RGB space name. If a list or tuple is given, it
809 must be in the format (gamma, whitepoint, red, green, blue). The
810 whitepoint can be a string (e.g. "D50"), a tuple of XYZ
811 coordinates, or a color temperature in degrees K (float or int).
812 The gamma should be a float. The RGB primaries red, green, blue
813 should be lists or tuples of xyY coordinates (only x and y will be
814 used, so Y can be zero or None).
815 description (str): Description of the profile.
816 black_cdm2 (float): Black level in cd/m^2.
817 white_cdm2 (float): White level in cd/m^2.
818 master_black_cdm2 (float): Mastering display black level in cd/m^2.
819 master_white_cdm2 (float): Mastering display white level in cd/m^2.
820 use_alternate_master_white_clip (bool): Use alternate master white clip
821 for PQ.
822 content_rgb_space (str): RGB space for content, e.g. "DCI P3".
823 rolloff (bool): Whether to apply roll-off. If False, raises NotImplementedError.
824 clutres (int): Resolution of the cLUT.
825 mode (str): Gamut mapping mode for roll-off. The gamut mapping mode
826 when rolling off. Valid values:
827 "HSV_ICtCp" (default, recommended)
828 "ICtCp"
829 "XYZ" (not recommended, unpleasing hue shift)
830 "HSV" (not recommended, saturation loss)
831 "RGB" (not recommended, saturation loss, pleasing hue shift)
832 sat (float): Saturation preservation factor [0.0, 1.0]:
833 0.0 = Favor luminance preservation over saturation
834 1.0 = Favor saturation preservation over luminance
835 hue (float): Selective hue preservation factor [0.0, 1.0]:
836 0.0 = Allow hue shift for redorange/orange/yellowgreen towards
837 yellow to preserve more saturation and detail
838 1.0 = Preserve hue
839 forward_xicclu (callable): Forward XICCLU function, not used for HLG.
840 backward_xicclu (callable): Backward XICCLU function, not used for HLG.
841 generate_B2A (bool): Generate B2A table, not used for HLG.
842 worker (callable): Worker function for parallel processing, not used here.
843 logfile (file): Log file for output, can be None.
844 cat (str): Chromatic adaptation transform, default is "Bradford".
845
846 Returns:
847 ICCProfile: A synthetic cLUT profile with SMPTE 2084 TRC.
848 """
849 if not rolloff:
850 raise NotImplementedError("rolloff needs to be True")
851
852 return create_synthetic_hdr_clut_profile(
853 "PQ",
854 rgb_space,
855 description,
856 black_cdm2,
857 white_cdm2,
858 master_black_cdm2,
859 master_white_cdm2,
860 use_alternate_master_white_clip,
861 1.2, # Not used for PQ
862 5.0, # Not used for PQ
863 1.0, # Not used for PQ
864 content_rgb_space,
865 clutres,
866 mode,
867 sat,
868 hue,
869 forward_xicclu,
870 backward_xicclu,
871 generate_B2A,
872 worker,
873 logfile,
874 cat,
875 )
876
877
878 def create_synthetic_hdr_clut_profile(
879 hdr_format: str,
880 rgb_space: None | str | list | tuple,
881 description: str,
882 black_cdm2: float = 0,
883 white_cdm2: float = 400,
884 master_black_cdm2: float = 0, # Not used for HLG
885 master_white_cdm2: float = 10000, # Not used for HLG
886 use_alternate_master_white_clip: bool = True, # Not used for HLG
887 system_gamma: float = 1.2, # Not used for PQ
888 ambient_cdm2: float = 5, # Not used for PQ
889 maxsignal: float = 1.0, # Not used for PQ
890 content_rgb_space: str = "DCI P3",
891 clutres: int = 33,
892 mode: str = "HSV_ICtCp", # Not used for HLG
893 sat: float = 1.0, # Not used for HLG
894 hue: float = 0.5, # Not used for HLG
895 forward_xicclu: None | Xicclu = None,
896 backward_xicclu: None | Xicclu = None,
897 generate_B2A: bool = False, # noqa: N803
898 worker: None | Worker = None,
899 logfile: None | TextIO = None,
900 cat: str = "Bradford",
901 ) -> ICCProfile:
902 """Create a synthetic HDR cLUT profile from a colorspace definition.
903
904 Args:
905 hdr_format (str): HDR format, either "PQ" or "HLG".
906 rgb_space (None | str | list | tuple): The RGB space to use for
907 conversion. Defaults to sRGB if not set. If a string is given, it
908 must be a valid RGB space name. If a list or tuple is given, it
909 must be in the format (gamma, whitepoint, red, green, blue). The
910 whitepoint can be a string (e.g. "D50"), a tuple of XYZ
911 coordinates, or a color temperature in degrees K (float or int).
912 The gamma should be a float. The RGB primaries red, green, blue
913 should be lists or tuples of xyY coordinates (only x and y will be
914 used, so Y can be zero or None).
915 description (str): Description of the profile.
916 black_cdm2 (float): Black level in cd/m^2.
917 white_cdm2 (float): White level in cd/m^2.
918 master_black_cdm2 (int): Mastering display black level in cd/m^2.
919 master_white_cdm2 (int): Mastering display white level in cd/m^2.
920 use_alternate_master_white_clip (bool): Use alternate master white clip
921 for PQ.
922 system_gamma (float): System gamma, not used for PQ.
923 ambient_cdm2 (float): Ambient light level in cd/m^2, not used for PQ.
924 maxsignal (float): Maximum signal value, not used for PQ.
925 content_rgb_space (str): RGB space for content, e.g. "DCI P3".
926 clutres (int): Resolution of the cLUT.
927 mode (str): Gamut mapping mode for roll-off, not used for HLG.
928 sat (float): Saturation preservation factor for roll-off, not used for HLG.
929 hue (float): Hue preservation factor for roll-off, not used for HLG.
930 forward_xicclu (callable): Forward XICCLU function, not used for HLG.
931 backward_xicclu (callable): Backward XICCLU function, not used for HLG.
932 generate_B2A (bool): Generate B2A table, not used for HLG.
933 worker (callable): Worker function for parallel processing, not used here.
934 logfile (file): Log file for output, can be None.
935 cat (str): Chromatic adaptation transform, default is "Bradford".
936
937 Returns:
938 ICCProfile: A synthetic HDR cLUT profile.
939 """
940 rgb_space = colormath.get_rgb_space(rgb_space)
941 content_rgb_space = colormath.get_rgb_space(content_rgb_space)
942
943 if hdr_format == "PQ":
944 bt2390 = colormath.BT2390(
945 black_cdm2,
946 white_cdm2,
947 master_black_cdm2,
948 master_white_cdm2,
949 use_alternate_master_white_clip,
950 )
951 # Preserve detail in saturated colors if mastering display peak < 10K cd/m2
952 # XXX: Effect is detrimental to contrast at low target peak, and looks
953 # artificial for BT.2390-4. Don't use for now.
954 preserve_saturated_detail = False # master_white_cdm2 < 10000
955 if preserve_saturated_detail:
956 bt2390s = colormath.BT2390(black_cdm2, white_cdm2, master_black_cdm2, 10000)
957
958 maxv = white_cdm2 / 10000.0
959
960 def eotf(v: float) -> float:
961 """Electro-Optical Transfer Function (EOTF) for PQ.
962
963 Args:
964 v (float): Input value in range [0, 1].
965
966 Returns:
967 float: Output value in range [0, 1] after applying EOTF.
968 """
969 return colormath.special_pow(v, -2084)
970
971 _oetf = eotf_inverse = lambda v: colormath.special_pow(v, 1.0 / -2084)
972 eetf = bt2390.apply
973
974 # Apply a slight power to the segments to optimize encoding
975 encpow = min(max(bt2390.omaxi * (5 / 3.0), 1.0), 1.5)
976
977 def encf(v: float) -> float:
978 """Encoding function for PQ.
979
980 Args:
981 v (float): Input value in range [0, 1].
982
983 Returns:
984 float: Output value in range [0, 1] after applying encoding
985 function.
986 """
987 if v < bt2390.mmaxi:
988 v = colormath.convert_range(v, 0, bt2390.mmaxi, 0, 1)
989 v = colormath.special_pow(v, 1.0 / encpow, 2)
990 return colormath.convert_range(v, 0, 1, 0, bt2390.mmaxi)
991 return v
992
993 def encf_inverse(v: float) -> float:
994 """Inverse encoding function for PQ.
995
996 Args:
997 v (float): Input value in range [0, 1].
998
999 Returns:
1000 float: Output value in range [0, 1] after applying inverse
1001 encoding function.
1002 """
1003 if v < bt2390.mmaxi:
1004 v = colormath.convert_range(v, 0, bt2390.mmaxi, 0, 1)
1005 v = colormath.special_pow(v, encpow, 2)
1006 return colormath.convert_range(v, 0, 1, 0, bt2390.mmaxi)
1007 return v
1008
1009 elif hdr_format == "HLG":
1010 # Note: Unlike the PQ black level lift, we apply HLG black offset as
1011 # separate final step, not as part of the HLG EOTF
1012 hlg = colormath.HLG(0, white_cdm2, system_gamma, ambient_cdm2, rgb_space)
1013
1014 if maxsignal < 1:
1015 # Adjust EOTF so that EOTF[maxsignal] gives (approx) white_cdm2
1016 while hlg.eotf(maxsignal) * hlg.white_cdm2 < white_cdm2:
1017 hlg.white_cdm2 += 1
1018
1019 lscale = 1.0 / hlg.oetf(1.0, True)
1020 hlg.white_cdm2 *= lscale
1021 if lscale < 1 and logfile:
1022 logfile.write(
1023 f"Nominal peak luminance after scaling = {hlg.white_cdm2:.2f}\n"
1024 )
1025
1026 Ymax = hlg.eotf(maxsignal) # noqa: N806
1027
1028 maxv = 1.0
1029 eotf = hlg.eotf
1030
1031 def eotf_inverse(v: float) -> float:
1032 """Inverse Electro-Optical Transfer Function (EOTF) for HLG.
1033
1034 Args:
1035 v (float): Input value in range [0, 1].
1036
1037 Returns:
1038 float: Output value in range [0, 1] after applying inverse EOTF.
1039 """
1040 return hlg.eotf(v, True)
1041
1042 _oetf = hlg.oetf
1043
1044 def eetf(v: float) -> float:
1045 """Rolloff encoding function for HLG.
1046
1047 Args:
1048 v (float): Input value in range [0, 1].
1049
1050 Returns:
1051 float: Output value in range [0, 1] after applying encoding
1052 function.
1053 """
1054 return v
1055
1056 def encf(v: float) -> float:
1057 """Encoding function for HLG.
1058
1059 Args:
1060 v (float): Input value in range [0, 1].
1061
1062 Returns:
1063 float: Output value in range [0, 1] after applying encoding
1064 function.
1065 """
1066 return v
1067 else:
1068 raise NotImplementedError(f"Unknown HDR format {hdr_format!r}")
1069
1070 tonemap = eetf(1) != 1
1071
1072 profile = ICCProfile()
1073 profile.version = 2.2 # Match ArgyllCMS
1074
1075 profile.tags.desc = TextDescriptionType(b"", "desc")
1076 profile.tags.desc.ASCII = description
1077 profile.tags.cprt = TextType(b"text\0\0\0\0Public domain\0", "cprt")
1078
1079 profile.tags.wtpt = XYZType(profile=profile)
1080 (
1081 profile.tags.wtpt.X,
1082 profile.tags.wtpt.Y,
1083 profile.tags.wtpt.Z,
1084 ) = colormath.get_whitepoint(rgb_space[1])
1085
1086 profile.tags.arts = ChromaticAdaptionTag()
1087 profile.tags.arts.update(colormath.get_cat_matrix(cat))
1088
1089 itable = profile.tags.A2B0 = LUT16Type(None, "A2B0", profile)
1090 itable.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
1091 # HDR RGB
1092 debugtable0 = profile.tags.DBG0 = LUT16Type(None, "DBG0", profile)
1093 debugtable0.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
1094 # Display RGB
1095 debugtable1 = profile.tags.DBG1 = LUT16Type(None, "DBG1", profile)
1096 debugtable1.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
1097 # Display XYZ
1098 debugtable2 = profile.tags.DBG2 = LUT16Type(None, "DBG2", profile)
1099 debugtable2.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
1100
1101 if generate_B2A:
1102 otable = profile.tags.B2A0 = LUT16Type(None, "B2A0", profile)
1103 Xr, Yr, Zr = colormath.adapt( # noqa: N806
1104 *colormath.RGB2XYZ(1, 0, 0, rgb_space=rgb_space),
1105 whitepoint_source=rgb_space[1],
1106 cat=cat,
1107 )
1108 Xg, Yg, Zg = colormath.adapt( # noqa: N806
1109 *colormath.RGB2XYZ(0, 1, 0, rgb_space=rgb_space),
1110 whitepoint_source=rgb_space[1],
1111 cat=cat,
1112 )
1113 Xb, Yb, Zb = colormath.adapt( # noqa: N806
1114 *colormath.RGB2XYZ(0, 0, 1, rgb_space=rgb_space),
1115 whitepoint_source=rgb_space[1],
1116 cat=cat,
1117 )
1118 m1 = colormath.Matrix3x3(((Xr, Xg, Xb), (Yr, Yg, Yb), (Zr, Zg, Zb)))
1119 m2 = m1.inverted()
1120 scale = 1 + (32767 / 32768.0)
1121 m3 = colormath.Matrix3x3(((scale, 0, 0), (0, scale, 0), (0, 0, scale)))
1122 otable.matrix = m2 * m3
1123
1124 # Input curve interpolation
1125 # Normlly the input curves would either be linear (= 1:1 mapping to
1126 # cLUT) or the respective tone response curve.
1127 # We use a overall linear curve that is 'bent' in <clutres> intervals
1128 # to accomodate the non-linear TRC. Thus, we can get away with much
1129 # fewer cLUT grid points.
1130
1131 # Use higher interpolation size than actual number of curve entries
1132 steps = 2**15 + 1
1133 maxstep = steps - 1.0
1134 segment = 1.0 / (clutres - 1.0)
1135 iv = 0.0
1136 prevpow = eotf(eetf(0))
1137 # Apply a slight power to segments to optimize encoding
1138 nextpow = eotf(eetf(encf(segment)))
1139 prevv = 0
1140 pprevpow = [0]
1141 # clipped = False
1142 xp = []
1143 if generate_B2A:
1144 oxp = []
1145 for j in range(steps):
1146 v = j / maxstep
1147 if v > iv + segment:
1148 iv += segment
1149 prevpow = nextpow
1150 # Apply a slight power to segments to optimize encoding
1151 nextpow = eotf(eetf(encf(iv + segment)))
1152 if nextpow > prevpow or TEST_INPUT_CURVE_CLIPPING:
1153 prevs = 1.0 - (v - iv) / segment
1154 nexts = (v - iv) / segment
1155 vv = prevs * prevpow + nexts * nextpow
1156 prevv = v
1157 if prevpow > pprevpow[-1]:
1158 pprevpow.append(prevpow)
1159 else:
1160 # clipped = True
1161 # Linearly interpolate
1162 vv = colormath.convert_range(v, prevv, 1, prevpow, 1)
1163 out = eotf_inverse(vv)
1164 xp.append(out)
1165 if generate_B2A:
1166 oxp.append(eotf(eetf(v)) / maxv)
1167 interp = colormath.Interp(xp, list(range(steps)), use_numpy=True)
1168 if generate_B2A:
1169 ointerp = colormath.Interp(oxp, list(range(steps)), use_numpy=True)
1170
1171 # Save interpolation input values for diagnostic purposes
1172 profile.tags.kTRC = CurveType()
1173 interp_inverse = colormath.Interp(list(range(steps)), xp, use_numpy=True)
1174 profile.tags.kTRC[:] = [
1175 interp_inverse(colormath.convert_range(v, 0, 2048, 0, maxstep)) * 65535
1176 for v in range(2049)
1177 ]
1178
1179 # Create input and output curves
1180 for _i in range(3):
1181 itable.input.append([])
1182 itable.output.append([0, 65535])
1183 debugtable0.input.append([0, 65535])
1184 debugtable0.output.append([0, 65535])
1185 debugtable1.input.append([0, 65535])
1186 debugtable1.output.append([0, 65535])
1187 debugtable2.input.append([0, 65535])
1188 debugtable2.output.append([0, 65535])
1189 if generate_B2A:
1190 otable.input.append([])
1191 otable.output.append([0, 65535])
1192
1193 # Generate device-to-PCS shaper curves from interpolated values
1194 if logfile:
1195 logfile.write("Generating device-to-PCS shaper curves...\n")
1196 entries = 1025
1197 prevperc = 0
1198 endperc = 1 if generate_B2A else 2
1199 threshold = eotf_inverse(pprevpow[-2])
1200 k = None
1201 end = eotf_inverse(pprevpow[-1])
1202 l = entries - 1
1203 if end > threshold:
1204 for j in range(entries):
1205 n = j / (entries - 1.0)
1206 if eetf(n) > end:
1207 l = j - 1
1208 break
1209 for j in range(entries):
1210 if worker and worker.thread_abort:
1211 if forward_xicclu:
1212 forward_xicclu.exit()
1213 if backward_xicclu:
1214 backward_xicclu.exit()
1215 raise Exception("aborted")
1216 n = j / (entries - 1.0)
1217 v = interp(eetf(n)) / maxstep
1218 if hdr_format == "PQ":
1219 # threshold = 1.0 - segment * math.ceil((1.0 - bt2390.mmaxi) *
1220 # (clutres - 1.0) + 1)
1221 # check = n >= threshold
1222 check = tonemap and eetf(n + (1 / (entries - 1.0))) > threshold
1223 elif hdr_format == "HLG":
1224 check = maxsignal < 1 and n >= maxsignal
1225 if check and not TEST_INPUT_CURVE_CLIPPING:
1226 # Linear interpolate shaper for last n cLUT steps to prevent
1227 # clipping in shaper
1228 if k is None:
1229 k = j
1230 ov = v
1231 ev = interp(eetf(l / (entries - 1.0))) / maxstep
1232 # v = min(ov + (1.0 - ov) * ((j - k) / (entries - k - 1.0)), 1.0)
1233 v = min(colormath.convert_range(j, k, l, ov, ev), n)
1234 for i in range(3):
1235 itable.input[i].append(v * 65535)
1236 perc = math.floor(n * endperc)
1237 if logfile and perc > prevperc:
1238 logfile.write(f"\r{perc:.0f}%")
1239 prevperc = perc
1240 startperc = perc
1241
1242 if generate_B2A:
1243 # Generate PCS-to-device shaper curves from interpolated values
1244 if logfile:
1245 logfile.write("\rGenerating PCS-to-device shaper curves...\n")
1246 logfile.write(f"\r{perc:.0f}%")
1247 for j in range(4096):
1248 if worker and worker.thread_abort:
1249 if forward_xicclu:
1250 forward_xicclu.exit()
1251 if backward_xicclu:
1252 backward_xicclu.exit()
1253 raise Exception("aborted")
1254 n = j / 4095.0
1255 v = ointerp(n) / maxstep * 65535
1256 for i in range(3):
1257 otable.input[i].append(v)
1258 perc = startperc + math.floor(n)
1259 if logfile and perc > prevperc:
1260 logfile.write(f"\r{perc:.0f}%")
1261 prevperc = perc
1262 startperc = perc
1263
1264 # Scene RGB -> HDR tone mapping -> HDR XYZ -> backward lookup -> display RGB
1265 itable.clut = []
1266 debugtable0.clut = []
1267 debugtable1.clut = []
1268 debugtable2.clut = []
1269 clutmax = clutres - 1.0
1270 step = 1.0 / clutmax
1271 count = 0
1272 # Lpt is the preferred mode for chroma blending. Some preliminary visual
1273 # comparison has shown it does overall the best job preserving hue and
1274 # saturation (blue hues superior to IPT). DIN99d is the second best,
1275 # but vibrant red turns slightly orange when desaturated (DIN99d has best
1276 # blue saturation preservation though).
1277 blendmode = "Lpt"
1278 IPT_white_XYZ = colormath.get_cat_matrix("IPT").inverted() * (1, 1, 1) # noqa: N806
1279 Cmode = ("all", "primaries_secondaries")[0] # noqa: N806
1280 RGB_in = [] # noqa: N806
1281 HDR_ICtCp = [] # noqa: N806
1282 HDR_RGB = [] # noqa: N806
1283 HDR_XYZ = [] # noqa: N806
1284 HDR_min_I = [] # noqa: N806
1285 logmsg = "\rGenerating lookup table"
1286 if hdr_format == "PQ" and tonemap:
1287 logmsg += " and applying HDR tone mapping"
1288 endperc = 25
1289 else:
1290 endperc = 50
1291 if logfile:
1292 logfile.write(f"{logmsg}...\n")
1293 logfile.write(f"\r{perc:.0f}%")
1294 # Selective hue preservation for redorange/orange
1295 # (otherwise shift towards yellow to preserve more saturation and detail)
1296 # Hue angles (RGB):
1297 # red, yellow, yellow, green, red
1298 hinterp = colormath.Interp(
1299 [0, 0.166666, 0.166666, 1], [1, hue, 1, 1], use_numpy=True
1300 )
1301 # Saturation adjustment for yellow/green/cyan
1302 # Hue angles (RGB):
1303 # red, orange, yellow, green, cyan, cyan/blue, red
1304 sinterp = colormath.Interp(
1305 [0, 0.083333, 0.166666, 0.333333, 0.5, 0.583333, 1],
1306 [1, 1, 0.5, 0.5, 0.5, 1, 1],
1307 use_numpy=True,
1308 )
1309 for R in range(clutres): # noqa: N806
1310 for G in range(clutres): # noqa: N806
1311 for B in range(clutres): # noqa: N806
1312 if worker and worker.thread_abort:
1313 if forward_xicclu:
1314 forward_xicclu.exit()
1315 if backward_xicclu:
1316 backward_xicclu.exit()
1317 raise Exception("aborted")
1318 # Apply a slight power to the segments to optimize encoding
1319 RGB = [encf(v * step) for v in (R, G, B)] # noqa: N806
1320 RGB_in.append(tuple(RGB))
1321 if DEBUG and R == G == B:
1322 print("RGB {:5.3f} {:5.3f} {:5.3f}".format(*RGB), end=" ")
1323 # RGB_sum = sum(RGB)
1324 if hdr_format == "PQ" and mode in (
1325 "HSV",
1326 "HSV_ICtCp",
1327 "ICtCp",
1328 "RGB_ICtCp",
1329 ):
1330 # Record original hue angle, saturation and value
1331 H, S, V = colormath.RGB2HSV(*RGB) # noqa: N806
1332 if hdr_format == "PQ" and mode in ("HSV_ICtCp", "ICtCp", "RGB_ICtCp"):
1333 I1, Ct1, Cp1 = colormath.RGB2ICtCp( # noqa: N806
1334 *RGB, rgb_space=rgb_space, eotf=eotf, oetf=eotf_inverse
1335 )
1336 if DEBUG and R == G == B:
1337 print(
1338 f"-> ICtCp {I1:5.3f} {Ct1:5.3f} {Cp1:5.3f}",
1339 end=" ",
1340 )
1341 I2 = eetf(I1) # noqa: N806
1342 if preserve_saturated_detail and S:
1343 sf = S
1344 I2 *= 1 - sf # noqa: N806
1345 I2 += bt2390s.apply(I1) * sf # noqa: N806
1346 if hdr_format == "HLG":
1347 X, Y, Z = hlg.RGB2XYZ(*RGB) # noqa: N806
1348 if Y:
1349 Y1 = Y # noqa: N806
1350 I1 = hlg.eotf(Y, True) # noqa: N806
1351 I2 = min(I1, maxsignal) # noqa: N806
1352 Y2 = hlg.eotf(I2) # noqa: N806
1353 Y3 = Y2 / Ymax # noqa: N806
1354 X, Y, Z = (v / Y * Y3 if Y else v for v in (X, Y, Z)) # noqa: N806
1355 if R == G == B and logfile and DEBUG:
1356 logfile.write(
1357 f"\rE {Y1:.4f} -> E' {I1:.4f} -> roll-off -> "
1358 f"{I2:.4f} -> E {Y2:.4f} -> "
1359 f"scale ({Y3 / Y2:.0%}) -> {Y3:.4f}\n"
1360 )
1361 elif mode == "XYZ":
1362 X, Y, Z = colormath.RGB2XYZ(*RGB, rgb_space=rgb_space, eotf=eotf) # noqa: N806
1363 if Y:
1364 I1 = colormath.special_pow(Y, 1.0 / -2084) # noqa: N806
1365 I2 = eetf(I1) # noqa: N806
1366 Y2 = colormath.special_pow(I2, -2084) # noqa: N806
1367 X, Y, Z = (v / Y * Y2 for v in (X, Y, Z)) # noqa: N806
1368 else:
1369 I1 = I2 = 0 # noqa: N806
1370 elif mode in ("HSV", "HSV_ICtCp", "ICtCp", "RGB", "RGB_ICtCp"):
1371 if mode in ("HSV", "RGB"):
1372 I1 = max(RGB) # noqa: N806
1373 if mode in ("HSV", "HSV_ICtCp", "ICtCp", "RGB_ICtCp"):
1374 # Allow hue shift based on hue angle
1375 hf = hinterp(H)
1376
1377 # Saturation adjustment
1378 cf = sinterp(H)
1379 for i, v in enumerate(RGB):
1380 RGB[i] = eetf(v) # noqa: N806
1381 if preserve_saturated_detail and S:
1382 sf = S
1383 RGB[i] *= 1 - sf # noqa: N806
1384 RGB[i] += bt2390s.apply(v) * sf # noqa: N806
1385 RGB_shifted = RGB # Potentially hue shifted RGB # noqa: N806
1386 if mode in ("HSV", "HSV_ICtCp"):
1387 HSV = list(colormath.RGB2HSV(*RGB_shifted)) # noqa: N806
1388
1389 if mode == "HSV":
1390 # Allow hue shift based on hue angle
1391 H = H * hf + HSV[0] * (1 - hf) # noqa: N806
1392
1393 # Set hue angle
1394 HSV[0] = H # noqa: N806
1395 RGB = colormath.HSV2RGB(*HSV) # noqa: N806
1396 if mode in ("HSV", "RGB"):
1397 I2 = max(RGB) # noqa: N806
1398 elif mode == "YRGB":
1399 LinearRGB = [eotf(v) for v in RGB] # noqa: N806
1400 I1 = ( # noqa: N806
1401 0.2627 * LinearRGB[0]
1402 + 0.678 * LinearRGB[1]
1403 + 0.0593 * LinearRGB[2]
1404 )
1405 I2 = eotf(eetf(eotf_inverse(I1))) # noqa: N806
1406 min_I = I2 / I1 if I1 else 1 # noqa: N806
1407 RGB = [eotf_inverse(min_I * v) for v in LinearRGB] # noqa: N806
1408 if (
1409 hdr_format == "PQ"
1410 and mode in ("HSV_ICtCp", "ICtCp", "RGB_ICtCp", "XYZ")
1411 and I1
1412 and I2
1413 ):
1414 if mode != "ICtCp" or (forward_xicclu and backward_xicclu):
1415 # Don't desaturate colors which are lighter after
1416 # roll-off if mode is not ICtCp or if doing
1417 # display-based desaturation
1418 dsat = 1.0
1419 else:
1420 # Desaturate colors which are lighter after roll-off
1421 # if mode is ICtCp and not doing display-based
1422 # desaturation
1423 dsat = I1 / I2
1424 min_I = min(dsat, I2 / I1) # noqa: N806
1425 else:
1426 min_I = 1 # noqa: N806
1427 if hdr_format == "PQ" and mode in ("HSV_ICtCp", "ICtCp", "RGB_ICtCp"):
1428 if DEBUG and R == G == B:
1429 print(f"* {min_I:5.3f}", "->", end=" ")
1430 Ct2, Cp2 = (min_I * v for v in (Ct1, Cp1)) # noqa: N806
1431 if DEBUG and R == G == B:
1432 print(f"{I2:5.3f} {Ct2:5.3f} {Cp2:5.3f}", "->", end=" ")
1433 if hdr_format == "HLG":
1434 pass
1435 elif mode == "XYZ":
1436 X, Y, Z = colormath.XYZsaturation(X, Y, Z, min_I, rgb_space[1])[0] # noqa: N806
1437 RGB = colormath.XYZ2RGB(X, Y, Z, rgb_space, oetf=eotf_inverse) # noqa: N806
1438 elif mode == "ICtCp":
1439 X, Y, Z = colormath.ICtCp2XYZ(I2, Ct2, Cp2) # noqa: N806
1440 RGB = colormath.XYZ2RGB( # noqa: N806
1441 X, Y, Z, rgb_space, clamp=False, oetf=eotf_inverse
1442 )
1443 if DEBUG and R == G == B:
1444 print("RGB {:5.3f} {:5.3f} {:5.3f}".format(*RGB))
1445 HDR_RGB.append(RGB)
1446 if hdr_format == "HLG":
1447 pass
1448 elif mode not in ("XYZ", "ICtCp"):
1449 X, Y, Z = colormath.RGB2XYZ(*RGB, rgb_space=rgb_space, eotf=eotf) # noqa: N806
1450 if hdr_format == "PQ" and mode in ("HSV_ICtCp", "ICtCp", "RGB_ICtCp"):
1451 # Use hue and chroma from ICtCp
1452 I, Ct, Cp = colormath.XYZ2ICtCp(X, Y, Z) # noqa: N806
1453 L, C, H = colormath.Lab2LCHab(I * 100, Ct * 100, Cp * 100) # noqa: N806
1454 L2, C2, H2 = colormath.Lab2LCHab(I2 * 100, Ct2 * 100, Cp2 * 100) # noqa: N806
1455
1456 # Allow hue shift based on hue angle
1457 I3, Ct3, Cp3 = colormath.RGB2ICtCp( # noqa: N806
1458 *RGB_shifted, rgb_space=rgb_space, eotf=eotf, oetf=eotf_inverse
1459 )
1460 L3, C3, H3 = colormath.Lab2LCHab(I3 * 100, Ct3 * 100, Cp3 * 100) # noqa: N806
1461 L = L * hf + L3 * (1 - hf) # noqa: N806
1462 C = C * hf + C3 * (1 - hf) # noqa: N806
1463 H2 = H2 * hf + H3 * (1 - hf) # noqa: N806
1464
1465 # Saturation adjustment
1466 C = colormath.convert_range(I1, I2, 1, C2, min(C2, C) * cf) # noqa: N806
1467 I, Ct2, Cp2 = (v / 100.0 for v in colormath.LCHab2Lab(L, C, H2)) # noqa: N806
1468 Ct, Cp = Ct2, Cp2 # noqa: N806
1469 if I1 > I2:
1470 f = colormath.convert_range(I1, I2, 1, 1, 0)
1471 Ct2, Cp2 = (v * f for v in (Ct2, Cp2)) # noqa: N806
1472 if mode in ("HSV_ICtCp", "RGB_ICtCp"):
1473 f = colormath.convert_range(sum(RGB_in[-1]), 0, 3, 1, sat)
1474 Ct2 = Ct * f + Ct2 * (1 - f) # noqa: N806
1475 Cp2 = Cp * f + Cp2 * (1 - f) # noqa: N806
1476 I2 = I * f + I2 * (1 - f) # noqa: N806
1477 X, Y, Z = colormath.ICtCp2XYZ(I2, Ct2, Cp2) # noqa: N806
1478 RGB_ICtCp_XYZ = [X, Y, Z] # noqa: N806
1479 # X, Y, Z = (v / maxv for v in (X, Y, Z))
1480 HDR_XYZ.append((RGB_in[-1], [X, Y, Z], RGB_ICtCp_XYZ))
1481 HDR_min_I.append(min_I)
1482 count += 1
1483 perc = startperc + math.floor(
1484 count / clutres**3.0 * (endperc - startperc)
1485 )
1486 if logfile and perc > prevperc:
1487 logfile.write(f"\r{perc:.0f}%")
1488 prevperc = perc
1489
1490 if hdr_format == "PQ" and tonemap:
1491 from DisplayCAL.multiprocess import cpu_count, pool_slice
1492
1493 num_cpus = cpu_count()
1494 num_workers = num_cpus
1495 if num_cpus > 2:
1496 num_workers -= 1
1497 num_batches = clutres // 6
1498
1499 HDR_XYZ = functools.reduce( # noqa: N806
1500 operator.iadd,
1501 pool_slice(
1502 _mp_hdr_tonemap,
1503 HDR_XYZ,
1504 (rgb_space, maxv, sat, cat),
1505 {},
1506 num_workers,
1507 worker and worker.thread_abort,
1508 logfile,
1509 num_batches,
1510 perc,
1511 ),
1512 [],
1513 )
1514 prevperc = startperc = perc = 75
1515 else:
1516 prevperc = startperc = perc = 50
1517
1518 for i, item in enumerate(HDR_XYZ):
1519 if not item and worker and worker.thread_abort: # Aborted
1520 if forward_xicclu:
1521 forward_xicclu.exit()
1522 if backward_xicclu:
1523 backward_xicclu.exit()
1524 raise Exception("aborted")
1525 (RGB, (X, Y, Z), RGB_ICtCp_XYZ) = item # noqa: N806
1526 I, Ct, Cp = colormath.XYZ2ICtCp(X, Y, Z, oetf=eotf_inverse) # noqa: N806
1527 X, Y, Z = (v / maxv for v in (X, Y, Z)) # noqa: N806
1528 HDR_ICtCp.append((I, Ct, Cp))
1529 # Adapt to D50
1530 X, Y, Z = colormath.adapt(X, Y, Z, whitepoint_source=rgb_space[1], cat=cat) # noqa: N806
1531 if max(X, Y, Z) * 32768 > 65535 or min(X, Y, Z) < 0 or round(Y, 6) > 1:
1532 # This should not happen
1533 print(
1534 f"#{i}",
1535 "RGB {:.3f} {:.3f} {:.3f}".format(*RGB),
1536 f"XYZ {X:.6f} {Y:.6f} {Z:.6f}",
1537 "not in range [0,1]",
1538 )
1539 HDR_XYZ[i] = (X, Y, Z) # noqa: N806
1540 perc = startperc + math.floor(i / clutres**3.0 * (100 - startperc))
1541 if logfile and perc > prevperc:
1542 logfile.write(f"\r{perc:.0f}%")
1543 prevperc = perc
1544 prevperc = startperc = perc = 0
1545
1546 if forward_xicclu and backward_xicclu and logfile:
1547 logfile.write("\rDoing backward lookup...\n")
1548 logfile.write(f"\r{perc:.0f}%")
1549 count = 0
1550 from DisplayCAL.worker import Xicclu
1551
1552 for _i, (X, Y, Z) in enumerate(HDR_XYZ): # noqa: N806
1553 if worker and worker.thread_abort:
1554 if forward_xicclu:
1555 forward_xicclu.exit()
1556 if backward_xicclu:
1557 backward_xicclu.exit()
1558 raise Exception("aborted")
1559 if forward_xicclu and backward_xicclu and Cmode != "primaries_secondaries":
1560 # HDR XYZ -> backward lookup -> display RGB
1561 backward_xicclu((X, Y, Z))
1562 count += 1
1563 perc = startperc + math.floor(count / clutres**3.0 * (100 - startperc))
1564 if logfile and perc > prevperc and isinstance(backward_xicclu, Xicclu):
1565 logfile.write(f"\r{perc:.0f}%")
1566 prevperc = perc
1567 prevperc = startperc = perc = 0
1568
1569 Cdiff = [] # noqa: N806
1570 Cmax = {} # noqa: N806
1571 Cdmax = {} # noqa: N806
1572 if forward_xicclu and backward_xicclu:
1573 # Display RGB -> forward lookup -> display XYZ
1574 backward_xicclu.close()
1575 try:
1576 display_RGB = backward_xicclu.get() # noqa: N806
1577 except Exception:
1578 if forward_xicclu:
1579 # Make sure resources are not held in use
1580 forward_xicclu.exit()
1581 raise
1582 finally:
1583 backward_xicclu.exit()
1584 if logfile:
1585 logfile.write("\rDoing forward lookup...\n")
1586 logfile.write(f"\r{perc:.0f}%")
1587
1588 # Smooth
1589 row = 0
1590 for _ in range(clutres):
1591 for _ in range(clutres):
1592 debugtable1.clut.append([])
1593 for _ in range(clutres):
1594 RGBdisp = display_RGB[row] # noqa: N806
1595 debugtable1.clut[-1].append(
1596 [min(max(v * 65535, 0), 65535) for v in RGBdisp]
1597 )
1598 row += 1
1599 debugtable1.smooth()
1600 display_RGB = [] # noqa: N806
1601 for block in debugtable1.clut:
1602 for row in block:
1603 display_RGB.append([v / 65535.0 for v in row])
1604
1605 from DisplayCAL.worker import Xicclu
1606
1607 for i, (R, G, B) in enumerate(display_RGB): # noqa: N806
1608 if worker and worker.thread_abort:
1609 if forward_xicclu:
1610 forward_xicclu.exit()
1611 if backward_xicclu:
1612 backward_xicclu.exit()
1613 raise Exception("aborted")
1614 forward_xicclu((R, G, B))
1615 perc = startperc + math.floor((i + 1) / clutres**3.0 * (100 - startperc))
1616 if logfile and perc > prevperc and isinstance(forward_xicclu, Xicclu):
1617 logfile.write(f"\r{perc:.0f}%")
1618 prevperc = perc
1619 prevperc = startperc = perc = 0
1620
1621 if Cmode == "primaries_secondaries":
1622 # Compare to chroma of content primaries/secondaries to determine
1623 # general chroma compression factor
1624 forward_xicclu((0, 0, 1))
1625 forward_xicclu((0, 1, 0))
1626 forward_xicclu((1, 0, 0))
1627 forward_xicclu((0, 1, 1))
1628 forward_xicclu((1, 0, 1))
1629 forward_xicclu((1, 1, 0))
1630 forward_xicclu.close()
1631 display_XYZ = forward_xicclu.get() # noqa: N806
1632 if Cmode == "primaries_secondaries":
1633 for i in range(6):
1634 if i == 0:
1635 # Blue
1636 j = clutres - 1
1637 elif i == 1:
1638 # Green
1639 j = clutres**2 - clutres
1640 elif i == 2:
1641 # Red
1642 j = clutres**3 - clutres**2
1643 elif i == 3:
1644 # Cyan
1645 j = clutres**2 - 1
1646 elif i == 4:
1647 # Magenta
1648 j = clutres**3 - clutres**2 + clutres - 1
1649 elif i == 5:
1650 # Yellow
1651 j = clutres**3 - clutres
1652 R, G, B = RGB_in[j] # noqa: N806
1653 XYZsrc = HDR_XYZ[j] # noqa: N806
1654 XYZdisp = display_XYZ[-(6 - i)] # noqa: N806
1655 XYZc = colormath.RGB2XYZ(R, G, B, content_rgb_space, eotf=eotf) # noqa: N806
1656 XYZc = colormath.adapt( # noqa: N806
1657 *XYZc, whitepoint_source=content_rgb_space[1], cat=cat
1658 )
1659 L, C, H = colormath.XYZ2DIN99dLCH(*(v * 100 for v in XYZc)) # noqa: N806
1660 Ld, Cd, Hd = colormath.XYZ2DIN99dLCH(*(v * 100 for v in XYZdisp)) # noqa: N806
1661 Cdmaxk = tuple(map(round, (Ld, Hd))) # noqa: N806
1662 if C > Cmax.get(Cdmaxk, -1): # noqa: SIM300
1663 Cmax[Cdmaxk] = C
1664 Cdiff.append(min(Cd / C, 1.0))
1665 if Cd > Cdmax.get(Cdmaxk, -1):
1666 Cdmax[Cdmaxk] = Cd
1667 print(f"RGB in {R:5.2f} {G:5.2f} {B:5.2f}")
1668 print(
1669 "Content BT2020 XYZ (DIN99d) {:5.2f} {:5.2f} {:5.2f}".format(
1670 *(v * 100 for v in XYZc)
1671 )
1672 )
1673 print(f"Content BT2020 LCH (DIN99d) {L:5.2f} {C:5.2f} {H:5.2f}")
1674 print(
1675 "Display XYZ {:5.2f} {:5.2f} {:5.2f}".format(
1676 *(v * 100 for v in XYZdisp)
1677 )
1678 )
1679 print(f"Display LCH (DIN99d) {Ld:5.2f} {Cd:5.2f} {Hd:5.2f}")
1680 if logfile:
1681 logfile.write(
1682 "\r{} chroma compression factor: {:6.4f}\n".format(
1683 {0: "B", 1: "G", 2: "R", 3: "C", 4: "M", 5: "Y"}[i],
1684 Cdiff[-1],
1685 )
1686 )
1687 # Tweak so that it gives roughly 0.91 for a Rec. 709 target
1688 general_compression_factor = (sum(Cdiff) / len(Cdiff)) * 0.99
1689 else:
1690 display_RGB = False # noqa: N806
1691 display_XYZ = False # noqa: N806
1692
1693 display_LCH = [] # noqa: N806
1694 if Cmode != "primaries_secondaries" and display_XYZ:
1695 # Determine compression factor by comparing display to content
1696 # colorspace in BT.2020
1697 if logfile:
1698 logfile.write("\rDetermining chroma compression factors...\n")
1699 logfile.write(f"\r{perc:.0f}%")
1700 for i, XYZsrc in enumerate(HDR_XYZ): # noqa: N806
1701 if worker and worker.thread_abort:
1702 if forward_xicclu:
1703 forward_xicclu.exit()
1704 if backward_xicclu:
1705 backward_xicclu.exit()
1706 raise Exception("aborted")
1707
1708 XYZdisp = display_XYZ[i] if display_XYZ else XYZsrc # noqa: N806
1709 # # Adjust luminance from destination to source
1710 # Ydisp = XYZdisp[1]
1711 # if Ydisp:
1712 # XYZdisp = [v / Ydisp * XYZsrc[1] for v in XYZdisp]
1713 X, Y, Z = (v * maxv for v in XYZsrc) # noqa: N806
1714 X, Y, Z = colormath.adapt( # noqa: N806
1715 X, Y, Z, whitepoint_destination=content_rgb_space[1], cat=cat
1716 )
1717 R, G, B = colormath.XYZ2RGB(X, Y, Z, content_rgb_space, oetf=eotf_inverse) # noqa: N806
1718 XYZc = colormath.RGB2XYZ(R, G, B, content_rgb_space, eotf=eotf) # noqa: N806
1719 XYZc = colormath.adapt( # noqa: N806
1720 *XYZc,
1721 whitepoint_source=content_rgb_space[1],
1722 whitepoint_destination=rgb_space[1],
1723 cat=cat,
1724 )
1725 RGBc_r2020 = colormath.XYZ2RGB( # noqa: N806
1726 *XYZc, rgb_space=rgb_space, oetf=eotf_inverse
1727 )
1728 XYZc_r2020 = colormath.RGB2XYZ(*RGBc_r2020, rgb_space=rgb_space, eotf=eotf) # noqa: N806
1729 if blendmode == "ICtCp":
1730 I, Ct, Cp = colormath.XYZ2ICtCp(*XYZc_r2020, oetf=eotf_inverse) # noqa: N806
1731 L, C, H = colormath.Lab2LCHab(I * 100, Cp * 100, Ct * 100) # noqa: N806
1732 XYZdispa = colormath.adapt( # noqa: N806
1733 *XYZdisp, whitepoint_destination=rgb_space[1], cat=cat
1734 )
1735 Id, Ctd, Cpd = colormath.XYZ2ICtCp( # noqa: N806
1736 *(v * maxv for v in XYZdispa), oetf=eotf_inverse
1737 )
1738 Ld, Cd, Hd = colormath.Lab2LCHab(Id * 100, Cpd * 100, Ctd * 100) # noqa: N806
1739 elif blendmode == "IPT":
1740 XYZc_r2020 = colormath.adapt( # noqa: N806
1741 *XYZc_r2020,
1742 whitepoint_source=rgb_space[1],
1743 whitepoint_destination=IPT_white_XYZ,
1744 cat=cat,
1745 )
1746 I, CP, CT = colormath.XYZ2IPT(*XYZc_r2020) # noqa: N806
1747 L, C, H = colormath.Lab2LCHab(I * 100, CP * 100, CT * 100) # noqa: N806
1748 XYZdispa = colormath.adapt( # noqa: N806
1749 *XYZdisp, whitepoint_destination=IPT_white_XYZ, cat=cat
1750 )
1751 Id, Pd, Td = colormath.XYZ2IPT(*XYZdispa) # noqa: N806
1752 Ld, Cd, Hd = colormath.Lab2LCHab(Id * 100, Pd * 100, Td * 100) # noqa: N806
1753 elif blendmode == "Lpt":
1754 XYZc_r2020 = colormath.adapt( # noqa: N806
1755 *XYZc_r2020, whitepoint_source=rgb_space[1], cat=cat
1756 )
1757 L, p, t = colormath.XYZ2Lpt(*(v / maxv * 100 for v in XYZc_r2020)) # noqa: N806
1758 L, C, H = colormath.Lab2LCHab(L, p, t) # noqa: N806
1759 Ld, pd, td = colormath.XYZ2Lpt(*(v * 100 for v in XYZdisp)) # noqa: N806
1760 Ld, Cd, Hd = colormath.Lab2LCHab(Ld, pd, td) # noqa: N806
1761 elif blendmode == "XYZ":
1762 XYZc_r2020 = colormath.adapt( # noqa: N806
1763 *XYZc_r2020, whitepoint_source=rgb_space[1], cat=cat
1764 )
1765 wx, wy = colormath.XYZ2xyY(*colormath.get_whitepoint())[:2]
1766 x, y, Y = colormath.XYZ2xyY(*XYZc_r2020) # noqa: N806
1767 x -= wx
1768 y -= wy
1769 L, C, H = colormath.Lab2LCHab(*(v * 100 for v in (Y, x, y))) # noqa: N806
1770 x, y, Y = colormath.XYZ2xyY(*XYZdisp) # noqa: N806
1771 x -= wx
1772 y -= wy
1773 Ld, Cd, Hd = colormath.Lab2LCHab(*(v * 100 for v in (Y, x, y))) # noqa: N806
1774 else:
1775 # DIN99d
1776 XYZc_r202099 = colormath.adapt( # noqa: N806
1777 *XYZc_r2020, whitepoint_source=rgb_space[1], cat=cat
1778 )
1779 L, C, H = colormath.XYZ2DIN99dLCH( # noqa: N806
1780 *(v / maxv * 100 for v in XYZc_r202099)
1781 )
1782 Ld, Cd, Hd = colormath.XYZ2DIN99dLCH(*(v * 100 for v in XYZdisp)) # noqa: N806
1783 Cdmaxk = tuple(map(round, (Ld, Hd), (2, 2))) # noqa: N806
1784 if C > Cmax.get(Cdmaxk, -1): # noqa: SIM300
1785 Cmax[Cdmaxk] = C
1786 if C:
1787 # print(f"{Cd:6.3f} {C:6.3f}")
1788 Cdiff.append(min(Cd / C, 1.0))
1789 # if Cdiff[-1] < 0.0001:
1790 # raise RuntimeError(
1791 # f"#{i} RGB {R:5.3f} {G:5.3f} {B:5.3f} Cdiff {Cdiff[-1]:5.3f}"
1792 # )
1793 else:
1794 Cdiff.append(1.0)
1795 display_LCH.append((Ld, Cd, Hd))
1796 if Cd > Cdmax.get(Cdmaxk, -1):
1797 Cdmax[Cdmaxk] = Cd
1798 if DEBUG:
1799 print("RGB in {:5.2f} {:5.2f} {:5.2f}".format(*RGB_in[i]))
1800 print(f"RGB out {R:5.2f} {G:5.2f} {B:5.2f}")
1801 print(
1802 "Content BT2020 XYZ {:5.2f} {:5.2f} {:5.2f}".format(
1803 *(v / maxv * 100 for v in XYZc_r2020)
1804 )
1805 )
1806 print(f"Content BT2020 LCH {L:5.2f} {C:5.2f} {H:5.2f}")
1807 print(
1808 "Display XYZ {:5.2f} {:5.2f} {:5.2f}".format(
1809 *(v * 100 for v in XYZdisp)
1810 )
1811 )
1812 print(f"Display LCH {Ld:5.2f} {Cd:5.2f} {Hd:5.2f}")
1813 perc = startperc + math.floor(i / clutres**3.0 * (80 - startperc))
1814 if logfile and perc > prevperc:
1815 logfile.write(f"\r{perc:.0f}%")
1816 prevperc = perc
1817 startperc = perc
1818
1819 general_compression_factor = sum(Cdiff) / len(Cdiff)
1820
1821 if display_XYZ:
1822 Cmaxv = max(Cmax.values()) # noqa: N806
1823 # Cdmaxv = max(Cdmax.values())
1824
1825 if logfile and display_LCH and Cmode == "primaries_secondaries":
1826 logfile.write(
1827 f"\rChroma compression factor: {general_compression_factor:6.4f}\n"
1828 )
1829
1830 # Chroma compress to display XYZ
1831 if logfile:
1832 if display_XYZ:
1833 logfile.write("\rApplying chroma compression and filling cLUT...\n")
1834 else:
1835 logfile.write("\rFilling cLUT...\n")
1836 logfile.write(f"\r{perc:.0f}%")
1837 row = 0
1838 oog_count = 0
1839 # if forward_xicclu:
1840 # forward_xicclu.spawn()
1841 # if backward_xicclu:
1842 # backward_xicclu.spawn()
1843 for col_0 in range(clutres):
1844 for col_1 in range(clutres):
1845 itable.clut.append([])
1846 debugtable0.clut.append([])
1847 if not display_RGB:
1848 debugtable1.clut.append([])
1849 debugtable2.clut.append([])
1850 for col_2 in range(clutres):
1851 if worker and worker.thread_abort:
1852 if forward_xicclu:
1853 forward_xicclu.exit()
1854 if backward_xicclu:
1855 backward_xicclu.exit()
1856 raise Exception("aborted")
1857 R, G, B = HDR_RGB[row] # noqa: N806
1858 I, Ct, Cp = HDR_ICtCp[row] # noqa: N806
1859 X, Y, Z = HDR_XYZ[row] # noqa: N806
1860 min_I = HDR_min_I[row] # noqa: N806
1861 if not (col_0 == col_1 == col_2) and display_XYZ:
1862 # Desaturate based on compression factor
1863 if display_LCH:
1864 blend = 1
1865 else:
1866 # Blending threshold: Don't desaturate dark colors
1867 # (< 26 cd/m2). Preserves more "pop"
1868 thresh_I = 0.381 # noqa: N806
1869 blend = min_I * min(
1870 max((I - thresh_I) / (0.5081 - thresh_I), 0), 1
1871 )
1872 if blend:
1873 if blendmode == "XYZ":
1874 wx, wy = colormath.XYZ2xyY(*colormath.get_whitepoint())[:2]
1875 x, y, Y = colormath.XYZ2xyY(X, Y, Z) # noqa: N806
1876 x -= wx
1877 y -= wy
1878 L, C, H = colormath.Lab2LCHab(*(v * 100 for v in (Y, x, y))) # noqa: N806
1879 elif blendmode == "ICtCp":
1880 L, C, H = colormath.Lab2LCHab(I * 100, Cp * 100, Ct * 100) # noqa: N806
1881 elif blendmode == "DIN99d":
1882 XYZ = X, Y, Z # noqa: N806
1883 L, C, H = colormath.XYZ2DIN99dLCH(*[v * 100 for v in XYZ]) # noqa: N806
1884 elif blendmode == "IPT":
1885 XYZ = colormath.adapt( # noqa: N806
1886 X, Y, Z, whitepoint_destination=IPT_white_XYZ, cat=cat
1887 )
1888 I, CP, CT = colormath.XYZ2IPT(*XYZ) # noqa: N806
1889 L, C, H = colormath.Lab2LCHab(I * 100, CP * 100, CT * 100) # noqa: N806
1890 elif blendmode == "Lpt":
1891 XYZ = X, Y, Z # noqa: N806
1892 L, p, t = colormath.XYZ2Lpt(*[v * 100 for v in XYZ]) # noqa: N806
1893 L, C, H = colormath.Lab2LCHab(L, p, t) # noqa: N806
1894 if blendmode:
1895 if display_LCH:
1896 Ld, Cd, Hd = display_LCH[row] # noqa: N806
1897 # Cdmaxk = tuple(map(round, (Ld, Hd), (2, 2)))
1898 # # Lookup HDR max chroma for given display
1899 # # luminance and hue
1900 # HCmax = Cmax[Cdmaxk]
1901 # if C and HCmax:
1902 # # Lookup display max chroma for given display
1903 # # luminance and hue
1904 # HCdmax = Cdmax[Cdmaxk]
1905 # # Display max chroma in 0..1 range
1906 # maxCc = min(HCdmax / HCmax, 1.0)
1907 # KSCc = 1.5 * maxCc - 0.5
1908 # # HDR chroma in 0..1 range
1909 # Cc1 = min(C / HCmax, 1.0)
1910 # if Cc1 >= KSCc <= 1 and maxCc > KSCc >= 0:
1911 # # Roll-off chroma
1912 # Cc2 = bt2390.apply(
1913 # Cc1, KSCc, maxCc, 1.0, 0, normalize=False
1914 # )
1915 # C = HCmax * Cc2
1916 # else:
1917 # # Use display chroma as-is (clip)
1918 # if debug:
1919 # print(
1920 # "CLUT grid point "
1921 # f"{int(col_0):d} {int(col_1):d} "
1922 # f"{int(col_2):d}: "
1923 # f"C {C:6.4f} Cd {Cd:6.4f} "
1924 # f"HCmax {HCmax:6.4f} "
1925 # f"maxCc {maxCc:6.4f} "
1926 # f"KSCc {KSCc:6.4f} "
1927 # f"Cc1 {Cc1:6.4f}"
1928 # )
1929 # C = Cd
1930 if C:
1931 C *= min(Cd / C, 1.0) # noqa: N806
1932 C *= min(Ld / L, 1.0) # noqa: N806
1933 else:
1934 Cc = general_compression_factor # noqa: N806
1935 Cc **= C / Cmaxv # noqa: N806
1936 C = C * (1 - blend) + (C * Cc) * blend # noqa: N806
1937 if blendmode == "ICtCp":
1938 I, Cp, Ct = [ # noqa: N806
1939 v / 100.0 for v in colormath.LCHab2Lab(L, C, H)
1940 ]
1941 XYZ = colormath.ICtCp2XYZ(I, Ct, Cp, eotf=eotf) # noqa: N806
1942 X, Y, Z = (v / maxv for v in XYZ) # noqa: N806
1943 # Adapt to D50
1944 X, Y, Z = colormath.adapt( # noqa: N806
1945 X, Y, Z, whitepoint_source=rgb_space[1], cat=cat
1946 )
1947 elif blendmode == "DIN99d":
1948 L, a, b = colormath.DIN99dLCH2Lab(L, C, H) # noqa: N806
1949 X, Y, Z = colormath.Lab2XYZ(L, a, b) # noqa: N806
1950 elif blendmode == "IPT":
1951 I, CP, CT = [ # noqa: N806
1952 v / 100.0 for v in colormath.LCHab2Lab(L, C, H)
1953 ]
1954 X, Y, Z = colormath.IPT2XYZ(I, CP, CT) # noqa: N806
1955 # Adapt to D50
1956 X, Y, Z = colormath.adapt( # noqa: N806
1957 X, Y, Z, whitepoint_source=IPT_white_XYZ, cat=cat
1958 )
1959 elif blendmode == "Lpt":
1960 L, p, t = colormath.LCHab2Lab(L, C, H) # noqa: N806
1961 X, Y, Z = colormath.Lpt2XYZ(L, p, t) # noqa: N806
1962 elif blendmode == "XYZ":
1963 Y, x, y = [v / 100.0 for v in colormath.LCHab2Lab(L, C, H)] # noqa: N806
1964 x += wx
1965 y += wy
1966 X, Y, Z = colormath.xyY2XYZ(x, y, Y) # noqa: N806
1967 else:
1968 print(
1969 "CLUT grid point "
1970 f"{int(col_0):d} {int(col_1):d} {int(col_2):d}: blend = 0"
1971 )
1972 # if backward_xicclu and forward_xicclu:
1973 # backward_xicclu((X, Y, Z))
1974 # else:
1975 # HDR_XYZ[row] = (X, Y, Z)
1976 # row += 1
1977 # perc = startperc + math.floor(row / clutres ** 3.0 *
1978 # (90 - startperc))
1979 # if logfile and perc > prevperc:
1980 # logfile.write(f"\r{perc:.0f}%")
1981 # prevperc = perc
1982 # startperc = perc
1983
1984 # if backward_xicclu and forward_xicclu:
1985 # # Get XYZ clipped to display RGB
1986 # backward_xicclu.exit()
1987 # for R, G, B in backward_xicclu.get():
1988 # forward_xicclu((R, G, B))
1989 # forward_xicclu.exit()
1990 # display_XYZ = forward_xicclu.get()
1991 # else:
1992 # display_XYZ = HDR_XYZ
1993 # row = 0
1994 # for a in range(clutres):
1995 # for b in range(clutres):
1996 # itable.clut.append([])
1997 # debugtable0.clut.append([])
1998 # for c in range(clutres):
1999 # if worker and worker.thread_abort:
2000 # if forward_xicclu:
2001 # forward_xicclu.exit()
2002 # if backward_xicclu:
2003 # backward_xicclu.exit()
2004 # raise Exception("aborted")
2005 # X, Y, Z = display_XYZ[row]
2006 itable.clut[-1].append(
2007 [min(max(v * 32768, 0), 65535) for v in (X, Y, Z)]
2008 )
2009 debugtable0.clut[-1].append(
2010 [min(max(v * 65535, 0), 65535) for v in (R, G, B)]
2011 )
2012 if not display_RGB:
2013 debugtable1.clut[-1].append([0, 0, 0])
2014 XYZdisp = display_XYZ[row] if display_XYZ else [0, 0, 0] # noqa: N806
2015 debugtable2.clut[-1].append(
2016 [min(max(v * 65535, 0), 65535) for v in XYZdisp]
2017 )
2018 row += 1
2019 perc = startperc + math.floor(row / clutres**3.0 * (100 - startperc))
2020 if logfile and perc > prevperc:
2021 logfile.write(f"\r{perc:.0f}%")
2022 prevperc = perc
2023 prevperc = startperc = perc = 0
2024
2025 if DEBUG:
2026 print("Num OOG:", oog_count)
2027
2028 if generate_B2A:
2029 if logfile:
2030 logfile.write("\rGenerating PCS-to-device table...\n")
2031
2032 otable.clut = []
2033 count = 0
2034 for R in range(clutres): # noqa: N806
2035 for G in range(clutres): # noqa: N806
2036 otable.clut.append([])
2037 for B in range(clutres): # noqa: N806
2038 RGB = [v * step for v in (R, G, B)] # noqa: N806
2039 X, Y, Z = colormath.RGB2XYZ(*RGB, rgb_space=rgb_space, eotf=eotf) # noqa: N806
2040 if hdr_format == "PQ":
2041 I1, Ct1, Cp1 = colormath.XYZ2ICtCp(X, Y, Z) # noqa: N806
2042 I2 = eetf(I1) # noqa: N806
2043 Ct2, Cp2 = (min(I1 / I2, I2 / I1) * v for v in (Ct1, Cp1)) # noqa: N806
2044 RGB = colormath.ICtCp2RGB(I1, Ct2, Cp2, rgb_space) # noqa: N806
2045 else:
2046 RGB = hlg.XYZ2RGB(X, Y, Z) # noqa: N806
2047 if (
2048 max(X, Y, Z) * 32768 > 65535
2049 or min(X, Y, Z) < 0
2050 or round(Y, 6) > 1
2051 or max(RGB) > 1
2052 or min(RGB) < 0
2053 ):
2054 print(
2055 f"#{count:d}",
2056 "RGB {:.3f} {:.3f} {:.3f}".format(*RGB),
2057 f"XYZ {X:.6f} {Y:.6f} {Z:.6f}",
2058 "not in range [0,1]",
2059 )
2060 otable.clut[-1].append([min(max(v, 0), 1) * 65535 for v in RGB])
2061 count += 1
2062
2063 if logfile:
2064 logfile.write("\n")
2065
2066 if forward_xicclu:
2067 forward_xicclu.exit()
2068 if backward_xicclu:
2069 backward_xicclu.exit()
2070
2071 if hdr_format == "HLG" and black_cdm2:
2072 # Apply black offset
2073 XYZbp = colormath.get_whitepoint(scale=black_cdm2 / float(white_cdm2)) # noqa: N806
2074 if logfile:
2075 logfile.write("Applying black offset...\n")
2076 profile.tags.A2B0.apply_black_offset(
2077 XYZbp, logfile=logfile, thread_abort=worker and worker.thread_abort
2078 )
2079
2080 return profile
2081
2082
2083 def create_synthetic_hlg_clut_profile(
2084 rgb_space: None | str | list | tuple,
2085 description: str,
2086 black_cdm2: float = 0,
2087 white_cdm2: float = 400,
2088 system_gamma: float = 1.2,
2089 ambient_cdm2: float = 5,
2090 maxsignal: float = 1.0,
2091 content_rgb_space: str = "DCI P3",
2092 rolloff: bool = True,
2093 clutres: int = 33,
2094 mode: str = "HSV_ICtCp",
2095 forward_xicclu: None | Xicclu = None,
2096 backward_xicclu: None | Xicclu = None,
2097 generate_B2A: bool = True, # noqa: N803
2098 worker: None | Worker = None,
2099 logfile: None | TextIO = None,
2100 cat: str = "Bradford",
2101 ) -> ICCProfile:
2102 """Create a synthetic cLUT profile with the HLG TRC from a colorspace definition.
2103
2104 mode: The gamut mapping mode when rolling off. Valid values:
2105 "RGB_ICtCp" (default, recommended)
2106 "ICtCp"
2107 "XYZ" (not recommended, unpleasing hue shift)
2108 "HSV" (not recommended, saturation loss)
2109 "RGB" (not recommended, saturation loss, pleasing hue shift)
2110
2111 Args:
2112 rgb_space (None | str | list | tuple): The RGB space to use for
2113 conversion. Defaults to sRGB if not set. If a string is given, it
2114 must be a valid RGB space name. If a list or tuple is given, it
2115 must be in the format (gamma, whitepoint, red, green, blue). The
2116 whitepoint can be a string (e.g. "D50"), a tuple of XYZ
2117 coordinates, or a color temperature in degrees K (float or int).
2118 The gamma should be a float. The RGB primaries red, green, blue
2119 should be lists or tuples of xyY coordinates (only x and y will be
2120 used, so Y can be zero or None).
2121 description (str): The profile description.
2122 black_cdm2 (float, optional): The black level in cd/m2. Defaults to 0.
2123 white_cdm2 (float, optional): The white level in cd/m2. Defaults to
2124 400.
2125 system_gamma (float, optional): The system gamma value. Defaults to
2126 1.2.
2127 ambient_cdm2 (float, optional): The ambient light level in cd/m2.
2128 Defaults to 5.
2129 maxsignal (float, optional): The maximum signal value. Defaults to 1.0.
2130 content_rgb_space (str, optional): The RGB colorspace of the content.
2131 Defaults to "DCI P3".
2132 rolloff (bool, optional): If True, apply roll-off to the cLUT.
2133 Defaults to True.
2134 clutres (int, optional): The resolution of the cLUT. Defaults to 33.
2135 mode (str, optional): The gamut mapping mode when rolling off. Valid
2136 values: "RGB_ICtCp" (default, recommended), "ICtCp", "XYZ" (not
2137 recommended, unpleasing hue shift), "HSV" (not recommended,
2138 saturation loss), "RGB" (not recommended, saturation loss, pleasing
2139 hue shift).
2140 forward_xicclu (Xicclu, optional): An instance of Xicclu for forward
2141 color space conversion. If None, a new instance will be created.
2142 backward_xicclu (Xicclu, optional): An instance of Xicclu for backward
2143 color space conversion. If None, a new instance will be created.
2144 generate_B2A (bool, optional): If True, generate the PCS-to-device
2145 conversion table. Defaults to True.
2146 worker (Worker, optional): A Worker instance for threading support.
2147 Defaults to None.
2148 logfile (TextIO, optional): A file-like object to log progress.
2149 Defaults to None.
2150 cat (str, optional): The chromatic adaptation transform to use.
2151 Defaults to "Bradford".
2152
2153 Returns:
2154 ICCProfile: An ICCProfile object representing the synthetic HLG cLUT
2155 profile.
2156 """
2157 if not rolloff:
2158 raise NotImplementedError("rolloff needs to be True")
2159
2160 return create_synthetic_hdr_clut_profile(
2161 "HLG",
2162 rgb_space,
2163 description,
2164 black_cdm2,
2165 white_cdm2,
2166 0, # Not used for HLG
2167 10000, # Not used for HLG
2168 True, # Not used for HLG
2169 system_gamma,
2170 ambient_cdm2,
2171 maxsignal,
2172 content_rgb_space,
2173 clutres,
2174 mode, # Not used for HLG
2175 1.0, # Sat - Not used for HLG
2176 0.5, # Hue - Not used for HLG
2177 forward_xicclu,
2178 backward_xicclu,
2179 generate_B2A,
2180 worker,
2181 logfile,
2182 cat,
2183 )
2184
2185
2186 def _colord_get_display_profile(
2187 display_no: int = 0, path_only: bool = False, use_cache: bool = True
2188 ) -> None | str | ICCProfile:
2189 """Use a brute force way of getting display profile.
2190
2191 Args:
2192 display_no (int): The display number to query.
2193 path_only (bool, optional): If True, return the profile path as a
2194 string, otherwise return an ICCProfile object.
2195 use_cache (bool, optional): If True, use cached profile if available.
2196
2197 Returns:
2198 None | str | ICCProfile: The display profile path as a string or
2199 an ICCProfile object, or None if no profile is found.
2200 """
2201 edid_ = get_edid(display_no)
2202 device_ids = []
2203 if edid_:
2204 # Try a range of possible device IDs
2205 dife = colord.device_id_from_edid
2206 device_ids = [
2207 dife(edid_, quirk=False, query=True),
2208 dife(edid_, quirk=True, truncate_edid_strings=True),
2209 dife(edid_, quirk=True, use_serial_32=False),
2210 dife(edid_, quirk=True, use_serial_32=False, truncate_edid_strings=True),
2211 dife(edid_, quirk=True),
2212 dife(edid_, quirk=False, truncate_edid_strings=True),
2213 dife(edid_, quirk=False, use_serial_32=False),
2214 dife(edid_, quirk=False, use_serial_32=False, truncate_edid_strings=True),
2215 # Try with manufacturer omitted
2216 dife(edid_, omit_manufacturer=True),
2217 dife(edid_, truncate_edid_strings=True, omit_manufacturer=True),
2218 dife(edid_, use_serial_32=False, omit_manufacturer=True),
2219 dife(
2220 edid_,
2221 use_serial_32=False,
2222 truncate_edid_strings=True,
2223 omit_manufacturer=True,
2224 ),
2225 ]
2226 else:
2227 # Fall back to XrandR name
2228 try:
2229 from DisplayCAL import real_display_size_mm
2230 except ImportError as exception:
2231 warnings.warn(str(exception), Warning, stacklevel=2)
2232 return None
2233 display = real_display_size_mm.get_display(display_no)
2234 if display:
2235 xrandr_name = display.get("xrandr_name")
2236 if xrandr_name:
2237 edid_ = {"monitor_name": xrandr_name}
2238 device_ids = [f"xrandr-{xrandr_name.decode()}"]
2239 elif os.getenv("XDG_SESSION_TYPE") == "wayland":
2240 # Preliminary Wayland support under non-GNOME desktops.
2241 # This still needs a lot of work.
2242 device_ids = colord.get_display_device_ids()
2243 if device_ids and display_no < len(device_ids):
2244 edid_ = {
2245 "monitor_name": device_ids[display_no].split("xrandr-", 1).pop()
2246 }
2247 device_ids = [device_ids[display_no]]
2248 if not edid_:
2249 return None
2250 for device_id in dict.fromkeys(device_ids):
2251 if not device_id:
2252 continue
2253 try:
2254 profile = colord.get_default_profile(device_id)
2255 profile_path = profile.properties.get("Filename")
2256 except colord.CDObjectQueryError:
2257 # Device ID was not found, try next one
2258 continue
2259 except colord.CDError as exception:
2260 warnings.warn(str(exception), Warning, stacklevel=2)
2261 except colord.DBusException as exception:
2262 warnings.warn(str(exception), Warning, stacklevel=2)
2263 else:
2264 if profile_path:
2265 if "hash" in edid_:
2266 colord.device_ids[edid_["hash"]] = device_id
2267 if path_only:
2268 print(
2269 "Got profile from colord for display "
2270 f"{int(display_no):d} ({device_id}):",
2271 profile_path,
2272 )
2273 return profile_path
2274 return ICCProfile(profile_path, use_cache=use_cache)
2275 break
2276 return None
2277
2278
2279 def _ucmm_get_display_profile(
2280 display_no: int, name: str | bytes, path_only: bool = False, use_cache: bool = True
2281 ) -> None | str | ICCProfile:
2282 """Argyll UCMM.
2283
2284 Args:
2285 display_no (int): The display number to query.
2286 name (str | bytes): The display name to search for.
2287 path_only (bool, optional): If True, return the profile path as a
2288 string, otherwise return an ICCProfile object.
2289 use_cache (bool, optional): If True, use cached profile if available.
2290
2291 Returns:
2292 None | str | ICCProfile: The display profile path as a string or
2293 an ICCProfile object, or None if no profile is found.
2294 """
2295 search = []
2296 edid = get_edid(display_no)
2297 if edid:
2298 # Look for matching EDID entry first
2299 search.append((b"EDID", b"0x" + binascii.hexlify(edid["edid"]).upper()))
2300 # Fallback to X11 name
2301 search.append((b"NAME", name))
2302 for path in [XDG_CONFIG_HOME, *XDG_CONFIG_DIRS]:
2303 color_jcnf = os.path.join(path, "color.jcnf")
2304 if not os.path.isfile(color_jcnf):
2305 continue
2306
2307 with open(color_jcnf) as f:
2308 data = json.load(f)
2309 displays = data.get("devices", {}).get("display")
2310 if not isinstance(displays, dict):
2311 continue
2312
2313 # Look for matching entry
2314 for key, value in search:
2315 for item in displays.values():
2316 if not isinstance(item, dict):
2317 continue
2318 if item.get(key) != value:
2319 continue
2320 profile_path = item.get("ICC_PROFILE")
2321 if path_only:
2322 print(
2323 "Got profile from Argyll UCMM for display "
2324 f"{int(display_no):d} ({key} {value}):",
2325 profile_path,
2326 )
2327 return profile_path
2328 return ICCProfile(profile_path, use_cache=use_cache)
2329 return None
2330
2331
2332 def _wcs_get_display_profile(
2333 devicekey: str,
2334 scope: int = WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"],
2335 profile_type: int = COLOR_PROFILE_TYPE["ICC"],
2336 profile_subtype: int = COLOR_PROFILE_SUBTYPE["NONE"],
2337 profile_id: int = 0,
2338 path_only: bool = False,
2339 use_cache: bool = True,
2340 ) -> None | str | ICCProfile:
2341 """Get display profile using WCS API.
2342
2343 Args:
2344 devicekey (str): The device key to query.
2345 scope (int, optional): The scope of the profile management.
2346 profile_type (int, optional): The type of the color profile.
2347 profile_subtype (int, optional): The subtype of the color profile.
2348 profile_id (int, optional): The ID of the color profile.
2349 path_only (bool, optional): If True, return the profile path as a
2350 string, otherwise return an ICCProfile object.
2351 use_cache (bool, optional): If True, use cached profile if available.
2352
2353 Returns:
2354 None | str | ICCProfile: The display profile path as a string or
2355 an ICCProfile object, or None if no profile is found.
2356 """
2357 prof = mscms.get_default_color_profile(
2358 scope, devicekey, profile_type, profile_subtype, profile_id
2359 )
2360 if prof:
2361 if path_only:
2362 return os.path.join(ICCPROFILES[0], prof)
2363 return ICCProfile(prof, use_cache=use_cache)
2364 return None
2365
2366
2367 def _winreg_get_display_profile(
2368 monkey: list,
2369 current_user: bool = False,
2370 path_only: bool = False,
2371 use_cache: bool = True,
2372 advanced_color_active: bool | None = None,
2373 ) -> None | str | ICCProfile:
2374 """Get display profile from Windows registry.
2375
2376 Args:
2377 monkey (list): Registry key path components for the display.
2378 current_user (bool): If True, use HKEY_CURRENT_USER, otherwise
2379 HKEY_LOCAL_MACHINE.
2380 path_only (bool): If True, return the profile path as a string,
2381 otherwise return an ICCProfile object.
2382 use_cache (bool): If True, use cached profile if available.
2383 advanced_color_active (bool | None): Whether the display is currently
2384 in Advanced Color (HDR) mode. If explicitly False, the
2385 ICMProfileAC (Windows HDR Calibration) profile is excluded so the
2386 SDR profile is returned instead. None means unknown (include all).
2387
2388 Returns:
2389 None | str | ICCProfile: The display profile path as a string or
2390 an ICCProfile object, or None if no profile is found.
2391 """
2392 filename = None
2393 filenames = _winreg_get_display_profiles(
2394 monkey,
2395 current_user,
2396 exclude_advanced_color=advanced_color_active is False,
2397 )
2398 if filenames:
2399 # last existing file in the list is active
2400 filename = filenames.pop()
2401 if not filename and not current_user:
2402 # fall back to sRGB
2403 filename = os.path.join(ICCPROFILES[0], "sRGB Color Space Profile.icm")
2404 if filename:
2405 if path_only:
2406 return os.path.join(ICCPROFILES[0], filename)
2407 return ICCProfile(filename, use_cache=use_cache)
2408 return None
2409
2410
2411 def _winreg_get_display_profiles(
2412 monkey: list,
2413 current_user: bool = False,
2414 exclude_advanced_color: bool = False,
2415 ) -> list:
2416 """Get display profile filenames from Windows registry.
2417
2418 Args:
2419 monkey (list): Registry key path components for the display.
2420 current_user (bool): If True, use HKEY_CURRENT_USER, otherwise
2421 HKEY_LOCAL_MACHINE.
2422 exclude_advanced_color (bool): If True, skip profiles stored under
2423 ICMProfileAC (the Windows HDR Calibration / Advanced Color profile
2424 slot). Pass True when the display is not currently in HDR mode so
2425 the SDR profile is used instead.
2426
2427 Returns:
2428 list: List of profile filenames.
2429 """
2430 filenames = []
2431 try:
2432 if current_user and sys.getwindowsversion() >= (6,):
2433 # Vista / Windows 7 ONLY
2434 # User has to place a check in 'use my settings for this device'
2435 # in the color management control panel at least once to cause
2436 # this key to be created, otherwise it won't exist
2437 subkey = "\\".join(
2438 [
2439 "Software",
2440 "Microsoft",
2441 "Windows NT",
2442 "CurrentVersion",
2443 "ICM",
2444 "ProfileAssociations",
2445 "Display",
2446 *monkey,
2447 ]
2448 )
2449 key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, subkey)
2450 else:
2451 subkey = "\\".join(
2452 ["SYSTEM", "CurrentControlSet", "Control", "Class", *monkey]
2453 )
2454 key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey)
2455 numsubkeys, numvalues, mtime = winreg.QueryInfoKey(key)
2456 for i in range(numvalues):
2457 name, value, type_ = winreg.EnumValue(key, i)
2458 if name not in ["ICMProfile", "ICMProfileAC"] or not value:
2459 continue
2460 if name == "ICMProfileAC" and exclude_advanced_color:
2461 continue
2462
2463 if type_ == winreg.REG_BINARY:
2464 # Win2k/XP
2465 # convert to list of strings
2466 value = value.decode("utf-16").split("\0")
2467 elif type_ == winreg.REG_MULTI_SZ:
2468 # Vista / Windows 7
2469 # nothing to be done, _winreg returns a list of strings
2470 pass
2471 if not isinstance(value, list):
2472 value = [value]
2473 while "" in value:
2474 value.remove("")
2475 filenames.extend(value)
2476 winreg.CloseKey(key)
2477 except OSError as exception:
2478 if exception.args[0] == 2:
2479 # Key does not exist
2480 pass
2481 else:
2482 raise
2483 return [
2484 filename
2485 for filename in filenames
2486 if os.path.isfile(os.path.join(ICCPROFILES[0], filename))
2487 ]
2488
2489
2490 def get_display_profile(
2491 display_no: int = 0,
2492 x_hostname: None | str = None,
2493 x_display: None | str = None,
2494 x_screen: None | int = None,
2495 path_only: bool = False,
2496 devicekey: None | str = None,
2497 use_active_display_device: bool = True,
2498 use_registry: bool = True,
2499 ) -> None | str | ICCProfile:
2500 """Return ICC Profile for display n or None.
2501
2502 Args:
2503 display_no (int, optional): The display number to query. Defaults to 0.
2504 x_hostname (str, optional): The X server hostname.
2505 x_display (str, optional): The X display name.
2506 x_screen (int, optional): The X screen number.
2507 path_only (bool, optional): If True, return the profile path as a
2508 string, otherwise return an ICCProfile object.
2509 devicekey (None | str, optional): The device key to query. If None,
2510 the active display device will be used.
2511 use_active_display_device (bool, optional): If True, use the active
2512 display device, otherwise use the first display device.
2513 use_registry (bool, optional): If True, use the Windows registry to
2514 get the display profile.
2515
2516 Returns:
2517 None | str | ICCProfile: The display profile path as a string or
2518 an ICCProfile object, or None if no profile is found.
2519 """
2520 if sys.platform == "win32":
2521 return get_display_profile_windows(
2522 display_no, path_only, devicekey, use_active_display_device, use_registry
2523 )
2524 if sys.platform == "darwin":
2525 return get_display_profile_macos(display_no, path_only)
2526 return get_display_profile_linux(
2527 display_no, x_hostname, x_display, x_screen, path_only
2528 )
2529
2530
2531 def get_display_profile_windows(
2532 display_no: int = 0,
2533 path_only: bool = False,
2534 devicekey: None | str = None,
2535 use_active_display_device: bool = True,
2536 use_registry: bool = True,
2537 ) -> None | str | ICCProfile:
2538 """Return ICC Profile for the given display under Windows.
2539
2540 Args:
2541 display_no (int): The display number to query.
2542 path_only (bool, optional): If True, return the profile path as a
2543 string, otherwise return an ICCProfile object.
2544 devicekey (None | str, optional): The device key to query. If None, the
2545 active display device will be used.
2546 use_active_display_device (bool, optional): If True, use the active
2547 display device, otherwise use the first display device.
2548 use_registry (bool, optional): If True, use the Windows registry to
2549 get the display profile.
2550
2551 Raises:
2552 ImportError: If pywin32 is not available.
2553
2554 Returns:
2555 None | str | ICCProfile: The display profile path as a string or
2556 an ICCProfile object, or None if no profile is found.
2557 """
2558 profile = None
2559 if "win32api" not in sys.modules:
2560 raise ImportError("pywin32 not available")
2561 gdi_device_name = None
2562 if not devicekey:
2563 # The ordering will work as long as Argyll continues using
2564 # EnumDisplayMonitors
2565 monitors = util_win.get_real_display_devices_info()
2566 moninfo = monitors[display_no]
2567 gdi_device_name = moninfo["Device"]
2568 if not mscms and not devicekey:
2569 # Via GetICMProfile. Sucks royally in a multi-monitor setup
2570 # where one monitor is disabled, because it'll always get
2571 # the profile of the first monitor regardless if that is the active
2572 # one or not. Yuck. Also, in this case it does not reflect runtime
2573 # changes to profile assignments. Double yuck.
2574 buflen = ctypes.c_ulong(260)
2575 dc = win32gui.CreateDC(moninfo["Device"], None, None)
2576 try:
2577 buf = ctypes.create_unicode_buffer(buflen.value)
2578 if ctypes.windll.gdi32.GetICMProfileW(
2579 dc,
2580 ctypes.byref(buflen),
2581 ctypes.byref(buf), # WCHARs
2582 ):
2583 if path_only:
2584 profile = buf.value
2585 else:
2586 profile = ICCProfile(buf.value, use_cache=True)
2587 finally:
2588 win32gui.DeleteDC(dc)
2589 else:
2590 if devicekey:
2591 device = None
2592 elif use_active_display_device:
2593 # This would be the correct way. Unfortunately that is not
2594 # what other apps (or Windows itself) do.
2595 device = util_win.get_active_display_device(moninfo["Device"])
2596 else:
2597 # This is wrong, but it's what other apps use. Matches
2598 # GetICMProfile sucky behavior i.e. should return the same
2599 # profile, but atleast reflects runtime changes to profile
2600 # assignments.
2601 device = util_win.get_first_display_device(moninfo["Device"])
2602 if device:
2603 devicekey = device.DeviceKey
2604 if devicekey:
2605 if mscms:
2606 # Via WCS
2607 if util_win.per_user_profiles_isenabled(devicekey=devicekey):
2608 scope = WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"]
2609 else:
2610 scope = WCS_PROFILE_MANAGEMENT_SCOPE["SYSTEM_WIDE"]
2611 if not use_registry:
2612 # NOTE: WcsGetDefaultColorProfile causes the whole system
2613 # to hitch if the profile of the active display device is
2614 # queried. Windows bug?
2615 return _wcs_get_display_profile(
2616 str(devicekey), scope, path_only=path_only
2617 )
2618 else:
2619 scope = None
2620 # Via registry
2621 monkey = devicekey.split("\\")[-2:] # pun totally intended
2622 # Current user scope
2623 current_user = scope == WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"]
2624 # Detect Advanced Color (HDR) state so we can skip the ICMProfileAC
2625 # entry when the display is in SDR mode (issue #627).
2626 if gdi_device_name is None:
2627 gdi_device_name = util_win.get_gdi_device_name_for_devicekey(devicekey)
2628 advanced_color_active = (
2629 util_win.is_advanced_color_enabled(gdi_device_name)
2630 if gdi_device_name
2631 else None
2632 )
2633 if current_user:
2634 profile = _winreg_get_display_profile(
2635 monkey,
2636 True,
2637 path_only=path_only,
2638 advanced_color_active=advanced_color_active,
2639 )
2640 else:
2641 # System scope
2642 profile = _winreg_get_display_profile(
2643 monkey,
2644 path_only=path_only,
2645 advanced_color_active=advanced_color_active,
2646 )
2647
2648 return profile
2649
2650
2651 def get_display_profile_macos(
2652 display_no: int = 0,
2653 path_only: bool = False,
2654 ) -> None | str | ICCProfile:
2655 """Return ICC Profile for the given display under macOS.
2656
2657 Args:
2658 display_no (int, optional): The display number to query. Defaults to 0.
2659 path_only (bool, optional): If True, return the profile path as a
2660 string, otherwise return an ICCProfile object.
2661
2662 Raises:
2663 OSError: If there is an error executing the AppleScript command.
2664
2665 Returns:
2666 None | str | ICCProfile: The display profile path as a string or
2667 an ICCProfile object, or None if no profile is found.
2668 """
2669 from DisplayCAL.util_mac import osascript
2670
2671 if intlist(platform.mac_ver()[0].split(".")) >= [10, 6]:
2672 options = ["Image Events"]
2673 else:
2674 options = ["ColorSyncScripting"]
2675
2676 for option in options:
2677 # applescript: one-based index
2678 applescript = [
2679 f'tell app "{option}"',
2680 "set displayProfile to location of display profile of "
2681 f"display {int(display_no + 1):d}",
2682 "return POSIX path of displayProfile",
2683 "end tell",
2684 ]
2685 retcode, output, errors = osascript(applescript)
2686 if retcode == 0 and output.strip():
2687 filename = output.strip("\n").decode(FS_ENC)
2688 profile = filename if path_only else ICCProfile(filename, use_cache=True)
2689 elif errors.strip():
2690 raise OSError(errors.strip())
2691
2692 return profile
2693
2694
2695 def get_display_profile_linux(
2696 display_no: int = 0,
2697 x_hostname: None | str = None,
2698 x_display: None | int = None,
2699 x_screen: None | int = None,
2700 path_only: bool = False,
2701 ) -> None | str | ICCProfile:
2702 """Return ICC Profile for the given display under Linux.
2703
2704 Args:
2705 display_no (int): The display number to query.
2706 x_hostname (str, optional): The X server hostname.
2707 x_display (int, optional): The X display number.
2708 x_screen (int, optional): The X screen number.
2709 path_only (bool, optional): If True, return the profile path as a
2710 string, otherwise return an ICCProfile object.
2711
2712 Returns:
2713 None | str | ICCProfile: The display profile path as a string or
2714 an ICCProfile object, or None if no profile is found.
2715 """
2716 options = ["_ICC_PROFILE"]
2717 try:
2718 from DisplayCAL import real_display_size_mm
2719 except ImportError as exception:
2720 warnings.warn(str(exception), Warning, stacklevel=2)
2721 display = get_display()
2722 else:
2723 display = real_display_size_mm.get_x_display(display_no)
2724 if display:
2725 if x_hostname is None:
2726 x_hostname = display[0]
2727 if x_display is None:
2728 x_display = display[1]
2729 if x_screen is None:
2730 x_screen = display[2]
2731 x_display_name = f"{x_hostname}:{x_display}.{x_screen}"
2732 for option in options:
2733 # Linux
2734 # Try colord
2735 if colord.which("colormgr") and (
2736 profile := (_colord_get_display_profile(display_no, path_only=path_only))
2737 ):
2738 return profile
2739 if path_only:
2740 # No way to figure out the profile path from X atom, so use
2741 # Argyll's UCMM if libcolordcompat.so is not present
2742 if dlopen("libcolordcompat.so"):
2743 # UCMM configuration might be stale, ignore
2744 return None
2745 return _ucmm_get_display_profile(display_no, x_display_name, path_only)
2746 # Try XrandR
2747 if (
2748 xrandr
2749 and real_display_size_mm
2750 and option == "_ICC_PROFILE"
2751 and None not in (x_hostname, x_display, x_screen)
2752 ):
2753 with xrandr.XDisplay(x_display_name) as display:
2754 if DEBUG:
2755 print("Using XrandR")
2756 for i, atom_id in enumerate(
2757 [
2758 real_display_size_mm.get_x_icc_profile_output_atom_id(
2759 display_no
2760 ),
2761 real_display_size_mm.get_x_icc_profile_atom_id(display_no),
2762 ]
2763 ):
2764 if not atom_id:
2765 continue
2766 if i == 0:
2767 meth = display.get_output_property
2768 what = real_display_size_mm.get_xrandr_output_xid(display_no)
2769 else:
2770 meth = display.get_window_property
2771 what = display.root_window(0)
2772 try:
2773 window_property = meth(what, atom_id)
2774 except ValueError as exception:
2775 warnings.warn(str(exception), Warning, stacklevel=2)
2776 else:
2777 if window_property and (
2778 profile := ICCProfile(
2779 b"".join(
2780 bytes(chr(n), "utf-8") for n in window_property
2781 ),
2782 use_cache=True,
2783 )
2784 ):
2785 return profile
2786 if DEBUG:
2787 if i == 0:
2788 print("Couldn't get _ICC_PROFILE XrandR output property")
2789 print("Using X11")
2790 else:
2791 print("Couldn't get _ICC_PROFILE X atom")
2792 return None
2793
2794 # Read up to 8 MB of any X properties
2795 if DEBUG:
2796 print("Using xprop")
2797 xprop = which("xprop")
2798 if not xprop:
2799 return None
2800 atom = "{}{}".format(option, "" if display_no == 0 else f"_{display_no}")
2801 tgt_proc = sp.Popen(
2802 [
2803 xprop,
2804 "-display",
2805 f"{x_hostname}:{x_display}.{x_screen}",
2806 "-len",
2807 "8388608",
2808 "-root",
2809 "-notype",
2810 atom,
2811 ],
2812 stdin=sp.PIPE,
2813 stdout=sp.PIPE,
2814 stderr=sp.PIPE,
2815 )
2816 stdout, stderr = [data.strip(b"\n") for data in tgt_proc.communicate()]
2817 if stdout:
2818 raw = [item.strip() for item in stdout.split("=")]
2819 if raw[0] == atom and len(raw) == 2:
2820 binary_data = "".join([chr(int(part)) for part in raw[1].split(", ")])
2821 profile = ICCProfile(binary_data, use_cache=True)
2822 elif stderr and tgt_proc.wait() != 0:
2823 raise OSError(stderr)
2824 if profile:
2825 break
2826 return profile
2827
2828
2829 def _wcs_set_display_profile(
2830 devicekey: str,
2831 profile_name: str,
2832 scope: int = WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"],
2833 ) -> bool:
2834 """Set the current default WCS color profile for the given device.
2835
2836 If the device is a display, this will also set its video card gamma ramps
2837 to linear* if the given profile is the display's current default profile
2838 and Windows calibration management isn't enabled.
2839
2840 Note that the profile needs to have been already installed.
2841
2842 * 0..65535 will get mapped to 0..65280, which is a Windows bug.
2843
2844 Args:
2845 devicekey (str): The device key of the display.
2846 profile_name (str): The name of the profile to be set.
2847 scope (int): The scope of the profile management, either
2848 WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"] or
2849 WCS_PROFILE_MANAGEMENT_SCOPE["SYSTEM_WIDE"].
2850
2851 Returns:
2852 bool: True if the profile was set successfully, False otherwise.
2853 """
2854 mscms.associate_color_profile_with_device(scope, profile_name, str(devicekey))
2855 profiles = mscms.get_device_color_profile_list(scope, str(devicekey))
2856 return profile_name in profiles
2857
2858
2859 def _wcs_unset_display_profile(
2860 devicekey: str,
2861 profile_name: str,
2862 scope: int = WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"],
2863 ) -> bool:
2864 """Unset the current default WCS color profile for the given device.
2865
2866 If the device is a display, this will also set its video card gamma ramps
2867 to linear* if the given profile is the display's current default profile
2868 and Windows calibration management isn't enabled.
2869
2870 Note that the profile needs to have been already installed.
2871
2872 * 0..65535 will get mapped to 0..65280, which is a Windows bug.
2873
2874 Args:
2875 devicekey (str): The device key of the display.
2876 profile_name (str): The name of the profile to be unset.
2877 scope (int): The scope of the profile management, either
2878 WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"] or
2879 WCS_PROFILE_MANAGEMENT_SCOPE["SYSTEM_WIDE"].
2880
2881 Returns:
2882 bool: True if the profile was unset successfully, False otherwise.
2883 """
2884 mscms.disassociate_color_profile_from_device(scope, profile_name, str(devicekey))
2885 profiles = mscms.get_device_color_profile_list(scope, str(devicekey))
2886 return profile_name not in profiles
2887
2888
2889 def set_display_profile(
2890 profile_name: str,
2891 display_no: int = 0,
2892 devicekey: None | str = None,
2893 use_active_display_device: bool = True,
2894 ) -> bool:
2895 """Set the current default WCS color profile for the given device.
2896
2897 Args:
2898 profile_name (str): The name of the profile to be set.
2899 display_no (int): The display number to set the profile for.
2900 devicekey (str): The device key of the display.
2901 use_active_display_device (bool): Whether to use the active display
2902 device.
2903
2904 Returns:
2905 bool: True if the profile was set successfully, False otherwise.
2906 """
2907 # Currently only implemented for Windows.
2908 # The profile to be assigned has to be already installed!
2909 if not devicekey:
2910 device = util_win.get_display_device(display_no, use_active_display_device)
2911 if not device:
2912 return False
2913 devicekey = device.DeviceKey
2914 if mscms:
2915 if util_win.per_user_profiles_isenabled(devicekey=devicekey):
2916 scope = WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"]
2917 else:
2918 scope = WCS_PROFILE_MANAGEMENT_SCOPE["SYSTEM_WIDE"]
2919 return _wcs_set_display_profile(str(devicekey), profile_name, scope)
2920 # TODO: Implement for XP
2921 return False
2922
2923
2924 def unset_display_profile(
2925 profile_name: str,
2926 display_no: int = 0,
2927 devicekey: None | str = None,
2928 use_active_display_device: bool = True,
2929 ) -> bool:
2930 """Unset the current default WCS color profile for the given device.
2931
2932 If the device is a display, this will also set its video card gamma ramps
2933 to linear* if the given profile is the display's current default profile
2934 and Windows calibration management isn't enabled.
2935
2936 Note that the profile needs to have been already installed.
2937 * 0..65535 will get mapped to 0..65280, which is a Windows bug.
2938
2939 Args:
2940 profile_name (str): The name of the profile to be unset.
2941 display_no (int, optional): The display number to unset the profile
2942 for. Defaults to 0.
2943 devicekey (None | str): The device key of the display. Defatults to
2944 None, which means the active display device will be used.
2945 use_active_display_device (bool, optional): Whether to use the active
2946 display device. Defaults to True.
2947
2948 Returns:
2949 bool: True if the profile was unset successfully, False otherwise.
2950 """
2951 # Currently only implemented for Windows.
2952 # The profile to be unassigned has to be already installed!
2953 if not devicekey:
2954 device = util_win.get_display_device(display_no, use_active_display_device)
2955 if not device:
2956 return False
2957 devicekey = device.DeviceKey
2958 if mscms:
2959 if util_win.per_user_profiles_isenabled(devicekey=devicekey):
2960 scope = WCS_PROFILE_MANAGEMENT_SCOPE["CURRENT_USER"]
2961 else:
2962 scope = WCS_PROFILE_MANAGEMENT_SCOPE["SYSTEM_WIDE"]
2963 return _wcs_unset_display_profile(str(devicekey), profile_name, scope)
2964 # TODO: Implement for XP
2965 return False
2966
2967
2968 def _blend_blackpoint(
2969 row: tuple[float, float, float],
2970 bp_in: None | tuple,
2971 bp_out: None | tuple,
2972 wp: None | float | str | list | tuple = None,
2973 use_bpc: bool = False,
2974 weight: bool = False,
2975 ) -> tuple[float, float, float]:
2976 """Blend black point compensation or offset into XYZ values.
2977
2978 Args:
2979 row (tuple): A tuple containing XYZ values.
2980 bp_in (tuple): Input black point (X, Y, Z).
2981 bp_out (tuple): Output black point (X, Y, Z).
2982 wp (None | float | str | list | tuple, optional): White point, if using
2983 BPC.
2984 use_bpc (bool, optional): Whether to use black point compensation.
2985 weight (bool, optional): Whether to apply weighting.
2986
2987 Returns:
2988 tuple: Adjusted XYZ values after applying black point compensation or
2989 offset.
2990 """
2991 X, Y, Z = row # noqa: N806
2992 if use_bpc:
2993 X, Y, Z = colormath.apply_bpc(X, Y, Z, bp_in, bp_out, wp, weight=weight) # noqa: N806
2994 else:
2995 X, Y, Z = colormath.blend_blackpoint(X, Y, Z, bp_in, bp_out, wp) # noqa: N806
2996 return X, Y, Z
2997
2998
2999 def _mp_apply(
3000 blocks: list,
3001 thread_abort_event: threading.Event,
3002 progress_queue: multiprocessing.Queue,
3003 pcs: str,
3004 fn: Callable,
3005 args: tuple,
3006 D50: None | float | str | list | tuple, # noqa: N803
3007 interp: list,
3008 rinterp: list,
3009 abortmessage: str = "Aborted",
3010 ) -> list:
3011 """Worker for applying function to cLUT.
3012
3013 This should be spawned as a multiprocessing process.
3014
3015 Args:
3016 blocks (list): List of blocks to process.
3017 thread_abort_event (threading.Event): Event to signal abort.
3018 progress_queue (multiprocessing.Queue): Queue for progress updates.
3019 pcs (str): PCS type, either "Lab" or "XYZ".
3020 fn (callable): Function to apply to each block.
3021 args (tuple): Arguments to pass to the function.
3022 D50 (None | float | str | list | tuple): D50 whitepoint.
3023 interp (list): Interpolation functions for each channel.
3024 rinterp (list): Reverse interpolation functions for each channel.
3025 abortmessage (str): Message to return if aborted.
3026
3027 Returns:
3028 list: Processed blocks after applying the function.
3029 """
3030 from DisplayCAL.debughelpers import Info
3031
3032 for interp_tuple in (interp, rinterp):
3033 if interp_tuple:
3034 # Use numpy for speed
3035 interp_list = list(interp_tuple)
3036 for i, ointerp in enumerate(interp_list):
3037 interp_list[i] = colormath.Interp(
3038 ointerp.xp, ointerp.fp, use_numpy=True
3039 )
3040 interp_list[i].lookup = ointerp.lookup
3041 if interp_tuple is interp:
3042 interp = interp_list
3043 else:
3044 rinterp = interp_list
3045 prevperc = 0
3046 count = 0
3047 numblocks = len(blocks)
3048 for block in blocks:
3049 if thread_abort_event and thread_abort_event.is_set():
3050 return Info(abortmessage)
3051 for i, row in enumerate(block):
3052 if interp:
3053 for column, value in enumerate(row):
3054 row[column] = interp[column](value)
3055 if pcs == "Lab":
3056 L, a, b = legacy_PCSLab_uInt16_to_dec(*row) # noqa: N806
3057 X, Y, Z = colormath.Lab2XYZ(L, a, b, D50) # noqa: N806
3058 else:
3059 X, Y, Z = [v / 32768.0 for v in row] # noqa: N806
3060 X, Y, Z = fn((X, Y, Z), *args) # noqa: N806
3061 if pcs == "Lab":
3062 L, a, b = colormath.XYZ2Lab(X, Y, Z, D50) # noqa: N806
3063 row = [
3064 min(max(0, v), 65535) for v in legacy_PCSLab_dec_to_uInt16(L, a, b)
3065 ]
3066 else:
3067 row = [min(max(0, v) * 32768.0, 65535) for v in (X, Y, Z)]
3068 if rinterp:
3069 for column, value in enumerate(row):
3070 row[column] = rinterp[column](value)
3071 block[i] = row
3072 count += 1.0
3073 perc = round(count / numblocks * 100)
3074 if progress_queue and perc > prevperc:
3075 progress_queue.put(perc - prevperc)
3076 prevperc = perc
3077 return blocks
3078
3079
3080 def _mp_apply_black(
3081 blocks: list,
3082 thread_abort_event: threading.Event,
3083 progress_queue: multiprocessing.Queue,
3084 pcs: str,
3085 bp: tuple[float, float, float],
3086 bp_out: tuple[float, float, float],
3087 wp: None | float | str | list | tuple,
3088 use_bpc: bool,
3089 weight: bool,
3090 D50: None | float | str | list | tuple, # noqa: N803
3091 interp: list,
3092 rinterp: list,
3093 abortmessage: str = "Aborted",
3094 ) -> list:
3095 """Worker for applying black point compensation or offset.
3096
3097 This should be spawned as a multiprocessing process.
3098
3099 Args:
3100 blocks (list): List of blocks to process.
3101 thread_abort_event (threading.Event): Event to signal abort.
3102 progress_queue (multiprocessing.Queue): Queue for progress updates.
3103 pcs (str): PCS type, either "Lab" or "XYZ".
3104 bp (tuple): Black point to apply.
3105 bp_out (tuple): Black point output.
3106 wp (None | float | str | list | tuple): White point, if using BPC.
3107 use_bpc (bool): Whether to use black point compensation.
3108 weight (bool): Whether to apply weighting.
3109 D50 (None | float | str | list | tuple): D50 whitepoint.
3110 interp (list): Interpolation functions for each channel.
3111 rinterp (list): Reverse interpolation functions for each channel.
3112 abortmessage (str): Message to return if aborted.
3113
3114 Returns:
3115 list: Processed blocks after applying black point compensation or
3116 offset.
3117 """
3118 return _mp_apply(
3119 blocks,
3120 thread_abort_event,
3121 progress_queue,
3122 pcs,
3123 _blend_blackpoint,
3124 (bp, bp_out, wp if use_bpc else None, use_bpc, weight),
3125 D50,
3126 interp,
3127 rinterp,
3128 abortmessage,
3129 )
3130
3131
3132 def _mp_hdr_tonemap(
3133 HDR_XYZ: list, # noqa: N803
3134 thread_abort_event: threading.Event,
3135 progress_queue: multiprocessing.Queue,
3136 rgb_space: None | str | list | tuple,
3137 maxv: float,
3138 sat: float,
3139 cat: str = "Bradford",
3140 ) -> list:
3141 """Worker for HDR tonemapping.
3142
3143 This should be spawned as a multiprocessing process
3144
3145 Args:
3146 HDR_XYZ (list): List of HDR XYZ tuples.
3147 thread_abort_event (threading.Event): Event to signal abort.
3148 progress_queue (multiprocessing.Queue): Queue for progress updates.
3149 rgb_space (None | str | list | tuple): The RGB space to use for
3150 conversion. Defaults to sRGB if not set. If a string is given, it
3151 must be a valid RGB space name. If a list or tuple is given, it
3152 must be in the format (gamma, whitepoint, red, green, blue). The
3153 whitepoint can be a string (e.g. "D50"), a tuple of XYZ
3154 coordinates, or a color temperature in degrees K (float or int).
3155 The gamma should be a float. The RGB primaries red, green, blue
3156 should be lists or tuples of xyY coordinates (only x and y will be
3157 used, so Y can be zero or None).
3158 maxv (float): Maximum value for normalization.
3159 sat (float): Saturation factor for ICtCp.
3160 cat (str): Chromatic adaptation transform to use, defaults to
3161 "Bradford".
3162
3163 Returns:
3164 list: Processed HDR XYZ tuples.
3165 """
3166 prevperc = 0
3167 amount = len(HDR_XYZ)
3168 dI = 0 # noqa: N806
3169 dI_max = 0 # noqa: N806
3170 dC = 0 # noqa: N806
3171 dC_max = 0 # noqa: N806
3172 I_reduced_count = 0 # noqa: N806
3173 its_hi = 0 # Highest number pf iterations seen per color
3174 for i, (RGB_in, ICtCp_XYZ, RGB_ICtCp_XYZ) in enumerate(HDR_XYZ): # noqa: N806
3175 if thread_abort_event and thread_abort_event.is_set():
3176 return [False]
3177 is_neutral = all(v == RGB_in[0] for v in RGB_in)
3178 for j, XYZ in enumerate((ICtCp_XYZ, RGB_ICtCp_XYZ)): # noqa: N806
3179 if j == 0 and (sat == 1 or ICtCp_XYZ == RGB_ICtCp_XYZ):
3180 # Set ICtCp_XYZ to the same object as RGB_ICtCp_XYZ which we
3181 # are going to change in-place in the next iteration of the loop
3182 # so that at the end of this loop, both will point to the same
3183 # changed data
3184 ICtCp_XYZ = RGB_ICtCp_XYZ # noqa: N806
3185 continue
3186 X, Y, Z = XYZ # noqa: N806
3187 H = None # noqa: N806
3188 its = 10000 # Remaining iterations (limit)
3189 while not is_neutral and its:
3190 X_D50, Y_D50, Z_D50 = colormath.adapt( # noqa: N806
3191 *(v / maxv for v in (X, Y, Z)),
3192 whitepoint_source=rgb_space[1],
3193 cat=cat,
3194 )
3195 negative_clip = min(X_D50, Y_D50, Z_D50) < 0
3196 positive_clip = (
3197 round(X_D50, 4) > 0.9642 or Y_D50 > 1 or round(Z_D50, 4) > 0.8249
3198 )
3199 if not (negative_clip or positive_clip):
3200 break
3201 if H is None:
3202 # Record hue angle
3203 H = colormath.RGB2HSV(*RGB_in)[0] # noqa: N806
3204 # This is the initial intensity, and hue + saturation
3205 I, Ct, Cp = colormath.XYZ2ICtCp(X, Y, Z) # noqa: N806
3206 Io = I # noqa: N806
3207 Co = colormath.Lab2LCHab(I, Ct, Cp)[1] # noqa: N806
3208 # Desaturate
3209 Ct *= 0.99 # noqa: N806
3210 Cp *= 0.99 # noqa: N806
3211 # Update XYZ
3212 X, Y, Z = colormath.ICtCp2XYZ(I, Ct, Cp) # noqa: N806
3213 if Y > XYZ[1]: # noqa: SIM300
3214 # Desaturating CtCp increases Y!
3215 # As we desaturate different amounts per color,
3216 # restore initial Y if lower than adjusted Y
3217 # to keep luminance relation
3218 X, Y, Z = (v / Y * XYZ[1] for v in (X, Y, Z)) # noqa: N806
3219 I, Ct, Cp = colormath.XYZ2ICtCp(X, Y, Z) # noqa: N806
3220 its -= 1
3221 if H is not None and round(Io - I, 4):
3222 # Intensity was reduced by >= 0.0001, gather statistics
3223 C = colormath.Lab2LCHab(I, Ct, Cp)[1] # noqa: N806
3224 dI += Io - I # noqa: N806
3225 dI_max = max(dI_max, Io - I) # noqa: N806
3226 dC += Co - C # noqa: N806
3227 dC_max = max(dC_max, Co - C) # noqa: N806
3228 I_reduced_count += 1 # noqa: N806
3229 if not its:
3230 # Max iterations exceeded, print diagnostics
3231 # XXX: This should not happen (testing OK)
3232 oX_D50, oY_D50, oZ_D50 = colormath.adapt( # noqa: N806
3233 *(v / maxv for v in XYZ), whitepoint_source=rgb_space[1], cat=cat
3234 )
3235 X_D50, Y_D50, Z_D50 = colormath.adapt( # noqa: N806
3236 *(v / maxv for v in (X, Y, Z)),
3237 whitepoint_source=rgb_space[1],
3238 cat=cat,
3239 )
3240 print(
3241 "Reached iteration limit, XYZ "
3242 f"{oX_D50:.4f} {oY_D50:.4f} {oZ_D50:.4f} -> "
3243 f"{X_D50:.4f} {Y_D50:.4f} {Z_D50:.4f}"
3244 )
3245 its_hi = max(its_hi, 10000 - its)
3246 XYZ[:] = X, Y, Z
3247 HDR_XYZ[i] = (RGB_in, ICtCp_XYZ, RGB_ICtCp_XYZ)
3248 perc = round((i + 1.0) / amount * 50)
3249 if progress_queue and perc > prevperc:
3250 progress_queue.put(perc - prevperc)
3251 prevperc = perc
3252 if I_reduced_count:
3253 # Intensity was reduced, print informational statistics
3254 print(
3255 f"Max iterations {int(its_hi):d} "
3256 f"dI avg {dI / I_reduced_count:.4f} "
3257 f"max {dI_max:.4f} "
3258 f"dC avg {dC / I_reduced_count:.4f} "
3259 f"max {dC_max:.4f}"
3260 )
3261 elif its_hi:
3262 print("Max iterations", its_hi)
3263 return HDR_XYZ
3264
3265
3266 def hexrepr(bytestring: bytes, mapping: None | dict = None) -> str:
3267 """Generate hex representation of a bytes instance.
3268
3269 Args:
3270 bytestring (bytes): The bytes to convert.
3271 mapping (dict): A dictionary to map the ASCII representation to
3272 a string.
3273
3274 Returns:
3275 str: The hex representation of the bytes.
3276 """
3277 hex_repr = (b"0x%s" % binascii.hexlify(bytestring).upper()).decode()
3278 ascii_repr = re.sub(b"[^\x20-\x7e]", b"", bytestring)
3279 if ascii_repr == bytestring:
3280 hex_repr += f" '{ascii_repr.decode()}'"
3281 if mapping:
3282 value = mapping.get(ascii_repr)
3283 if value:
3284 hex_repr = f"{hex_repr} {value}"
3285 return hex_repr
3286
3287
3288 def dateTimeNumber(binary_string: bytes) -> datetime.datetime: # noqa: N802
3289 """Convert a 12-byte hex representation to a datetime object.
3290
3291 Byte
3292 Offset Content Encoded as...
3293 0..1 number of the year (actual year, e.g. 1994) uInt16Number
3294 2..3 number of the month (1-12) uInt16Number
3295 4..5 number of the day of the month (1-31) uInt16Number
3296 6..7 number of hours (0-23) uInt16Number
3297 8..9 number of minutes (0-59) uInt16Number
3298 10..11 number of seconds (0-59) uInt16Number
3299
3300 Args:
3301 binary_string (bytes): A 12 character long bytes value representing a
3302 datetime value.
3303
3304 Returns:
3305 datetime: The datetime object represented by the hex.
3306 """
3307 Y, m, d, H, M, S = [ # noqa: N806
3308 uInt16Number(chunk)
3309 for chunk in (
3310 binary_string[:2],
3311 binary_string[2:4],
3312 binary_string[4:6],
3313 binary_string[6:8],
3314 binary_string[8:10],
3315 binary_string[10:12],
3316 )
3317 ]
3318 return datetime.datetime(*(Y, m, d, H, M, S))
3319
3320
3321 def dateTimeNumber_tohex(dt: datetime.datetime) -> bytes: # noqa: N802
3322 """Convert a datetime object to a 12-byte hex representation.
3323
3324 Args:
3325 dt (datetime): The datetime object to convert.
3326
3327 Returns:
3328 bytes: The 12-byte hex representation of the datetime.
3329 """
3330 data = [uInt16Number_tohex(n) for n in dt.timetuple()[:6]]
3331 return b"".join(data)
3332
3333
3334 def s15Fixed16Number(binaryString: bytes) -> float: # noqa: N802, N803
3335 """Convert a 4-byte hex representation to a float.
3336
3337 Args:
3338 binaryString (bytes): The 4-byte hex representation.
3339
3340 Returns:
3341 float: The number represented by the hex.
3342 """
3343 return struct.unpack(">i", binaryString)[0] / 65536.0
3344
3345
3346 def s15Fixed16Number_tohex(num: int) -> bytes: # noqa: N802
3347 """Convert a number to a 4-byte hex representation.
3348
3349 Args:
3350 num (int): The number to convert.
3351
3352 Returns:
3353 bytes: The 4-byte hex representation of the number.
3354 """
3355 return struct.pack(">i", round(num * 65536))
3356
3357
3358 def s15f16_is_equal(a: bytes, b: bytes, quantizer: None | Callable = None) -> bool:
3359 """Compare two s15Fixed16Number values.
3360
3361 Args:
3362 a (bytes): First value.
3363 b (bytes): Second value.
3364 quantizer (Optional[callable]): A callable to quantize the values.
3365 Defaults to None.
3366
3367 Returns:
3368 bool: True if the values are equal, False otherwise.
3369 """
3370 if quantizer is None:
3371
3372 def quantizer(v: int) -> float:
3373 """Default quantizer for s15Fixed16Number.
3374
3375 Args:
3376 v (int): The value to quantize.
3377
3378 Returns:
3379 float: The quantized value.
3380 """
3381 return s15Fixed16Number(s15Fixed16Number_tohex(v))
3382
3383 return colormath.is_equal(a, b, quantizer)
3384
3385
3386 def u16Fixed16Number(binaryString: bytes) -> int: # noqa: N802, N803
3387 """Convert a 2-byte hex representation to a number.
3388
3389 Args:
3390 binaryString (bytes): The 2-byte hex representation.
3391
3392 Returns:
3393 int: The number represented by the hex.
3394 """
3395 return struct.unpack(">I", binaryString)[0] / 65536.0
3396
3397
3398 def u16Fixed16Number_tohex(num: int) -> bytes: # noqa: N802
3399 """Convert a number to a 2-byte hex representation.
3400
3401 Args:
3402 num (int): The number to convert.
3403
3404 Returns:
3405 bytes: The 2-byte hex representation of the number.
3406 """
3407 return struct.pack(">I", round(num * 65536) & 0xFFFFFFFF)
3408
3409
3410 def u8Fixed8Number(binaryString: bytes) -> int: # noqa: N802, N803
3411 """Convert a 1-byte hex representation to a number.
3412
3413 Args:
3414 binaryString (bytes): The 1-byte hex representation.
3415
3416 Returns:
3417 int: The number represented by the hex.
3418 """
3419 return struct.unpack(">H", binaryString)[0] / 256.0
3420
3421
3422 def u8Fixed8Number_tohex(num: int) -> bytes: # noqa: N802
3423 """Convert a number to a 1-byte hex representation.
3424
3425 Args:
3426 num (int): The number to convert.
3427
3428 Returns:
3429 bytes: The 1-byte hex representation of the number.
3430 """
3431 return struct.pack(">H", round(num * 256))
3432
3433
3434 def uInt16Number(binaryString: bytes) -> int: # noqa: N802, N803
3435 """Convert a 2-byte hex representation to a number.
3436
3437 Args:
3438 binaryString (bytes): The 2-byte hex representation.
3439
3440 Returns:
3441 int: The number represented by the hex.
3442 """
3443 return struct.unpack(">H", binaryString)[0]
3444
3445
3446 def uInt16Number_tohex(num: int) -> bytes: # noqa: N802
3447 """Convert a number to a 2-byte hex representation.
3448
3449 Args:
3450 num (int): The number to convert.
3451
3452 Returns:
3453 bytes: The 2-byte hex representation of the number.
3454 """
3455 return struct.pack(">H", round(num))
3456
3457
3458 def uInt32Number(binaryString: bytes) -> int: # noqa: N802, N803
3459 """Convert a 4-byte hex representation to a number.
3460
3461 Args:
3462 binaryString (bytes): The 4-byte hex representation.
3463
3464 Returns:
3465 int: The number represented by the hex.
3466 """
3467 return struct.unpack(">I", binaryString)[0]
3468
3469
3470 def uInt32Number_tohex(num: int) -> bytes: # noqa: N802
3471 """Convert a number to a 4-byte hex representation.
3472
3473 Args:
3474 num (int): The number to convert.
3475
3476 Returns:
3477 bytes: The 4-byte hex representation of the number.
3478 """
3479 return struct.pack(">I", round(num))
3480
3481
3482 def uInt64Number(binaryString: bytes) -> int: # noqa: N802, N803
3483 """Convert a 8-byte hex representation to a number.
3484
3485 Args:
3486 binaryString (bytes): The 8-byte hex representation.
3487
3488 Returns:
3489 int: The number represented by the hex.
3490 """
3491 return struct.unpack(">Q", binaryString)[0]
3492
3493
3494 def uInt64Number_tohex(num: int) -> bytes: # noqa: N802
3495 """Convert a number to a 8-byte hex representation.
3496
3497 Args:
3498 num (int): The number to convert.
3499
3500 Returns:
3501 bytes: The 8-byte hex representation of the number.
3502 """
3503 return struct.pack(">Q", round(num))
3504
3505
3506 def uInt8Number(binaryString: bytes) -> int: # noqa: N802, N803
3507 """Convert a 1-byte hex representation to a number.
3508
3509 Args:
3510 binaryString (bytes): The 1-byte hex representation.
3511
3512 Returns:
3513 int: The number represented by the hex.
3514 """
3515 return struct.unpack(">H", b"\0" + binaryString)[0]
3516
3517
3518 def uInt8Number_tohex(num: int) -> bytes: # noqa: N802
3519 """Convert a number to a 1-byte hex representation.
3520
3521 Args:
3522 num (int): The number to convert.
3523
3524 Returns:
3525 bytes: The 1-byte hex representation of the number.
3526 """
3527 return struct.pack(">H", round(num))[1:2]
3528
3529
3530 def videoCardGamma( # noqa: N802
3531 tagData: bytes, # noqa: N803
3532 tagSignature: str, # noqa: N803
3533 ) -> None | VideoCardGammaTableType | VideoCardGammaFormulaType:
3534 """Generate a VideoCardGammaTableType or VideoCardGammaFormulaType tag.
3535
3536 Args:
3537 tagData (bytes): The raw tag data containing the video LUT curves.
3538 tagSignature (str): The signature of the tag, typically "vcgt".
3539
3540 Returns:
3541 None | VideoCardGammaTableType | VideoCardGammaFormulaType: The parsed
3542 tag data as a VideoCardGammaTableType or VideoCardGammaFormulaType
3543 object, or None if the tag type is not recognized.
3544 """
3545 # reserved = uInt32Number(tagData[4:8])
3546 tag_type = uInt32Number(tagData[8:12])
3547 if tag_type == 0: # table
3548 return VideoCardGammaTableType(tagData, tagSignature)
3549 if tag_type == 1: # formula
3550 return VideoCardGammaFormulaType(tagData, tagSignature)
3551 return None
3552
3553
3554 class CRInterpolation:
3555 """Catmull-Rom interpolation.
3556
3557 Curve passes through the points exactly, with neighbouring points
3558 influencing curvature.points[] should be at least 3 points long.
3559
3560 Args:
3561 points (list[float]): A list of points to interpolate. The list should
3562 contain at least 3 points, and each point should be a float value.
3563 """
3564
3565 def __init__(self, points: list[float]) -> None:
3566 self.points = points
3567
3568 def __call__(self, pos: float) -> float:
3569 """Interpolate the value at the given position.
3570
3571 Args:
3572 pos (float): The position to interpolate the value for, in the range
3573 [0, len(points) - 1].
3574
3575 Returns:
3576 float: The interpolated value at the given position.
3577 """
3578 lbound = int(math.floor(pos) - 1)
3579 ubound = int(math.ceil(pos) + 1)
3580 t = pos % 1.0
3581 if abs((lbound + 1) - pos) < 0.0001:
3582 # sitting on a datapoint, so just return that
3583 return self.points[lbound + 1]
3584 if lbound < 0:
3585 p = self.points[: ubound + 1]
3586 # extend to the left linearly
3587 while len(p) < 4:
3588 p.insert(0, p[0] - (p[1] - p[0]))
3589 else:
3590 p = self.points[lbound : ubound + 1]
3591 # extend to the right linearly
3592 while len(p) < 4:
3593 p.append(p[-1] - (p[-2] - p[-1]))
3594 t2 = t * t
3595 return 0.5 * (
3596 (2 * p[1])
3597 + (-p[0] + p[2]) * t
3598 + ((2 * p[0]) - (5 * p[1]) + (4 * p[2]) - p[3]) * t2
3599 + (-p[0] + (3 * p[1]) - (3 * p[2]) + p[3]) * (t2 * t)
3600 )
3601
3602
3603 class ADict(dict):
3604 """Convenience class for dictionary key access via attributes.
3605
3606 Instead of writing aodict[key], you can also write aodict.key
3607 """
3608
3609 def __getattr__(self, name: str) -> Any: # noqa: ANN401
3610 """Get the attribute with the given name.
3611
3612 Args:
3613 name (str): The name of the attribute to get.
3614 """
3615 if name in self:
3616 return self[name]
3617 return self.__getattribute__(name)
3618
3619 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
3620 """Set the attribute with the given name to the given value.
3621
3622 Args:
3623 name (str): The name of the attribute to set.
3624 value (Any): The value to set the attribute to.
3625 """
3626 self[name] = value
3627
3628
3629 class AODict(ADict):
3630 """Convenience class for dictionary key access via attributes."""
3631
3632 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
3633 """Set the attribute with the given name to the given value.
3634
3635 Args:
3636 name (str): The name of the attribute to set.
3637 value (Any): The value to set the attribute to.
3638 """
3639 if name == "_keys":
3640 object.__setattr__(self, name, value)
3641 else:
3642 self[name] = value
3643
3644
3645 class LazyLoadTagAODict(AODict):
3646 """Lazy-load (and parse) tag data on access.
3647
3648 Args:
3649 profile (ICCProfile): The ICC profile this tag dictionary belongs to.
3650 *args: Variable length argument list.
3651 **kwargs: Arbitrary keyword arguments.
3652 """
3653
3654 def __init__(self, profile: ICCProfile, *args, **kwargs) -> None:
3655 self.profile = profile
3656 AODict.__init__(self)
3657
3658 def __getitem__(self, key: str) -> Any: # noqa: ANN401
3659 """Get the item with the given key.
3660
3661 Args:
3662 key (str): The key to get the item for.
3663
3664 Returns:
3665 Any: The item with the given key.
3666 """
3667 tag = AODict.__getitem__(self, key)
3668 if isinstance(tag, ICCProfileTag):
3669 # Return already parsed tag
3670 return tag
3671 # Load and parse tag data
3672 tag_signature = key
3673 type_signature, tag_data_offset, tag_data_size, tag_data = tag
3674 try:
3675 if tag_signature in TAG_SIGNATURE_TO_TAG:
3676 tag = TAG_SIGNATURE_TO_TAG[tag_signature](tag_data, tag_signature)
3677 elif type_signature in TYPE_SIGNATURE_TO_TYPE:
3678 args = tag_data, tag_signature
3679 if type_signature in (b"clrt", b"ncl2"):
3680 args += (self.profile.connectionColorSpace,)
3681 if type_signature == b"ncl2":
3682 args += (self.profile.colorSpace,)
3683 elif type_signature in (b"XYZ ", b"mft2", b"curv", b"MS10", b"pseq"):
3684 args += (self.profile,)
3685 tag = TYPE_SIGNATURE_TO_TYPE[type_signature](*args)
3686 else:
3687 tag = ICCProfileTag(tag_data, tag_signature)
3688 except Exception as exception:
3689 raise ICCProfileInvalidError(
3690 f"Couldn't parse tag {tag_signature!r} "
3691 f"(type {type_signature!r}, "
3692 f"offset {int(tag_data_offset):d}, "
3693 f"size {int(tag_data_size):d}): {exception!r}"
3694 ) from exception
3695 self[key] = tag
3696 return tag
3697
3698 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
3699 """Set the attribute with the given name to the given value.
3700
3701 Args:
3702 name (str): The name of the attribute to set.
3703 value (Any): The value to set the attribute to.
3704 """
3705 if name == "profile":
3706 object.__setattr__(self, name, value)
3707 else:
3708 AODict.__setattr__(self, name, value)
3709
3710 def get(self, key: str, default: None | Any = None) -> Any: # noqa: ANN401
3711 """Return the value of the attribute with the given key.
3712
3713 Args:
3714 key (str): The key of the attribute to get.
3715 default (None | Any, optional): The default value to return if the
3716 key does not exist.
3717
3718 Returns:
3719 Any: The value of the attribute with the given key, or the default
3720 value if the key does not exist.
3721 """
3722 return self[key] if key in self else default # noqa: SIM401
3723
3724
3725 class ICCProfileTag:
3726 """Base class for ICC profile tags.
3727
3728 Args:
3729 tagData (bytes): The data of the tag.
3730 tagSignature (str): The signature of the tag.
3731 """
3732
3733 def __init__(self, tagData: bytes, tagSignature: str) -> None: # noqa: N803
3734 self.tagData = tagData
3735 self.tagSignature = tagSignature
3736
3737 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
3738 """Set attribute with the given name to the given value.
3739
3740 Args:
3741 name (str): The name of the attribute to set.
3742 value (Any): The value to set the attribute to.
3743 """
3744 if not isinstance(self, dict) or name in ("_keys", "tagData", "tagSignature"):
3745 object.__setattr__(self, name, value)
3746 else:
3747 self[name] = value
3748
3749 def __repr__(self) -> str:
3750 """Return the string representation of the object.
3751
3752 t.__repr__() <==> repr(t).
3753
3754 Returns:
3755 str: The string representation of the object.
3756 """
3757 if isinstance(self, dict):
3758 return dict.__repr__(self)
3759 if isinstance(self, UserString):
3760 return UserString.__repr__(self)
3761 if isinstance(self, list):
3762 return list.__repr__(self)
3763 cls = self.__class__
3764 if not self:
3765 return f"{cls.__module__}.{cls.__name__}()"
3766 return f"{cls.__module__}.{cls.__name__}({self.tagData!r})"
3767
3768
3769 class Text(ICCProfileTag, bytes):
3770 """Text tag class which is a bytes type and handles str conversion.
3771
3772 Args:
3773 seq (bytes): The byte sequence representing the text tag.
3774 """
3775
3776 def __init__(self, seq: bytes) -> None:
3777 super().__init__(tagData=seq, tagSignature=b"")
3778 self.data = seq
3779
3780 def __str__(self) -> str:
3781 """Return the string representation of the object.
3782
3783 Returns:
3784 str: The string representation of the object.
3785 """
3786 return self.data.decode(FS_ENC, errors="replace")
3787
3788
3789 class Colorant:
3790 """Colorant class to handle colorant information.
3791
3792 Args:
3793 binaryString (bytes, optional): A 4-byte binary string representing the
3794 colorant type.
3795 """
3796
3797 def __init__(self, binaryString: bytes = b"\0" * 4) -> None: # noqa: N803
3798 self._type = uInt32Number(binaryString)
3799 self._channels = []
3800
3801 def __getitem__(self, key: str) -> Any: # noqa: ANN401
3802 """Get attribute via dictionary key.
3803
3804 Args:
3805 key (str): The attribute name.
3806
3807 Returns:
3808 Any: The value of the attribute.
3809 """
3810 return self.__getattribute__(key)
3811
3812 def __iter__(self) -> Iterator[str]:
3813 """Return an iterator over the keys of the object.
3814
3815 Returns:
3816 iter: An iterator over the keys of the object.
3817 """
3818 return iter(list(self.keys()))
3819
3820 def __repr__(self) -> str:
3821 """Return the string representation of the object.
3822
3823 Returns:
3824 str: The string representation of the object.
3825 """
3826 items = []
3827 for key, value in (("type", self.type), ("description", self.description)):
3828 items.append(f"{key!r}: {value!r}")
3829 channels = [
3830 "[{}]".format(", ".join([str(v) for v in xy])) for xy in self.channels
3831 ]
3832 items.append("'channels': [{}]".format(", ".join(channels)))
3833 return "{{{}}}".format(", ".join(items))
3834
3835 def __setitem__(self, key: str, value: Any) -> None: # noqa: ANN401
3836 """Set attribute via dictionary key.
3837
3838 Args:
3839 key (str): The attribute name.
3840 value (Any): The value to set.
3841 """
3842 object.__setattr__(self, key, value)
3843
3844 @property
3845 def channels(self) -> list:
3846 """Return the channels of the colorant.
3847
3848 Returns:
3849 list: A list of channels, where each channel is a list of values
3850 representing the colorant's channels. If no channels are set,
3851 """
3852 if not self._channels and self._type and self._type in COLORANTS:
3853 return [list(xy) for xy in COLORANTS[self._type]["channels"]]
3854 return self._channels
3855
3856 @channels.setter
3857 def channels(self, channels: list) -> None:
3858 """Set the channels of the colorant.
3859
3860 Args:
3861 channels (list): A list of channels, where each channel is a list
3862 of values representing the colorant's channels.
3863 """
3864 self._channels = channels
3865
3866 @property
3867 def description(self) -> str:
3868 """Return the description of the colorant.
3869
3870 Returns:
3871 str: The description of the colorant, which is based on its type.
3872 """
3873 return COLORANTS.get(self._type, COLORANTS[0])["description"]
3874
3875 @description.setter
3876 def description(self, value: str) -> None:
3877 """Set the description of the colorant.
3878
3879 Does nothing, as the description is derived from the type.
3880
3881 Args:
3882 value (str): The description of the colorant.
3883 """
3884
3885 def get(self, key: str, default: None | Any = None) -> Any: # noqa: ANN401
3886 """Get the value of the attribute with the given key.
3887
3888 Args:
3889 key (str): The key of the attribute to get.
3890 default (None | Any, optional): The default value to return if the
3891 key does not exist.
3892
3893 Returns:
3894 Any: The value of the attribute with the given key, or the default
3895 value if the key does not exist.
3896 """
3897 return getattr(self, key, default)
3898
3899 def items(self) -> list[tuple[str, Any]]:
3900 """Return a list of key-value pairs in the object.
3901
3902 Returns:
3903 list[tuple[str, Any]]: A list of key-value pairs in the object.
3904 """
3905 return list(zip(list(self.keys()), list(self.values())))
3906
3907 def iteritems(self) -> Iterator[tuple[str, Any]]:
3908 """Return an iterator over the key-value pairs in the object.
3909
3910 Returns:
3911 Iterator[tuple[str, Any]]: An iterator over the key-value pairs in
3912 the object.
3913 """
3914 return zip(list(self.keys()), iter(self.values()))
3915
3916 iterkeys = __iter__
3917
3918 def itervalues(self) -> Iterator:
3919 """Return an iterator over the values in the object.
3920
3921 Returns:
3922 Iterator: An iterator over the values in the object.
3923 """
3924 return map(self.get, list(self.keys()))
3925
3926 def keys(self) -> list[str]:
3927 """Return a list of keys in the object.
3928
3929 Returns:
3930 list[str]: A list of keys in the object.
3931 """
3932 return ["type", "description", "channels"]
3933
3934 def round(self, digits: int = 4) -> Colorant:
3935 """Return a new Colorant object with rounded channel values.
3936
3937 Args:
3938 digits (int): The number of decimal places to round to. Defaults to
3939 4.
3940
3941 Returns:
3942 Colorant: A new Colorant object with rounded channel values.
3943 """
3944 colorant = self.__class__()
3945 colorant.type = self.type
3946 for xy in self.channels:
3947 colorant._channels.append([round(value, digits) for value in xy])
3948 return colorant
3949
3950 @property
3951 def type(self) -> int:
3952 """Return the type of the colorant.
3953
3954 Returns:
3955 int: The type of the colorant, which should be one of the
3956 predefined colorant types in COLORANTS.
3957 """
3958 return self._type
3959
3960 @type.setter
3961 def type(self, value: int) -> None:
3962 """Set the type of the colorant.
3963
3964 Args:
3965 value (int): The type of the colorant, which should be one of the
3966 predefined colorant types in COLORANTS.
3967 """
3968 if value and value != self._type and value in COLORANTS:
3969 self._channels = []
3970 self._type = value
3971
3972 def update(self, *args: tuple, **kwargs: dict) -> None:
3973 """Update the object with key-value pairs from the given arguments.
3974
3975 Args:
3976 *args: Iterable of key-value pairs or a dictionary.
3977 **kwargs: Additional key-value pairs to update the object with.
3978
3979 Raises:
3980 TypeError: If more than one argument is provided.
3981 """
3982 if len(args) > 1:
3983 raise TypeError(f"update expected at most 1 arguments, got {len(args):d}")
3984 for iterable in args + tuple(kwargs.items()):
3985 if hasattr(iterable, "items"):
3986 self.update(iter(iterable.items()))
3987 elif hasattr(iterable, "keys"):
3988 for key in list(iterable.keys()):
3989 self[key] = iterable[key]
3990 else:
3991 for key, val in iterable:
3992 self[key] = val
3993
3994 def values(self) -> list:
3995 """Return a list of values in the object.
3996
3997 Returns:
3998 list: A list of values in the object.
3999 """
4000 return list(map(self.get, list(self.keys())))
4001
4002
4003 class Geometry(ADict):
4004 """Geometry attribute dictionary class.
4005
4006 Args:
4007 binaryString (bytes): The binary string representing the geometry type.
4008 """
4009
4010 def __init__(self, binaryString: bytes) -> None: # noqa: N803
4011 super().__init__()
4012 self.type = uInt32Number(binaryString)
4013 self.description = GEOMETRY[self.type]
4014
4015
4016 class Illuminant(ADict):
4017 """Illuminant attribute dictionary class.
4018
4019 Args:
4020 binaryString (bytes): The binary string representing the illuminant
4021 type.
4022 """
4023
4024 def __init__(self, binaryString: bytes) -> None: # noqa: N803
4025 super().__init__()
4026 self.type = uInt32Number(binaryString)
4027 self.description = ILLUMINANTS[self.type]
4028
4029
4030 class LUT16Type(ICCProfileTag):
4031 """ICC LUT16Type tag.
4032
4033 Args:
4034 tagData (bytes): The raw tag data.
4035 tagSignature (bytes): The tag signature.
4036 profile (ICCProfile): The ICC profile this tag belongs to.
4037 """
4038
4039 def __init__(
4040 self,
4041 tagData: None | bytes = None, # noqa: N803
4042 tagSignature: None | str = None, # noqa: N803
4043 profile: None | ICCProfile = None,
4044 ) -> None:
4045 ICCProfileTag.__init__(self, tagData, tagSignature)
4046 self.profile = profile
4047 self._matrix = None
4048 self._input = None
4049 self._clut = None
4050 self._output = None
4051 self._i = (tagData and uInt8Number(tagData[8:9])) or 0 # Input channel count
4052 self._o = (tagData and uInt8Number(tagData[9:10])) or 0 # Output channel count
4053 self._g = (tagData and uInt8Number(tagData[10:11])) or 0 # cLUT grid res
4054 self._n = (
4055 tagData and uInt16Number(tagData[48:50])
4056 ) or 0 # Input channel entries count
4057 self._m = (
4058 tagData and uInt16Number(tagData[50:52])
4059 ) or 0 # Output channel entries count
4060
4061 def apply_black_offset(
4062 self,
4063 XYZbp: tuple[float, float, float], # noqa: N803
4064 logfile: None | TextIO = None,
4065 thread_abort: None | threading.Event = None,
4066 abortmessage: str = "Aborted",
4067 ) -> None:
4068 """Apply black point offset to the cLUT.
4069
4070 Args:
4071 XYZbp (tuple[float, float, float]): The black point offset values
4072 as a tuple of three floats (X, Y, Z).
4073 logfile (None | TextIO): File-like object to write progress
4074 messages to. Defaults to None.
4075 thread_abort (threading.Event): Event to signal thread abortion.
4076 Defaults to None.
4077 abortmessage (str): Message to display when the operation is
4078 aborted. Defaults to "Aborted".
4079 """
4080 # Apply only the black point blending portion of BT.1886 mapping
4081 self._apply_black(XYZbp, False, False, logfile, thread_abort, abortmessage)
4082
4083 def apply_bpc(
4084 self,
4085 bp_out: tuple[float, float, float] = (0, 0, 0),
4086 weight: bool = False,
4087 logfile: None | TextIO = None,
4088 thread_abort: None | threading.Event = None,
4089 abortmessage: str = "Aborted",
4090 ) -> None:
4091 """Apply black point compensation to the cLUT.
4092
4093 Args:
4094 bp_out (tuple, optional): The black point output values as a tuple
4095 of three floats (R, G, B). Defaults to (0, 0, 0).
4096 weight (bool, optional): Whether to apply a weighted black point
4097 compensation. Defaults to False.
4098 logfile (None | TextIO): File-like object to write the log messages
4099 to.
4100 thread_abort (threading.Event): Event to signal thread abortion.
4101 abortmessage (str): Message to display when the operation is aborted.
4102 """
4103 return self._apply_black(
4104 bp_out, True, weight, logfile, thread_abort, abortmessage
4105 )
4106
4107 def _apply_black(
4108 self,
4109 bp_out: tuple[float, float, float],
4110 use_bpc: bool = False,
4111 weight: bool = False,
4112 logfile: None | TextIO = None,
4113 thread_abort: None | threading.Event = None,
4114 abortmessage: str = "Aborted",
4115 ) -> None:
4116 """Apply black point compensation or offset to the cLUT.
4117
4118 Args:
4119 bp_out (tuple): The black point output values as a tuple of three
4120 floats (R, G, B).
4121 use_bpc (bool, optional): Whether to use black point compensation
4122 (BPC) or just apply a black offset. Defaults to False.
4123 weight (bool, optional): Whether to apply a weighted black point
4124 compensation. Defaults to False.
4125 logfile (None | TextIO): File-like object to write progress
4126 messages to. Defaults to None.
4127 thread_abort (None | threading.Event, optional): Event to signal
4128 thread abortion. Defaults to None.
4129 abortmessage (str): Message to display when the operation is
4130 aborted. Defaults to "Aborted".
4131
4132 Raises:
4133 ValueError: If the PCS is not supported or if the black point
4134 output does not match the expected format.
4135 """
4136 pcs = self.profile and self.profile.connectionColorSpace
4137 bp_row = list(self.clut[0][0])
4138 wp_row = list(self.clut[-1][-1])
4139 nonzero_bp = tuple(bp_out) != (0, 0, 0)
4140 interp = []
4141 rinterp = []
4142 if not use_bpc or nonzero_bp:
4143 osize = len(self.output[0])
4144 omaxv = osize - 1.0
4145 orange = [i / omaxv * 65535 for i in range(osize)]
4146 for i in range(3):
4147 interp.append(colormath.Interp(orange, self.output[i]))
4148 rinterp.append(colormath.Interp(self.output[i], orange))
4149 for row in (bp_row, wp_row):
4150 for column, value in enumerate(row):
4151 row[column] = interp[column](value)
4152 method = "apply_bpc" if use_bpc else "apply_black_offset"
4153 if pcs == b"Lab":
4154 bp = colormath.Lab2XYZ(*legacy_PCSLab_uInt16_to_dec(*bp_row))
4155 wp = colormath.Lab2XYZ(*legacy_PCSLab_uInt16_to_dec(*wp_row))
4156 elif not pcs or pcs == b"XYZ":
4157 if not pcs:
4158 warnings.warn(
4159 f"LUT16Type.{method}: PCS not specified, assuming XYZ",
4160 Warning,
4161 stacklevel=2,
4162 )
4163 bp = [v / 32768.0 for v in bp_row]
4164 wp = [v / 32768.0 for v in wp_row]
4165 else:
4166 raise ValueError(f"LUT16Type.{method}: Unsupported PCS {pcs!r}")
4167 if [round(v * 32768) for v in bp] != [round(v * 32768) for v in bp_out]:
4168 D50 = colormath.get_whitepoint("D50") # noqa: N806
4169
4170 from DisplayCAL.multiprocess import pool_slice
4171
4172 num_workers = 1 if len(self.clut[0]) < 33 else None
4173
4174 # if pcs != "Lab" and nonzero_bp:
4175 # bp_out_offset = bp_out
4176 # bp_out = (0, 0, 0)
4177
4178 if bp != bp_out:
4179 self.clut = functools.reduce(
4180 operator.iadd,
4181 pool_slice(
4182 _mp_apply_black,
4183 self.clut,
4184 (
4185 pcs,
4186 bp,
4187 bp_out,
4188 wp,
4189 use_bpc,
4190 weight,
4191 D50,
4192 interp,
4193 rinterp,
4194 abortmessage,
4195 ),
4196 {},
4197 num_workers,
4198 thread_abort,
4199 logfile,
4200 ),
4201 [],
4202 )
4203
4204 # if pcs != "Lab" and nonzero_bp:
4205 # # Apply black offset to output curves
4206 # out = [[], [], []]
4207 # for i in range(2049):
4208 # v = i / 2048.0
4209 # X, Y, Z = colormath.blend_blackpoint(v, v, v, (0, 0, 0),
4210 # bp_out_offset)
4211 # out[0].append(X * 2048 / 4095.0 * 65535)
4212 # out[1].append(Y * 2048 / 4095.0 * 65535)
4213 # out[2].append(Z * 2048 / 4095.0 * 65535)
4214 # for i in range(2049, 4096):
4215 # v = i / 4095.0
4216 # out[0].append(v * 65535)
4217 # out[1].append(v * 65535)
4218 # out[2].append(v * 65535)
4219 # self.output = out
4220
4221 @property
4222 def clut(self) -> list:
4223 """Return the cLUT of the LUT16Type tag.
4224
4225 Returns:
4226 list: The cLUT of the LUT16Type tag, a nested list structure
4227 containing uInt16Number values.
4228 """
4229 if self._clut is not None:
4230 return self._clut
4231
4232 # Calculate cLUT from tag data
4233 i, o, g, n = self._i, self._o, self._g, self._n
4234 tag_data = self._tagData
4235 self._clut = [
4236 [
4237 [
4238 uInt16Number(
4239 tag_data[
4240 52 + n * i * 2 + o * 2 * (g * x + y) + z * 2 : 54
4241 + n * i * 2
4242 + o * 2 * (g * x + y)
4243 + z * 2
4244 ]
4245 )
4246 for z in range(o)
4247 ]
4248 for y in range(g)
4249 ]
4250 for x in range(int(g**i / g))
4251 ]
4252 return self._clut
4253
4254 @clut.setter
4255 def clut(self, value: list) -> None:
4256 """Set the cLUT of the LUT16Type tag.
4257
4258 Args:
4259 value (list): The cLUT to set, a nested list structure containing
4260 uInt16Number values.
4261 """
4262 self._clut = value
4263
4264 def clut_writepng(self, stream_or_filename: str | BinaryIO) -> None:
4265 """Write the cLUT as a PNG image arranged in grid squares.
4266
4267 Args:
4268 stream_or_filename (str | BinaryIO): The filename or
4269 file-like object to write the PNG image to.
4270
4271 Raises:
4272 NotImplementedError: If the output channels are not RGB
4273 (3 channels).
4274 """
4275 if len(self.clut[0][0]) != 3:
4276 raise NotImplementedError("clut_writepng: output channels != 3")
4277 imfile.write(self.clut, stream_or_filename)
4278
4279 def clut_writecgats(self, stream_or_filename: str | BinaryIO) -> None:
4280 """Write the cLUT as CGATS.
4281
4282 Args:
4283 stream_or_filename (str | BinaryIO): The filename or
4284 file-like object to write the CGATS data to.
4285 """
4286 # TODO:
4287 # Need to take into account input/output curves
4288 # Currently only supports RGB, A2B direction, and XYZ color space
4289 if len(self.clut[0][0]) != 3:
4290 raise NotImplementedError("clut_writecgats: output channels != 3")
4291 if isinstance(stream_or_filename, str):
4292 stream = open(stream_or_filename, "wb") # noqa: SIM115
4293 else:
4294 stream = stream_or_filename
4295 with stream:
4296 stream.write(
4297 b"""CTI3
4298 DEVICE_CLASS "DISPLAY"
4299 COLOR_REP "RGB_XYZ"
4300 BEGIN_DATA_FORMAT
4301 SAMPLE_ID RGB_R RGB_G RGB_B XYZ_X XYZ_Y XYZ_Z
4302 END_DATA_FORMAT
4303 BEGIN_DATA
4304 """
4305 )
4306 clutres = len(self.clut[0])
4307 block = 0
4308 i = 1
4309 if self.tagSignature and self.tagSignature.startswith("B2A"):
4310 interp = [
4311 colormath.Interp(
4312 input_value, list(range(len(input_value))), use_numpy=True
4313 )
4314 for input_value in self.input
4315 ]
4316 for a in range(clutres):
4317 for b in range(clutres):
4318 for c in range(clutres):
4319 R, G, B = [v / (clutres - 1.0) * 100 for v in (a, b, c)] # noqa: N806
4320 if self.tagSignature and self.tagSignature.startswith("B2A"):
4321 linear_rgb = [
4322 interp[i](v)
4323 / (len(interp[i].xp) - 1.0)
4324 * (1 + (32767 / 32768.0))
4325 * 100
4326 for i, v in enumerate(self.clut[block][c])
4327 ]
4328 X, Y, Z = self.matrix.inverted() * linear_rgb # noqa: N806
4329 else:
4330 X, Y, Z = [v / 32768.0 * 100 for v in self.clut[block][c]] # noqa: N806
4331 stream.write(
4332 b"%i %7.3f %7.3f %7.3f %10.6f %10.6f %10.6f\n"
4333 % (i, R, G, B, X, Y, Z)
4334 )
4335 i += 1
4336 block += 1
4337 stream.write(b"END_DATA\n")
4338
4339 @property
4340 def clut_grid_steps(self) -> int:
4341 """Return number of grid points per dimension.
4342
4343 Returns:
4344 int: The number of grid points per dimension of the cLUT.
4345 """
4346 return self._g or len(self.clut[0])
4347
4348 @property
4349 def input(self) -> list:
4350 """Return the input table of the LUT16Type tag.
4351
4352 Returns:
4353 list: The input table of the LUT16Type tag, a list of lists
4354 containing uInt16Number values.
4355 """
4356 if self._input is None:
4357 i, n = self._i, self._n
4358 tag_data = self._tagData
4359 self._input = [
4360 [
4361 uInt16Number(
4362 tag_data[52 + n * 2 * z + y * 2 : 54 + n * 2 * z + y * 2]
4363 )
4364 for y in range(n)
4365 ]
4366 for z in range(i)
4367 ]
4368 return self._input
4369
4370 @input.setter
4371 def input(self, value: list) -> None:
4372 """Set the input table of the LUT16Type tag.
4373
4374 Args:
4375 value (list): The input table to set, a list of lists containing
4376 uInt16Number values.
4377 """
4378 self._input = value
4379
4380 @property
4381 def input_channels_count(self) -> int:
4382 """Return number of input channels.
4383
4384 Returns:
4385 int: The number of input channels in the LUT16Type tag.
4386 """
4387 return self._i or len(self.input)
4388
4389 @property
4390 def input_entries_count(self) -> int:
4391 """Return number of entries per input channel.
4392
4393 Returns:
4394 int: The number of entries per input channel in the LUT16Type tag.
4395 """
4396 return self._n or len(self.input[0])
4397
4398 def invert(self) -> None:
4399 """Invert input and output tables."""
4400 # Invert input/output 1d LUTs
4401 for channel in (self.input, self.output):
4402 for e, entries in enumerate(channel):
4403 lut = {}
4404 maxv = len(entries) - 1.0
4405 for i, entry in enumerate(entries):
4406 lut[entry / 65535.0 * maxv] = i / maxv * 65535
4407 xp = list(lut.keys())
4408 fp = list(lut.values())
4409 for i in range(len(entries)):
4410 if i not in lut:
4411 lut[i] = colormath.interp(i, xp, fp)
4412 lut = dict_sort(lut)
4413 channel[e] = list(lut.values())
4414
4415 def clut_row_apply_per_channel(
4416 self,
4417 indexes: list,
4418 fn: Callable,
4419 fnargs: None | tuple = None,
4420 fnkwargs: None | dict = None,
4421 pcs: None | str = None,
4422 protect_gray_axis: bool = True,
4423 protect_dark: bool = False,
4424 protect_black: bool = True,
4425 exclude: None | set = None,
4426 ) -> None:
4427 """Apply function to channel values of each cLUT row.
4428
4429 Args:
4430 indexes (list): List of channel indexes to apply the function to.
4431 fn (callable): Function to apply to the channel values.
4432 fnargs (None | tuple, optional): Additional positional arguments to
4433 pass to the function. Defaults to an empty tuple.
4434 fnkwargs (None | dict, optional): Additional keyword arguments to
4435 pass to the function. Defaults to an empty dictionary.
4436 pcs (None | str, optional): The PCS (Profile Connection Space) to
4437 use. Defaults to None, which means the PCS will be determined
4438 from the profile.
4439 protect_gray_axis (bool, optional): Whether to protect the gray
4440 axis (diagonal) from modification. Defaults to True.
4441 protect_dark (bool, optional): Whether to protect dark values from
4442 modification. Defaults to False.
4443 protect_black (bool, optional): Whether to protect black values
4444 from modification. Defaults to True.
4445 exclude (set, optional): Set of (row_index, column_index) tuples to
4446 exclude from modification. Defaults to None, which means no
4447 exclusions will be applied.
4448 """
4449 if fnargs is None:
4450 fnargs = ()
4451
4452 if fnkwargs is None:
4453 fnkwargs = {}
4454
4455 clutres = len(self.clut[0])
4456 block = -1
4457 for i, row in enumerate(self.clut):
4458 channels = {}
4459 for k in indexes:
4460 channels[k] = []
4461 if protect_gray_axis or protect_dark or protect_black or exclude:
4462 if i % clutres == 0:
4463 block += 1
4464 gray_col_i = block if pcs == "XYZ" else clutres // 2 # L*a*b*
4465 gray_row_i = i + gray_col_i
4466 fnkwargs["protect"] = []
4467 for j, column in enumerate(row):
4468 is_exclude = exclude and (i, j) in exclude
4469 if is_exclude or (
4470 protect_gray_axis and (i == gray_row_i and j == gray_col_i)
4471 ):
4472 if DEBUG:
4473 print(
4474 "protect", "exclude" if is_exclude else "gray", i, j, column
4475 )
4476 fnkwargs["protect"].append(j)
4477 elif (protect_dark and sum(column) < 65535 * 0.03125 * 3) or (
4478 protect_black and min(column) == max(column) == 0
4479 ):
4480 if DEBUG:
4481 print("protect dark", i, j, column)
4482 fnkwargs["protect"].append(j)
4483 for k in indexes:
4484 channels[k].append(column[k])
4485 for k in channels:
4486 values = channels[k]
4487 channels[k] = fn(values, *fnargs, **fnkwargs)
4488 for j, column in enumerate(row):
4489 for k in indexes:
4490 column[k] = channels[k][j]
4491
4492 def clut_shift_columns(
4493 self,
4494 order: tuple[int, int, int] = (1, 2, 0),
4495 ) -> None:
4496 """Shift cLUT columns, altering slowest to fastest changing column.
4497
4498 Args:
4499 order (tuple[int, int, int]): The order of the channels to shift.
4500 Default is (1, 2, 0), which means the first channel will be
4501 the slowest changing, the second channel will be the middle
4502 changing, and the third channel will be the fastest changing.
4503
4504 Raises:
4505 NotImplementedError: If the number of input channels is not 3.
4506 """
4507 if len(self.input) != 3:
4508 raise NotImplementedError("input channels != 3")
4509 steps = len(self.clut[0])
4510 clut = []
4511 coord = [0, 0, 0]
4512 for a in range(steps):
4513 coord[order[0]] = a
4514 for b in range(steps):
4515 coord[order[1]] = b
4516 clut.append([])
4517 for c in range(steps):
4518 coord[order[2]] = c
4519 z, y, x = coord
4520 clut[-1].append(self.clut[z * steps + y][x])
4521 self.clut = clut
4522
4523 @property
4524 def matrix(self) -> colormath.Matrix3x3:
4525 """Return the matrix of the LUT16Type tag.
4526
4527 Returns:
4528 colormath.Matrix3x3: The matrix of the LUT16Type tag.
4529 """
4530 if self._matrix is None:
4531 tag_data = self._tagData
4532 return colormath.Matrix3x3(
4533 [
4534 (
4535 s15Fixed16Number(tag_data[12:16]),
4536 s15Fixed16Number(tag_data[16:20]),
4537 s15Fixed16Number(tag_data[20:24]),
4538 ),
4539 (
4540 s15Fixed16Number(tag_data[24:28]),
4541 s15Fixed16Number(tag_data[28:32]),
4542 s15Fixed16Number(tag_data[32:36]),
4543 ),
4544 (
4545 s15Fixed16Number(tag_data[36:40]),
4546 s15Fixed16Number(tag_data[40:44]),
4547 s15Fixed16Number(tag_data[44:48]),
4548 ),
4549 ]
4550 )
4551 return self._matrix
4552
4553 @matrix.setter
4554 def matrix(self, value: colormath.Matrix3x3) -> None:
4555 """Set the matrix of the LUT16Type tag.
4556
4557 Args:
4558 value (colormath.Matrix3x3): The matrix to set.
4559 """
4560 self._matrix = value
4561
4562 @property
4563 def output(self) -> list:
4564 """Return the output table of the LUT16Type tag.
4565
4566 Returns:
4567 list: The output table of the LUT16Type tag.
4568 """
4569 if self._output is None:
4570 i, o, g, n, m = self._i, self._o, self._g, self._n, self._m
4571 tag_data = self._tagData
4572 self._output = [
4573 [
4574 uInt16Number(
4575 tag_data[
4576 52 + n * i * 2 + m * 2 * z + y * 2 + g**i * o * 2 : 54
4577 + n * i * 2
4578 + m * 2 * z
4579 + y * 2
4580 + g**i * o * 2
4581 ]
4582 )
4583 for y in range(m)
4584 ]
4585 for z in range(o)
4586 ]
4587 return self._output
4588
4589 @output.setter
4590 def output(self, value: list) -> None:
4591 """Set the output table of the LUT16Type tag.
4592
4593 Args:
4594 value (list): The output table to set, which should be a list of
4595 lists containing uInt16Number values.
4596 """
4597 self._output = value
4598
4599 @property
4600 def output_channels_count(self) -> int:
4601 """Return number of output channels.
4602
4603 Returns:
4604 int: The number of output channels of the cLUT.
4605 """
4606 return self._o or len(self.output)
4607
4608 @property
4609 def output_entries_count(self) -> int:
4610 """Return number of entries per output channel.
4611
4612 Returns:
4613 int: The number of entries per output channel of the cLUT.
4614 """
4615 return self._m or len(self.output[0])
4616
4617 def smooth(
4618 self,
4619 diagpng: int = 2,
4620 pcs: None | str = None,
4621 filename: None | str = None,
4622 logfile: None | TextIO = None,
4623 debug_: int = 0,
4624 ) -> None:
4625 """Apply extra smoothing to the cLUT.
4626
4627 Args:
4628 diagpng (int, optional): If 2, generate a diagnostic PNG image of
4629 the cLUT. If 1, generate a diagnostic PNG image only if the
4630 cLUT is modified. If 0, do not generate a diagnostic image.
4631 Defatult is 2.
4632 pcs (None | str, optional): The profile connection space, either
4633 "XYZ" or "Lab". Default is None, which uses the profile's
4634 connectionColorSpace if available.
4635 filename (None | str, optional): The filename to save the
4636 diagnostic image to. Default is None, which uses the
4637 profile's filename if available.
4638 logfile (None | TextIO, optional): A file-like object to write log
4639 messages to. Default is None, which means no logging.
4640 debug_ (int, optional): Debug level, where 0 means no debug, 1
4641 means debug with some output, and 2 means full debug output.
4642 Default is 0.
4643
4644 Raises:
4645 TypeError: If PCS is not specified and no profile is available.
4646 """
4647 if not pcs:
4648 if self.profile:
4649 pcs = self.profile.connectionColorSpace
4650 else:
4651 raise TypeError("PCS not specified")
4652
4653 if not filename and self.profile:
4654 filename = self.profile.filename
4655
4656 clutres = len(self.clut[0])
4657
4658 sig = self.tagSignature or id(self)
4659
4660 if diagpng and filename and len(self.output) == 3:
4661 # Generate diagnostic images
4662 fname, _ = os.path.splitext(filename)
4663 diag_fname = f"{fname}.{sig}.post.CLUT.png"
4664 if diagpng == 2 and not os.path.isfile(diag_fname):
4665 self.clut_writepng(diag_fname)
4666 else:
4667 diagpng = 0
4668
4669 if logfile:
4670 logfile.write(f"Smoothing {sig}...\n")
4671 # Create a list of <clutres> number of 2D grids, each one with a
4672 # size of (width x height) <clutres> x <clutres>
4673 grids = []
4674 for i, block in enumerate(self.clut):
4675 if i % clutres == 0:
4676 grids.append([])
4677 grids[-1].append([])
4678 for RGB in block: # noqa: N806
4679 grids[-1][-1].append(RGB)
4680 for i, grid in enumerate(grids):
4681 for y in range(clutres):
4682 for x in range(clutres):
4683 is_dark = sum(grid[y][x]) < 65535 * 0.03125 * 3
4684 if pcs == "XYZ":
4685 is_gray = x == y == i
4686 elif clutres // 2 != clutres / 2.0:
4687 # For CIELab cLUT, gray will only
4688 # fall on a cLUT point if uneven cLUT res
4689 is_gray = x == y == clutres // 2
4690 else:
4691 is_gray = False
4692 # print(
4693 # i, y, x,
4694 # "{:d} {:d} {:d}".format(*(int(v / 655.35 * 2.55)
4695 # for v in grid[y][x])),
4696 # is_dark,
4697 # raw_input(is_gray) if is_gray else "",
4698 # )
4699 if is_dark or is_gray:
4700 # Don't smooth dark colors and gray axis
4701 continue
4702 RGB = [[v] for v in grid[y][x]] # noqa: N806
4703 # Use either "plus"-shaped or box filter depending if one
4704 # channel is fully saturated
4705 if clutres - 1 in (y, x) or 0 in (x, y):
4706 # Filter with a "plus" (+) shape
4707 # Smoothing factor for L*a*b* -> RGB cLUT above 50%
4708 smooth = 0.25 if pcs == "Lab" and i > clutres / 2.0 else 0.5
4709 for j, c in enumerate((x, y)):
4710 # Omit corners and perpendicular axis
4711 if 0 < c < clutres - 1:
4712 for n in (-1, 1):
4713 yi, xi = (y, y + n)[j], (x + n, x)[j]
4714 if -1 < xi < clutres and -1 < yi < clutres:
4715 RGBn = grid[yi][xi] # noqa: N806
4716 if debug_ == 2:
4717 if i < clutres - 1 or grid[y][x] != [
4718 16384,
4719 16384,
4720 16384,
4721 ]:
4722 grid[y][x] = [32768, 32768, 32768]
4723 if x == y == clutres - 2:
4724 RGBn[:] = [16384, 16384, 16384]
4725 for k in range(3):
4726 RGB[k].append(
4727 RGBn[k] * smooth
4728 + RGB[k][0] * (1 - smooth)
4729 )
4730 else:
4731 # Box filter, 3x3
4732 # Center pixel weight = 1.0, surround = 2/3, corners = 1/3
4733 if debug_ == 1:
4734 grid[y][x] = [32768, 32768, 32768]
4735 for j in (0, 1):
4736 for n in (-1, 1):
4737 for yi, xi in [
4738 ((y, y + n)[j], (x + n, x)[j]),
4739 (y - n, (x + n, x - n)[j]),
4740 ]:
4741 if -1 < xi < clutres and -1 < yi < clutres:
4742 RGBn = grid[yi][xi] # noqa: N806
4743 if yi != y and xi != x:
4744 smooth = 1 / 3.0
4745 else:
4746 smooth = 2 / 3.0
4747 if debug_ == 1 and x == y == clutres - 2:
4748 RGBn[:] = (v * (1 - smooth) for v in RGBn)
4749 for k in range(3):
4750 RGB[k].append(
4751 RGBn[k] * smooth
4752 + RGB[k][0] * (1 - smooth)
4753 )
4754 if not debug_:
4755 grid[y][x] = [sum(v) / float(len(v)) for v in RGB]
4756 for j, row in enumerate(grid):
4757 self.clut[i * clutres + j] = [
4758 [min(v, 65535) for v in RGB] for RGB in row
4759 ]
4760
4761 if diagpng and filename:
4762 self.clut_writepng(f"{fname}.{sig}.post.CLUT.smooth.png")
4763
4764 def smooth2(
4765 self,
4766 diagpng: int = 2,
4767 pcs: None | str = None,
4768 filename: None | str = None,
4769 logfile: None | TextIO = None,
4770 window: tuple[float, float, float] = (1 / 16.0, 1, 1 / 16.0),
4771 ) -> None:
4772 """Apply extra smoothing to the cLUT.
4773
4774 Args:
4775 diagpng (int, optional): Diagnostic PNG generation level (0, 1, 2,
4776 or 3). If `diagpng` is 0, no diagnostic images will be
4777 generated. If `diagpng` is 1, only the final smoothed cLUT will
4778 be saved. If `diagpng` is 2, the original and final smoothed
4779 cLUT will be saved. If `diagpng` is 3, intermediate steps will
4780 also be saved. If `diagpng` is 2 or 3, the filename will be
4781 used to generate diagnostic PNG files with the signature of the
4782 tag appended to the filename, e.g.,
4783 `filename.<signature>.post.CLUT.png`.
4784 pcs (None | str): The profile connection space (PCS) to use, e.g.,
4785 "Lab" or "XYZ". Default is None, which will use the PCS from
4786 the profile if available, or raise a TypeError if no PCS is
4787 specified and no profile is available.
4788 filename (None | str): The filename to save diagnostic images to.
4789 Default is None, which will use the profile filename if
4790 available.
4791 logfile (None | TextIO): A file-like object to write log messages
4792 to. Default is None, which means no logging will be done.
4793 window (tuple[float, float, float]): The smoothing window as a
4794 tuple of three floats, representing the weights for the R, G,
4795 and B channels. Default value is (1/16.0, 1, 1/16.0).
4796
4797 Raises:
4798 TypeError: If PCS is not specified and no profile is available.
4799 """
4800 if not pcs:
4801 if self.profile:
4802 pcs = self.profile.connectionColorSpace
4803 else:
4804 raise TypeError("PCS not specified")
4805
4806 if not filename and self.profile:
4807 filename = self.profile.filename
4808
4809 clutres = len(self.clut[0])
4810
4811 sig = self.tagSignature or id(self)
4812
4813 if diagpng and filename and len(self.output) == 3:
4814 # Generate diagnostic images
4815 fname, ext = os.path.splitext(filename)
4816 diag_fname = f"{fname}.{sig}.post.CLUT.png"
4817 if diagpng == 2 and not os.path.isfile(diag_fname):
4818 self.clut_writepng(diag_fname)
4819 else:
4820 diagpng = 0
4821
4822 if logfile:
4823 logfile.write(f"Smoothing {sig}...\n")
4824
4825 for i in range(3):
4826 state = ("original", "pass", "final")[i]
4827 if diagpng != 3 and i != 1:
4828 continue
4829 for j, (order, channels) in enumerate(
4830 [
4831 (None, "BGR"),
4832 ((1, 2, 0), "RBG"),
4833 ((0, 2, 1), "BRG"),
4834 ((2, 1, 0), "GRB"),
4835 ((0, 2, 1), "RGB"),
4836 ((2, 0, 1), "GBR"),
4837 ((0, 2, 1), "BGR"),
4838 ]
4839 ):
4840 if order:
4841 if DEBUG:
4842 print("Shifting order to", channels)
4843 self.clut_shift_columns(order)
4844 if i == 1 and j != 6:
4845 if DEBUG:
4846 print("Smoothing")
4847 exclude = None
4848 protect_gray_axis = True
4849 if pcs == "Lab":
4850 if clutres // 2 != clutres / 2.0:
4851 # For CIELab cLUT, gray will only
4852 # fall on a cLUT point if uneven cLUT res
4853 if channels in ("RBG", "RGB"):
4854 exclude = [
4855 ((clutres // 2 + 1) * (clutres - 1), col)
4856 for col in range(clutres)
4857 ]
4858 protect_gray_axis = False
4859 elif channels in ("BRG", "GRB"):
4860 exclude = [
4861 ((clutres // 2) * clutres + y, clutres // 2)
4862 for y in range(clutres)
4863 ]
4864 protect_gray_axis = False
4865 else:
4866 protect_gray_axis = False
4867 self.clut_row_apply_per_channel(
4868 (0, 1, 2),
4869 colormath.smooth_avg,
4870 (),
4871 {"window": window},
4872 pcs,
4873 protect_gray_axis,
4874 exclude=exclude,
4875 )
4876 if diagpng == 3 and filename and j != 6:
4877 if DEBUG:
4878 print("Writing diagnostic PNG for", state, channels)
4879 self.clut_writepng(
4880 f"{fname}.{sig}.post.CLUT.{channels}.{state}.png"
4881 )
4882
4883 if diagpng and filename:
4884 self.clut_writepng(f"{fname}.{sig}.post.CLUT.smooth.png")
4885
4886 @property
4887 def tagData(self) -> bytes: # noqa: N802
4888 """Return raw tag data.
4889
4890 Returns:
4891 bytes: Raw tag data for the LUT16Type tag.
4892 """
4893 if (self._matrix, self._input, self._clut, self._output) == (None,) * 4:
4894 return self._tagData
4895 tag_data = [
4896 b"mft2",
4897 b"\0" * 4,
4898 uInt8Number_tohex(len(self.input)),
4899 uInt8Number_tohex(len(self.output)),
4900 uInt8Number_tohex(len(self.clut and self.clut[0])),
4901 b"\0",
4902 s15Fixed16Number_tohex(self.matrix[0][0]),
4903 s15Fixed16Number_tohex(self.matrix[0][1]),
4904 s15Fixed16Number_tohex(self.matrix[0][2]),
4905 s15Fixed16Number_tohex(self.matrix[1][0]),
4906 s15Fixed16Number_tohex(self.matrix[1][1]),
4907 s15Fixed16Number_tohex(self.matrix[1][2]),
4908 s15Fixed16Number_tohex(self.matrix[2][0]),
4909 s15Fixed16Number_tohex(self.matrix[2][1]),
4910 s15Fixed16Number_tohex(self.matrix[2][2]),
4911 uInt16Number_tohex(len(self.input and self.input[0])),
4912 uInt16Number_tohex(len(self.output and self.output[0])),
4913 ]
4914 for entries in self.input:
4915 tag_data.extend(uInt16Number_tohex(v) for v in entries)
4916 for block in self.clut:
4917 for entries in block:
4918 tag_data.extend(uInt16Number_tohex(v) for v in entries)
4919 for entries in self.output:
4920 tag_data.extend(uInt16Number_tohex(v) for v in entries)
4921 return b"".join(tag_data)
4922
4923 @tagData.setter
4924 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
4925 """Set raw tag data.
4926
4927 Args:
4928 tagData (bytes): Raw tag data.
4929 """
4930 self._tagData = tagData
4931
4932
4933 class Observer(ADict):
4934 """ICC Observer tag.
4935
4936 Args:
4937 bytes_data (bytes): Raw tag data containing the observer type.
4938 """
4939
4940 def __init__(self, bytes_data: bytes) -> None:
4941 super(ADict, self).__init__()
4942 self.type = uInt32Number(bytes_data)
4943 self.description = OBSERVERS[self.type]
4944
4945
4946 class ChromaticityType(ICCProfileTag, Colorant):
4947 """ICC ChromaticityType tag.
4948
4949 Args:
4950 tagData (bytes, optional): Raw tag data. Defaults to None.
4951 tagSignature (str, optional): Tag signature. Defaults to None.
4952 """
4953
4954 def __init__(
4955 self,
4956 tagData: None | bytes = None, # noqa: N803
4957 tagSignature: None | str = None, # noqa: N803
4958 ) -> None:
4959 ICCProfileTag.__init__(self, tagData, tagSignature)
4960 if not tagData:
4961 Colorant.__init__(self, uInt32Number_tohex(1))
4962 return
4963 device_channels_count = uInt16Number(tagData[8:10])
4964 Colorant.__init__(self, uInt32Number_tohex(uInt16Number(tagData[10:12])))
4965 channels = tagData[12:]
4966 for _count in range(device_channels_count):
4967 self._channels.append(
4968 [u16Fixed16Number(channels[:4]), u16Fixed16Number(channels[4:8])]
4969 )
4970 channels = channels[8:]
4971
4972 __repr__ = Colorant.__repr__
4973
4974 @property
4975 def tagData(self) -> bytes: # noqa: N802
4976 """Return raw tag data.
4977
4978 Returns:
4979 bytes: Raw tag data for the ChromaticityType tag.
4980 """
4981 tag_data = [b"chrm", b"\0" * 4, uInt16Number_tohex(len(self.channels))]
4982 tag_data.append(uInt16Number_tohex(self.type))
4983 tag_data.extend(
4984 u16Fixed16Number_tohex(xy) for channel in self.channels for xy in channel
4985 )
4986 return b"".join(tag_data)
4987
4988 @tagData.setter
4989 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
4990 """Set raw tag data.
4991
4992 Does nothing as this tag is read-only.
4993
4994 Args:
4995 tagData (bytes): Raw tag data.
4996 """
4997
4998
4999 class ColorantTableType(ICCProfileTag, AODict):
5000 """ICC ColorantTableType tag.
5001
5002 Args:
5003 tagData (bytes, optional): Raw tag data. Defaults to None.
5004 tagSignature (str, optional): Tag signature. Defaults to None.
5005 pcs (bytes, optional): Profile connection space. Defaults to None.
5006 """
5007
5008 def __init__(
5009 self,
5010 tagData: None | bytes = None, # noqa: N803
5011 tagSignature: None | str = None, # noqa: N803
5012 pcs: None | bytes = None,
5013 ) -> None:
5014 ICCProfileTag.__init__(self, tagData, tagSignature)
5015 AODict.__init__(self)
5016 if not tagData:
5017 return
5018 colorant_count = uInt32Number(tagData[8:12])
5019 data = tagData[12:]
5020 for _count in range(colorant_count):
5021 pcsvalues = [
5022 uInt16Number(data[32:34]),
5023 uInt16Number(data[34:36]),
5024 uInt16Number(data[36:38]),
5025 ]
5026 for i, pcsvalue in enumerate(pcsvalues):
5027 if pcs in (b"Lab", b"RGB", b"CMYK", b"YCbr"):
5028 keys = ["L", "a", "b"]
5029 if i == 0:
5030 # L* range 0..100 + (25500 / 65280.0)
5031 pcsvalues[i] = pcsvalue / 65536.0 * 256 / 255.0 * 100
5032 else:
5033 # a, b range -128..127 + (255 / 256.0)
5034 pcsvalues[i] = -128 + (pcsvalue / 65536.0 * 256)
5035 elif pcs == b"XYZ":
5036 # X, Y, Z range 0..100 + (32767 / 32768.0)
5037 keys = ["X", "Y", "Z"]
5038 pcsvalues[i] = pcsvalue / 32768.0 * 100
5039 else:
5040 print(f"Warning: Non-standard profile connection space '{pcs}'")
5041 return
5042 end = data[:32].find(b"\0")
5043 if end < 0:
5044 end = 32
5045 name = data[:end]
5046 self[name] = AODict(list(zip(keys, pcsvalues)))
5047 data = data[38:]
5048
5049
5050 class CurveType(ICCProfileTag, list):
5051 """ICC CurveType tag.
5052
5053 Args:
5054 tagData (bytes, optional): Raw tag data. Defaults to None.
5055 tagSignature (str, optional): Tag signature. Defaults to None.
5056 profile (ICCProfile, optional): ICC profile instance. Defaults to None.
5057 """
5058
5059 def __init__(
5060 self,
5061 tagData: None | bytes = None, # noqa: N803
5062 tagSignature: None | str = None, # noqa: N803
5063 profile: None | ICCProfile = None,
5064 ) -> None:
5065 ICCProfileTag.__init__(self, tagData, tagSignature)
5066 self.profile = profile
5067 self._reset()
5068 if not tagData:
5069 return
5070 curve_entries_count = uInt32Number(tagData[8:12])
5071 curve_entries = tagData[12:]
5072 if curve_entries_count == 1:
5073 # Gamma
5074 self.append(u8Fixed8Number(curve_entries[:2]))
5075 elif curve_entries_count:
5076 # Curve
5077 for _count in range(curve_entries_count):
5078 self.append(uInt16Number(curve_entries[:2]))
5079 curve_entries = curve_entries[2:]
5080 else:
5081 # Identity
5082 self.append(1.0)
5083
5084 def __delitem__(self, value: int) -> None:
5085 """Delete an item from the list.
5086
5087 Args:
5088 value (int): Index of the item to delete.
5089 """
5090 list.__delitem__(self, value)
5091 self._reset()
5092
5093 def __iadd__(self, value: Any) -> Self: # noqa: ANN401
5094 """Add a value to the list.
5095
5096 Args:
5097 value (Any): The value to add to the list.
5098
5099 Returns:
5100 Self: The updated list.
5101 """
5102 list.__iadd__(self, value)
5103 self._reset()
5104 return self
5105
5106 def __imul__(self, value: int) -> Self:
5107 """Multiply the list by a scalar.
5108
5109 Args:
5110 value (int): The scalar to multiply the list by.
5111
5112 Returns:
5113 Self: The updated list.
5114 """
5115 list.__imul__(self, value)
5116 self._reset()
5117 return self
5118
5119 def __setitem__(self, key: int, value: Any) -> None: # noqa: ANN401
5120 """Set an item in the list.
5121
5122 Args:
5123 key (int): Index of the item to set.
5124 value (Any): The new value to set at the index.
5125 """
5126 list.__setitem__(self, key, value)
5127 self._reset()
5128
5129 def _reset(self) -> None:
5130 """Reset internal state."""
5131 self._transfer_function = {}
5132 self._bt1886 = {}
5133
5134 def append(self, object_: Any) -> None: # noqa: ANN401
5135 """Append an object to the list.
5136
5137 Args:
5138 object_ (Any): The object to append to the list.
5139 """
5140 list.append(self, object_)
5141 self._reset()
5142
5143 def apply_bpc(self, black_Y_out: float = 0, weight: bool = False) -> None: # noqa: N803
5144 """Apply black point compensation to the curve.
5145
5146 Args:
5147 black_Y_out (float, optional): The output black point Y value to
5148 apply. Defaults to 0.
5149 weight (bool, optional): If True, apply weighted black point
5150 compensation. Defaults to False.
5151 """
5152 if len(self) < 2:
5153 return
5154 D50_xyY = colormath.XYZ2xyY(*colormath.get_whitepoint("D50")) # noqa: N806
5155 bp_in = colormath.xyY2XYZ(D50_xyY[0], D50_xyY[1], self[0] / 65535.0)
5156 bp_out = colormath.xyY2XYZ(D50_xyY[0], D50_xyY[1], black_Y_out)
5157 wp_out = colormath.xyY2XYZ(D50_xyY[0], D50_xyY[1], self[-1] / 65535.0)
5158 for i, v in enumerate(self):
5159 X, Y, Z = colormath.xyY2XYZ(D50_xyY[0], D50_xyY[1], v / 65535.0) # noqa: N806
5160 self[i] = (
5161 colormath.apply_bpc(X, Y, Z, bp_in, bp_out, wp_out, weight)[1] * 65535.0
5162 )
5163
5164 def extend(self, iterable: Iterable) -> None:
5165 """Extend the list with elements from an iterable.
5166
5167 Args:
5168 iterable (iterable): An iterable whose elements will be added to
5169 the list.
5170 """
5171 list.extend(self, iterable)
5172 self._reset()
5173
5174 def get_gamma(
5175 self,
5176 use_vmin_vmax: bool = False,
5177 average: bool = True,
5178 least_squares: bool = False,
5179 slice_: tuple[float, float] = (0.01, 0.99),
5180 lstar_slice: bool = True,
5181 ) -> float | list:
5182 """Return average or least squares gamma or a list of gamma values.
5183
5184 Args:
5185 use_vmin_vmax (bool, optional): If True, use the first and last
5186 values as vmin and vmax for gamma calculation. Default is
5187 False.
5188 average (bool, optional): If True, return the average gamma value.
5189 Default is True.
5190 least_squares (bool, optional): If True, return the least squares
5191 gamma value. Default is False.
5192 slice_ (tuple[float, float], optional): The range of the curve to
5193 consider for the gamma calculation. Defaults to (0.01, 0.99).
5194 lstar_slice (bool, optional): If True, use L* values for the slice.
5195 Defaults to True.
5196
5197 Returns:
5198 float | list: If average or least_squares is True, return a single
5199 gamma value. Otherwise, return a list of gamma values for the
5200 specified slice.
5201 """
5202 if len(self) <= 1:
5203 values = self if len(self) else [1.0] # Identity
5204 if average or least_squares:
5205 return values[0]
5206 return [values[0]]
5207 if lstar_slice:
5208 start = slice_[0] * 100
5209 end = slice_[1] * 100
5210 values = []
5211 for i, y in enumerate(self):
5212 n = colormath.XYZ2Lab(0, y / 65535.0 * 100, 0)[0]
5213 if start <= n <= end:
5214 values.append((i / (len(self) - 1.0) * 65535.0, y))
5215 else:
5216 maxv = len(self) - 1.0
5217 maxi = int(maxv)
5218 starti = round(slice_[0] * maxi)
5219 endi = round(slice_[1] * maxi) + 1
5220 values = list(
5221 zip(
5222 [(v / maxv) * 65535 for v in range(starti, endi)], self[starti:endi]
5223 )
5224 )
5225 vmin = 0
5226 vmax = 65535.0
5227 if use_vmin_vmax and len(self) > 2:
5228 vmin = self[0]
5229 vmax = self[-1]
5230 return colormath.get_gamma(values, 65535.0, vmin, vmax, average, least_squares)
5231
5232 def get_transfer_function(
5233 self,
5234 best: bool = True,
5235 slice_: tuple[float, float] = (0.05, 0.95),
5236 black_Y: None | float = None, # noqa: N803
5237 outoffset: None | float = None,
5238 ) -> tuple[tuple[str, float, float], float] | float:
5239 """Return transfer function name, exponent and match percentage.
5240
5241 Args:
5242 best (bool): If True, return the best matching transfer function.
5243 slice_ (tuple[float, float]): The range of the curve to consider for
5244 the transfer function.
5245 black_Y (None | float): The black Y value to use for the transfer
5246 function calculation. If None, it will be calculated from the
5247 curve.
5248 outoffset (None | float): The output offset to apply. If None, it
5249 will be set to 1.0.
5250
5251 Returns:
5252 tuple: A tuple containing the transfer function name, exponent,
5253 output offset, and the match percentage.
5254 float: The match percentage of the transfer function.
5255 """
5256 if len(self) == 1:
5257 # Gamma
5258 return (f"Gamma {round(self[0], 2):.2f}", self[0], 1.0), 1.0
5259 if not len(self):
5260 # Identity
5261 return ("Gamma 1.0", 1.0, 1.0), 1.0
5262 transfer_function = self._transfer_function.get((best, slice_))
5263 if transfer_function:
5264 return transfer_function
5265 trc = CurveType()
5266 match = {}
5267 otrc = CurveType()
5268 otrc[:] = self
5269 if otrc[0]:
5270 otrc.apply_bpc()
5271 vmin = otrc[0]
5272 vmax = otrc[-1]
5273 if self.profile and isinstance(self.profile.tags.get("lumi"), XYZType):
5274 white_cdm2 = self.profile.tags.lumi.Y
5275 else:
5276 white_cdm2 = 100.0
5277 if black_Y is None:
5278 black_Y = self[0] / 65535.0 # noqa: N806
5279 black_cdm2 = black_Y * white_cdm2
5280 maxv = len(otrc) - 1.0
5281 maxi = int(maxv)
5282 _starti = round(0.4 * maxi)
5283 _endi = round(0.6 * maxi)
5284 gamma = otrc.get_gamma(True, slice_=(0.4, 0.6), lstar_slice=False)
5285 egamma = colormath.get_gamma([(0.5, 0.5**gamma)], vmin=-black_Y)
5286 outoffset_unspecified = outoffset is None
5287 if outoffset_unspecified:
5288 outoffset = 1.0
5289 tfs = [
5290 ("Rec. 709", -709, outoffset),
5291 ("Rec. 1886", -1886, 0),
5292 ("SMPTE 240M", -240, outoffset),
5293 ("SMPTE 2084", -2084, outoffset),
5294 ("DICOM", -1023, outoffset),
5295 ("HLG", -2, outoffset),
5296 ("L*", -3.0, outoffset),
5297 ("sRGB", -2.4, outoffset),
5298 (
5299 f"Gamma {gamma:.2f} {outoffset:.0%}",
5300 gamma,
5301 outoffset,
5302 ),
5303 ]
5304 if outoffset_unspecified and black_Y:
5305 tfs.extend(
5306 (
5307 f"Gamma {gamma:.2f} {i:d}%",
5308 gamma,
5309 i / 100.0,
5310 )
5311 for i in range(100)
5312 )
5313 for name, exp, outoffset in tfs:
5314 if name in ("DICOM", "Rec. 1886", "SMPTE 2084", "HLG"):
5315 try:
5316 if name == "DICOM":
5317 trc.set_dicom_trc(black_cdm2, white_cdm2, size=len(self))
5318 elif name == "Rec. 1886":
5319 trc.set_bt1886_trc(black_Y, size=len(self))
5320 elif name == "SMPTE 2084":
5321 trc.set_smpte2084_trc(black_cdm2, white_cdm2, size=len(self))
5322 elif name == "HLG":
5323 trc.set_hlg_trc(black_cdm2, white_cdm2, size=len(self))
5324 except ValueError:
5325 continue
5326 elif exp > 0 and black_Y:
5327 trc.set_bt1886_trc(black_Y, outoffset, egamma, "b")
5328 else:
5329 trc.set_trc(exp, len(self), vmin, vmax)
5330 if trc[0] and trc[-1] - trc[0]:
5331 trc.apply_bpc()
5332 if otrc == trc:
5333 match[(name, exp, outoffset)] = 1.0
5334 else:
5335 match[(name, exp, outoffset)] = 0.0
5336 count = 0
5337 start = slice_[0] * len(self)
5338 end = slice_[1] * len(self)
5339 for i, n in enumerate(otrc):
5340 # n = colormath.XYZ2Lab(0, n / 65535.0 * 100, 0)[0]
5341 if start > i or i > end:
5342 continue
5343 n = colormath.get_gamma(
5344 [(i / (len(self) - 1.0) * 65535.0, n)],
5345 65535.0,
5346 vmin,
5347 vmax,
5348 False,
5349 )
5350 if n:
5351 n = n[0]
5352 # n2 = colormath.XYZ2Lab(0, trc[i] / 65535.0 * 100, 0)[0]
5353 n2 = colormath.get_gamma(
5354 [(i / (len(self) - 1.0) * 65535.0, trc[i])],
5355 65535.0,
5356 vmin,
5357 vmax,
5358 False,
5359 )
5360 if n2 and n2[0]:
5361 n2 = n2[0]
5362 match[(name, exp, outoffset)] += 1 - (
5363 max(n, n2) - min(n, n2)
5364 ) / ((n + n2) / 2.0)
5365 count += 1
5366 if count:
5367 match[(name, exp, outoffset)] /= count
5368 if not best:
5369 self._transfer_function[(best, slice_)] = match
5370 return match
5371 match, (name, exp, outoffset) = sorted(
5372 zip(list(match.values()), list(match.keys()))
5373 )[-1]
5374 self._transfer_function[(best, slice_)] = (name, exp, outoffset), match
5375 return (name, exp, outoffset), match
5376
5377 def insert(self, object_: Any) -> None: # noqa: ANN401
5378 """Insert an item at a given position in the list.
5379
5380 Args:
5381 object_ (Any): The item to insert into the list.
5382 """
5383 list.insert(self, object_)
5384 self._reset()
5385
5386 def pop(self, index: int) -> None:
5387 """Remove and return an item at the given index.
5388
5389 Args:
5390 index (int): The index of the item to remove and return.
5391 """
5392 list.pop(self, index)
5393 self._reset()
5394
5395 def remove(self, value: Any) -> None: # noqa: ANN401
5396 """Remove the first occurrence of a value from the list.
5397
5398 Args:
5399 value (Any): The value to remove from the list.
5400 """
5401 list.remove(self, value)
5402 self._reset()
5403
5404 def reverse(self) -> None:
5405 """Reverse the order of the list."""
5406 list.reverse(self)
5407 self._reset()
5408
5409 def set_bt1886_trc(
5410 self,
5411 black_Y: float = 0, # noqa: N803
5412 outoffset: float = 0.0,
5413 gamma: float = 2.4,
5414 gamma_type: str = "B",
5415 size: None | int = None,
5416 ) -> None | colormath.BT1886:
5417 """Set the response to the BT. 1886 curve.
5418
5419 This response is special in that it depends on the actual black
5420 level of the display.
5421
5422 Args:
5423 black_Y (float, optional): Black point in absolute Y, range 0..100.
5424 Defaults to 0.
5425 outoffset (float, optional): Output offset, range 0.0..1. Defaults to 0.0.
5426 gamma (float, optional): Gamma value, range 1.0..3.0.
5427 Defaults to 2.4.
5428 gamma_type (str, optional): Type of gamma to use, either "b" for
5429 BT.1886 or "g" for technical gamma. Defaults to "B".
5430 size (None | int, optional): Number of steps. Recommended >= 1024.
5431
5432 Returns:
5433 None | BT1886: None if the response was set successfully, or BT1886
5434 instance if it was already set for the given parameters.
5435 """
5436 bt1886 = self._bt1886.get((gamma, black_Y, outoffset))
5437 if bt1886:
5438 return bt1886
5439 if gamma_type in ("b", "g"):
5440 # Get technical gamma needed to achieve effective gamma
5441 gamma = colormath.xicc_tech_gamma(gamma, black_Y, outoffset)
5442 rXYZ = colormath.RGB2XYZ(1.0, 0, 0) # noqa: N806
5443 gXYZ = colormath.RGB2XYZ(0, 1.0, 0) # noqa: N806
5444 bXYZ = colormath.RGB2XYZ(0, 0, 1.0) # noqa: N806
5445 mtx = colormath.Matrix3x3(
5446 [
5447 [rXYZ[0], gXYZ[0], bXYZ[0]],
5448 [rXYZ[1], gXYZ[1], bXYZ[1]],
5449 [rXYZ[2], gXYZ[2], bXYZ[2]],
5450 ]
5451 )
5452 wXYZ = colormath.RGB2XYZ(1.0, 1.0, 1.0) # noqa: N806
5453 x, y = colormath.XYZ2xyY(*wXYZ)[:2]
5454 XYZbp = colormath.xyY2XYZ(x, y, black_Y) # noqa: N806
5455 bt1886 = colormath.BT1886(mtx, XYZbp, outoffset, gamma)
5456 self._bt1886[(gamma, black_Y, outoffset)] = bt1886
5457 self.set_trc(-709, size)
5458 for i, v in enumerate(self):
5459 X, Y, Z = colormath.xyY2XYZ(x, y, v / 65535.0) # noqa: N806
5460 self[i] = bt1886.apply(X, Y, Z)[1] * 65535.0
5461 return None
5462
5463 def set_dicom_trc(
5464 self, black_cdm2: float = 0.05, white_cdm2: float = 100, size: None | int = None
5465 ) -> None:
5466 """Set the response to the DICOM Grayscale Standard Display Function.
5467
5468 This response is special in that it depends on the actual black
5469 and white level of the display.
5470
5471 Args:
5472 black_cdm2 (float, optional): Black point in absolute Y,
5473 range 0.05..white_cdm2. Defaults to 0.05.
5474 white_cdm2 (float, optional): White point in absolute Y,
5475 range black_cdm2..4000. Defaults to 100.
5476 size (None | int, optional): Number of steps. Recommended >= 1024.
5477 """
5478 # See http://medical.nema.org/Dicom/2011/11_14pu.pdf
5479 # Luminance levels depend on the start level of 0.05 cd/m2
5480 # and end level of 4000 cd/m2
5481 black_cdm2 = round(black_cdm2, 6)
5482 if black_cdm2 < 0.05 or black_cdm2 >= white_cdm2:
5483 raise ValueError(
5484 f"The black level of {black_cdm2} cd/m2 is out of range "
5485 "for DICOM. Valid range begins at 0.05 cd/m2."
5486 )
5487 if white_cdm2 > 4000 or white_cdm2 <= black_cdm2:
5488 raise ValueError(
5489 f"The white level of {white_cdm2} cd/m2 is out of range "
5490 "for DICOM. Valid range is up to 4000 cd/m2."
5491 )
5492 black_jndi = colormath.DICOM(black_cdm2, True)
5493 white_jndi = colormath.DICOM(white_cdm2, True)
5494 white_dicom_y = math.pow(10, colormath.DICOM(white_jndi))
5495 if not size:
5496 size = len(self)
5497 if size < 2:
5498 size = 1024
5499 self[:] = []
5500 for i in range(size):
5501 v = (
5502 math.pow(
5503 10,
5504 colormath.DICOM(
5505 black_jndi + (float(i) / (size - 1)) * (white_jndi - black_jndi)
5506 ),
5507 )
5508 / white_dicom_y
5509 )
5510 self.append(v * 65535)
5511
5512 def set_hlg_trc(
5513 self,
5514 black_cdm2: float = 0,
5515 white_cdm2: float = 100,
5516 system_gamma: float = 1.2,
5517 ambient_cdm2: float = 5,
5518 maxsignal: float = 1.0,
5519 size: None | int = None,
5520 logfile: None | TextIO = None,
5521 ) -> None:
5522 """Set the response to the Hybrid Log-Gamma (HLG) function.
5523
5524 This response is special in that it depends on the actual black
5525 and white level of the display, system gamma and ambient.
5526
5527 Args:
5528 black_cdm2 (float, optional): Black point in absolute XYZ, range
5529 0..white_cdm2. Defaults to 0.
5530 white_cdm2 (float, optional): White point in absolute Y,
5531 range 0..10000. Defaults to 100.
5532 system_gamma (float, optional): System gamma, typically 1.2.
5533 Defaults to 1.2.
5534 ambient_cdm2 (float, optional): Ambient light in cd/m2. Defaults to
5535 5.
5536 maxsignal (float, optional): Set clipping point. Defaults to 1.0.
5537 size (None | int, optional): Number of steps. Recommended >= 1024.
5538 logfile (None | TextIO, optional): Log file to write diagnostic
5539 information to. Defaults to None.
5540
5541 Raises:
5542 ValueError: If the black or white levels are out of range for
5543 HLG.
5544 ValueError: If the white level exceeds 10000 cd/m2.
5545 ValueError: If the black level is negative or greater than or equal
5546 to the white level.
5547 ValueError: If the white level is less than or equal to the black
5548 level.
5549 """
5550 if black_cdm2 < 0 or black_cdm2 >= white_cdm2:
5551 raise ValueError(
5552 f"The black level of {black_cdm2:f} cd/m2 is out of range "
5553 "for HLG. Valid range begins at 0 cd/m2."
5554 )
5555 values = []
5556
5557 hlg = colormath.HLG(black_cdm2, white_cdm2, system_gamma, ambient_cdm2)
5558
5559 if maxsignal < 1:
5560 # Adjust EOTF so that EOTF[maxsignal] gives (approx) white_cdm2
5561 while hlg.eotf(maxsignal) * hlg.white_cdm2 < white_cdm2:
5562 hlg.white_cdm2 += 1
5563
5564 lscale = 1.0 / hlg.oetf(1.0, True)
5565 hlg.white_cdm2 *= lscale
5566 if lscale < 1 and logfile:
5567 logfile.write(
5568 f"Nominal peak luminance after scaling = {hlg.white_cdm2:.2f}\n"
5569 )
5570
5571 maxv = hlg.eotf(maxsignal)
5572 if not size:
5573 size = len(self)
5574 if size < 2:
5575 size = 1024
5576 for i in range(size):
5577 n = i / (size - 1.0)
5578 v = hlg.eotf(min(n, maxsignal))
5579 values.append(min(v / maxv, 1.0))
5580 self[:] = [min(v * 65535, 65535) for v in values]
5581
5582 def set_smpte2084_trc(
5583 self,
5584 black_cdm2: float = 0,
5585 white_cdm2: float = 100,
5586 master_black_cdm2: float = 0,
5587 master_white_cdm2: float = 0,
5588 use_alternate_master_white_clip: bool = True,
5589 rolloff: bool = False,
5590 size: None | int = None,
5591 ) -> None:
5592 """Set the response to the SMPTE 2084 perceptual quantizer (PQ) function.
5593
5594 This response is special in that it depends on the actual black
5595 and white level of the display.
5596
5597 Args:
5598 black_cdm2 (float, optinoal): Black point in absolute Y, range
5599 0..white_cdm2. Defaults to 0.
5600 white_cdm2 (float, optional): White point in absolute Y, range
5601 0..10000. Defaults to 100.
5602 master_black_cdm2 (float, optional): Used to normalize PQ values.
5603 master_white_cdm2 (float, optional): Used to normalize PQ values.
5604 use_alternate_master_white_clip (bool, optional): If True,
5605 use the alternate master white clip as defined in ITU-R
5606 BT.2390. Defaults to True.
5607 rolloff (bool, optional): BT.2390.
5608 size (None | int, optional): Number of steps. Recommended >= 1024.
5609
5610 Raises:
5611 ValueError: If the black or white levels are out of range for
5612 SMPTE 2084.
5613 ValueError: If the white level exceeds 10000 cd/m2.
5614 ValueError: If the black level is negative or greater than or equal
5615 to the white level.
5616 ValueError: If the white level is less than or equal to the black
5617 level.
5618 ValueError: If the master white level exceeds 10000 cd/m2.
5619 """
5620 # See https://www.smpte.org/sites/default/files/2014-05-06-EOTF-Miller-1-2-handout.pdf
5621 # Luminance levels depend on the end level of 10000 cd/m2
5622 if black_cdm2 < 0 or black_cdm2 >= white_cdm2:
5623 raise ValueError(
5624 f"The black level of {black_cdm2:f} cd/m2 is out of range "
5625 "for SMPTE 2084. Valid range begins at 0 cd/m2."
5626 )
5627 if max(white_cdm2, master_white_cdm2) > 10000:
5628 raise ValueError(
5629 f"The white level of {max(white_cdm2, master_white_cdm2):f} "
5630 "cd/m2 is out of range for SMPTE 2084. "
5631 "Valid range is up to 10000 cd/m2."
5632 )
5633 values = []
5634 maxv = white_cdm2 / 10000.0
5635 maxi = colormath.special_pow(maxv, 1.0 / -2084)
5636 if rolloff:
5637 # Rolloff as defined in ITU-R BT.2390
5638 if not master_white_cdm2:
5639 master_white_cdm2 = 10000
5640 bt2390 = colormath.BT2390(
5641 black_cdm2,
5642 white_cdm2,
5643 master_black_cdm2,
5644 master_white_cdm2,
5645 use_alternate_master_white_clip,
5646 )
5647 maxi_out = maxi
5648 else:
5649 if not master_white_cdm2:
5650 master_white_cdm2 = white_cdm2
5651 maxi_out = colormath.special_pow(master_white_cdm2 / 10000.0, 1.0 / -2084)
5652 if not size:
5653 size = len(self)
5654 if size < 2:
5655 size = 1024
5656 for i in range(size):
5657 n = i / (size - 1.0)
5658 if rolloff:
5659 n = bt2390.apply(n)
5660 v = colormath.special_pow(n * (maxi / maxi_out), -2084)
5661 values.append(min(v / maxv, 1.0))
5662 self[:] = [min(v * 65535, 65535) for v in values]
5663 if black_cdm2 and not rolloff:
5664 self.apply_bpc(black_cdm2 / white_cdm2)
5665
5666 def set_trc(
5667 self,
5668 power: float | Callable = 2.2,
5669 size: None | int = None,
5670 vmin: float = 0,
5671 vmax: float = 65535,
5672 ) -> None:
5673 """Set the response to a certain function.
5674
5675 Args:
5676 power (float | Callable, optional): The power to raise the input
5677 value to. If a callable, it should take a single float argument
5678 and return a float. Defaults to 2.2. Positive power, or
5679 -2.4 = sRGB, -3.0 = L*, -240 = SMPTE 240M, -601 = Rec. 601,
5680 -709 = Rec. 709 (Rec. 601 and 709 transfer functions are
5681 identical).
5682 size (int, optional): The number of entries in the curve. Defaults
5683 to None.
5684 vmin (float, optional): The minimum value of the curve. Defaults to
5685 0.
5686 vmax (float, optional): The maximum value of the curve. Defaults to
5687 65535.
5688 """
5689 if not size:
5690 size = len(self) or 1024
5691 if size == 1:
5692 if callable(power):
5693 power = colormath.get_gamma([(0.5, power(0.5))])
5694 if power >= 0.0 and not vmin:
5695 self[:] = [power]
5696 return
5697 size = 1024
5698 self[:] = []
5699 if not callable(power):
5700 exp = power
5701
5702 def power(a: float) -> float:
5703 """Power function for non-callable power.
5704
5705 Args:
5706 a (float): The input value to raise to the power.
5707
5708 Returns:
5709 float: The result of raising the input value to the power.
5710 """
5711 return colormath.special_pow(a, exp)
5712
5713 for i in range(size):
5714 self.append(vmin + power(float(i) / (size - 1)) * (vmax - vmin))
5715
5716 def smooth_cr(self, length: int = 64) -> None:
5717 """Smooth curves (Catmull-Rom).
5718
5719 Args:
5720 length (int, optional): Number of points to use for smoothing.
5721 Defaults to 64.
5722 """
5723 raise NotImplementedError
5724
5725 def smooth_avg(
5726 self,
5727 passes: int = 1,
5728 window: None | tuple[float, float, float] = None,
5729 ) -> None:
5730 """Smooth curves (moving average).
5731
5732 Args:
5733 passes (int, optional): Number of passes. Defaults to 1.
5734 window (None | tuple[float, float, float], optional): Tuple or list
5735 containing weighting factors. Its length determines the size of
5736 the window to use. Defaults to (1.0, 1.0, 1.0).
5737 """
5738 self[:] = colormath.smooth_avg(self, passes, window)
5739
5740 def sort(
5741 self,
5742 cmp: None | Callable = None,
5743 key: None | Callable = None,
5744 reverse: bool = False,
5745 ) -> None:
5746 """Sort the curve entries.
5747
5748 Args:
5749 cmp (callable, optional): A comparison function that defines the
5750 sort order. Not used in Python 3.
5751 key (callable, optional): A function that extracts a comparison
5752 key from each list element. Defaults to None.
5753 reverse (bool, optional): If True, the list elements are sorted in
5754 descending order. Defaults to False.
5755 """
5756 list.sort(self, key=key, reverse=reverse)
5757 self._reset()
5758
5759 @property
5760 def tagData(self) -> bytes: # noqa: N802
5761 """Return raw tag data.
5762
5763 Returns:
5764 bytes: The raw tag data representing the curve.
5765 """
5766 # Identity
5767 curve_entries_count = 0 if len(self) == 1 and self[0] == 1.0 else len(self)
5768 tag_data = [b"curv", b"\0" * 4, uInt32Number_tohex(curve_entries_count)]
5769 if curve_entries_count == 1:
5770 # Gamma
5771 tag_data.append(u8Fixed8Number_tohex(self[0]))
5772 elif curve_entries_count:
5773 # Curve
5774 tag_data.extend(uInt16Number_tohex(curveEntry) for curveEntry in self)
5775 return b"".join(tag_data)
5776
5777 @tagData.setter
5778 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
5779 """Set the tag data from raw bytes.
5780
5781 Does nothing, as this tag is read-only.
5782
5783 Args:
5784 tagData (bytes): Raw tag data to set.
5785 """
5786
5787
5788 class ParametricCurveType(ICCProfileTag):
5789 """ICC ParametricCurveType tag.
5790
5791 Args:
5792 tagData (bytes, optional): Raw tag data. Defaults to None.
5793 tagSignature (str, optional): Tag signature. Defaults to None.
5794 profile (ICCProfile, optional): ICC profile instance. Defaults to None.
5795 """
5796
5797 def __init__(
5798 self,
5799 tagData: None | bytes = None, # noqa: N803
5800 tagSignature: None | str = None, # noqa: N803
5801 profile: None | ICCProfile = None,
5802 ) -> None:
5803 ICCProfileTag.__init__(self, tagData, tagSignature)
5804 self.profile = profile
5805 self.params = {}
5806 if not tagData:
5807 return
5808 fntype = uInt16Number(tagData[8:10])
5809 numparams = {0: 1, 1: 3, 2: 4, 3: 5, 4: 7}.get(fntype)
5810 for i, param in enumerate("gabcdef"[:numparams]):
5811 self.params[param] = s15Fixed16Number(tagData[12 + i * 4 : 12 + i * 4 + 4])
5812
5813 def __apply(self, v: float) -> float:
5814 """Apply the transfer function to a value.
5815
5816 Args:
5817 v (float): The input value to apply the transfer function to.
5818
5819 Returns:
5820 float: The output value after applying the transfer function.
5821 """
5822 if len(self.params) == 1:
5823 return v ** self.params["g"]
5824 if len(self.params) == 3:
5825 # CIE 122-1966
5826 if v >= -self.params["b"] / self.params["a"]:
5827 return (self.params["a"] * v + self.params["b"]) ** self.params["g"]
5828 return 0
5829 if len(self.params) == 4:
5830 # IEC 61966-3
5831 if v >= -self.params["b"] / self.params["a"]:
5832 return (self.params["a"] * v + self.params["b"]) ** self.params[
5833 "g"
5834 ] + self.params["c"]
5835 return self.params["c"]
5836 if len(self.params) == 5:
5837 # IEC 61966-2.1 (sRGB)
5838 if v >= self.params["d"]:
5839 return (self.params["a"] * v + self.params["b"]) ** self.params["g"]
5840 return self.params["c"] * v
5841 if len(self.params) == 7:
5842 if v >= self.params["d"]:
5843 return (self.params["a"] * v + self.params["b"]) ** self.params[
5844 "g"
5845 ] + self.params["e"]
5846 return self.params["c"] * v + self.params["f"]
5847 raise NotImplementedError(f"Invalid number of parameters: {len(self.params):d}")
5848
5849 def apply(self, v: float) -> float:
5850 """Apply the transfer function to a value.
5851
5852 Args:
5853 v (float): The input value to apply the transfer function to.
5854
5855 Returns:
5856 float: The output value after applying the transfer function,
5857 clipped to [0, 1].
5858 """
5859 # clip result to [0, 1]
5860 return max(0, min(self.__apply(v), 1))
5861
5862 def get_trc(self, size: int = 1024) -> CurveType:
5863 """Return a CurveType object with the transfer function.
5864
5865 Args:
5866 size (int): Number of points in the curve. Defaults to 1024.
5867
5868 Returns:
5869 CurveType: A CurveType object representing the transfer function.
5870 """
5871 curv = CurveType(profile=self.profile)
5872 for i in range(size):
5873 curv.append(self.apply(i / (size - 1.0)) * 65535)
5874 return curv
5875
5876
5877 class DateTimeType(ICCProfileTag, datetime.datetime):
5878 """ICC DateTimeType tag.
5879
5880 Args:
5881 tagData (bytes): The raw tag data containing the date and time.
5882 tagSignature (str): The signature of the tag (not used here).
5883 """
5884
5885 def __new__(cls, tagData: bytes, tagSignature: str) -> datetime.datetime: # noqa: N803
5886 """Create a new DateTimeType instance.
5887
5888 Args:
5889 cls: The class to instantiate.
5890 tagData: The raw tag data containing the date and time.
5891 tagSignature: The signature of the tag (not used here).
5892
5893 Returns:
5894 datetime.datetime: A new instance of datetime.datetime.
5895 """
5896 dt = dateTimeNumber(tagData[8:20])
5897 return datetime.datetime.__new__(
5898 cls, dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second
5899 )
5900
5901
5902 class DictList(list):
5903 """ICC dictType Tag list."""
5904
5905 def __getitem__(self, key: slice | SupportsIndex) -> Any: # noqa: ANN401
5906 """Get item from list.
5907
5908 Args:
5909 key (slice | SupportsIndex): Key of the item.
5910
5911 Returns:
5912 Any: Value of the item.
5913 """
5914 for item in self:
5915 if item[0] == key:
5916 return item
5917 raise KeyError(key)
5918
5919 def __setitem__(self, key: slice | SupportsIndex, value: Any) -> None: # noqa: ANN401
5920 """Set item in list.
5921
5922 Args:
5923 key (slice | SupportsIndex): Key of the item.
5924 value (Any): Value of the item.
5925 """
5926 if not isinstance(value, DictListItem):
5927 self.append(DictListItem((key, value)))
5928
5929
5930 class DictListItem(list):
5931 """ICC dictType Tag item."""
5932
5933 def __iadd__(self, value: Any) -> Self: # noqa: ANN401
5934 """Add value to the last item in the list.
5935
5936 Args:
5937 value (Any): Value to add.
5938
5939 Returns:
5940 DictListItem: The updated list item.
5941 """
5942 self[-1] += value
5943 return self
5944
5945
5946 class DictType(ICCProfileTag, AODict):
5947 """ICC dictType Tag.
5948
5949 Implements all features of 'Dictionary Type and Metadata TAG Definition'
5950 (ICC spec revision 2010-02-25), including shared data (the latter will
5951 only be effective for mutable types, ie. MultiLocalizedUnicodeType)
5952
5953 Examples:
5954
5955 tag[key] Returns the (non-localized) value
5956 tag.getname(key, locale='en_US') Returns the localized name if present
5957 tag.getvalue(key, locale='en_US') Returns the localized value if present
5958 tag[key] = value Sets the (non-localized) value
5959
5960 """
5961
5962 def __init__(
5963 self,
5964 tagData: None | bytes = None, # noqa: N803
5965 tagSignature: None | str = None, # noqa: N803
5966 ) -> None:
5967 ICCProfileTag.__init__(self, tagData, tagSignature)
5968 AODict.__init__(self)
5969 if not tagData:
5970 return
5971 numrecords = uInt32Number(tagData[8:12])
5972 recordlen = uInt32Number(tagData[12:16])
5973 if recordlen not in (16, 24, 32):
5974 print(
5975 f"Error (non-critical): '{tagData[:4]}' invalid record length "
5976 f"(expected 16, 24 or 32, got {recordlen})"
5977 )
5978 return
5979 elements = {}
5980 for n in range(numrecords):
5981 record = tagData[16 + n * recordlen : 16 + (n + 1) * recordlen]
5982 if len(record) < recordlen:
5983 print(
5984 f"Error (non-critical): '{tagData[:4]}' record {n} too short "
5985 f"(expected {recordlen} bytes, got {len(record)} bytes)"
5986 )
5987 break
5988 for key, offsetpos in (
5989 ("name", 0),
5990 ("value", 8),
5991 ("display_name", 16),
5992 ("display_value", 24),
5993 ):
5994 if (
5995 offsetpos in (0, 8)
5996 or recordlen == offsetpos + 8
5997 or recordlen == offsetpos + 16
5998 ):
5999 # Required:
6000 # Bytes 0..3, 4..7: Name offset and size
6001 # Bytes 8..11, 12..15: Value offset and size
6002 # Optional:
6003 # Bytes 16..23, 24..23: Display name offset and size
6004 # Bytes 24..27, 28..31: Display value offset and size
6005 offset = uInt32Number(record[offsetpos : offsetpos + 4])
6006 size = uInt32Number(record[offsetpos + 4 : offsetpos + 8])
6007 if offset > 0:
6008 if (offset, size) in elements:
6009 # Use existing element if same offset and size
6010 # This will really only make a difference for
6011 # mutable types i.e. MultiLocalizedUnicodeType
6012 data = elements[(offset, size)]
6013 else:
6014 data = tagData[offset : offset + size]
6015 try:
6016 if key.startswith("display_"):
6017 data = MultiLocalizedUnicodeType(data, "mluc")
6018 else:
6019 data = data.decode("UTF-16-BE", "replace").rstrip(
6020 "\0"
6021 )
6022 except Exception:
6023 print(
6024 "Error (non-critical): could not decode "
6025 f"'{tagData[:4]}', offset {offset}, length {size}"
6026 )
6027 # Remember element by offset and size
6028 elements[(offset, size)] = data
6029 if key == "name":
6030 name = data
6031 self[name] = ""
6032 else:
6033 self.get(name)[key] = data
6034
6035 def __getitem__(self, name: str) -> Any: # noqa: ANN401
6036 """Get item from dict.
6037
6038 Args:
6039 name (str): Name of the item.
6040
6041 Returns:
6042 Any: Value of the item.
6043 """
6044 return self.get(name).value
6045
6046 def __setitem__(self, name: str, value: Any) -> None: # noqa: ANN401
6047 """Set item in dict.
6048
6049 Args:
6050 name (str): Name of the item.
6051 value (Any): Value of the item.
6052 """
6053 AODict.__setitem__(self, name, ADict(value=value))
6054
6055 @property
6056 def tagData(self) -> bytes: # noqa: N802
6057 """Return raw tag data.
6058
6059 Returns:
6060 bytes: The raw tag data representing the dictionary.
6061 """
6062 numrecords = len(self)
6063 recordlen = 16
6064 keys = ("name", "value")
6065 for value in self.values():
6066 if not isinstance(value, dict):
6067 continue
6068 if "display_value" in value:
6069 recordlen = 32
6070 break
6071 if "display_name" in value:
6072 recordlen = 24
6073 if recordlen > 16:
6074 keys += ("display_name",)
6075 if recordlen > 24:
6076 keys += ("display_value",)
6077 tag_data = [
6078 b"dict",
6079 b"\0" * 4,
6080 uInt32Number_tohex(numrecords),
6081 uInt32Number_tohex(recordlen),
6082 ]
6083 storage_offset = 16 + numrecords * recordlen
6084 storage = []
6085 elements = []
6086 offsets = []
6087 for item in self.items():
6088 for key in keys:
6089 if key == "name":
6090 element = item[0]
6091 else:
6092 element = item[1].get(key) if isinstance(item[1], dict) else item[1]
6093 if element is None:
6094 offset = 0
6095 size = 0
6096 elif element in elements:
6097 # Use existing offset and size if same element
6098 offset, size = offsets[elements.index(element)]
6099 else:
6100 offset = storage_offset + len(b"".join(storage))
6101 if isinstance(element, MultiLocalizedUnicodeType):
6102 data = element.tagData
6103 else:
6104 data = str(element).encode("UTF-16-BE")
6105 size = len(data)
6106 if isinstance(element, MultiLocalizedUnicodeType):
6107 # Remember element, offset and size
6108 elements.append(element)
6109 offsets.append((offset, size))
6110 # Pad all data with binary zeros so it lies on
6111 # 4-byte boundaries
6112 padding = math.ceil(size / 4.0) * 4 - size
6113 data += b"\0" * padding
6114 storage.append(data)
6115 tag_data.append(uInt32Number_tohex(offset))
6116 tag_data.append(uInt32Number_tohex(size))
6117 tag_data.extend(storage)
6118 return b"".join(tag_data)
6119
6120 @tagData.setter
6121 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
6122 """Set raw tag data.
6123
6124 Does nothing, as the tagData is read-only.
6125
6126 Args:
6127 tagData (bytes): The raw tag data to set.
6128 """
6129
6130 def getname(
6131 self,
6132 name: str,
6133 default: None | Any = None, # noqa: ANN401
6134 locale: str = "en_US",
6135 ) -> str:
6136 """Convenience function to get (localized) names.
6137
6138 Args:
6139 name (str): The name of the item to get.
6140 default (Any, optional): Default value to return if the item is not
6141 found. Defaults to None.
6142 locale (str, optional): Locale to use for localized names. Defaults
6143 to "en_US".
6144
6145 Returns:
6146 str: The localized name of the item if available, otherwise the
6147 default value or the non-localized name.
6148 """
6149 item = self.get(name, default)
6150 if item is default:
6151 return default
6152 if locale and "display_name" in item:
6153 return item.display_name.get_localized_string(*locale.split("_"))
6154 return name
6155
6156 def getvalue(
6157 self,
6158 name: str,
6159 default: None | Any = None, # noqa: ANN401
6160 locale: str = "en_US",
6161 ) -> Any: # noqa: ANN401
6162 """Convenience function to get (localized) values.
6163
6164 Args:
6165 name (str): The name of the item to get.
6166 default (Any, optional): Default value to return if the item is not
6167 found. Defaults to None.
6168 locale (str, optional): Locale to use for localized values.
6169 Defaults to "en_US".
6170
6171 Returns:
6172 Any: The localized value of the item if available, otherwise the
6173 default value or the non-localized value.
6174 """
6175 item = self.get(name, default)
6176 if item is default:
6177 return default
6178 if locale and "display_value" in item:
6179 return item.display_value.get_localized_string(*locale.split("_"))
6180 if isinstance(item, dict):
6181 return item.value
6182 return item
6183
6184 def setitem(
6185 self,
6186 name: str,
6187 value: Any, # noqa: ANN401
6188 display_name: None | dict = None,
6189 display_value: None | dict = None,
6190 ) -> None:
6191 """Convenience function to set items.
6192
6193 display_name and display_value (if given) should be dict types with
6194 country -> language -> string mappings, e.g.:
6195
6196 {"en": {"US": u"localized string"},
6197 "de": {"DE": u"localized string", "CH": u"localized string"}}
6198
6199
6200 Args:
6201 name (str): The name of the item to set.
6202 value (Any): The value to set for the item.
6203 display_name (None | dict, optional): Localized display names for
6204 the item.
6205 display_value (None | dict, optional): Localized display values
6206 for the item.
6207 """
6208 self[name] = value
6209 item = self.get(name)
6210 if display_name:
6211 item.display_name = MultiLocalizedUnicodeType()
6212 item.display_name.update(display_name)
6213 if display_value:
6214 item.display_value = MultiLocalizedUnicodeType()
6215 item.display_value.update(display_value)
6216
6217 def to_json(
6218 self, encoding: str = "UTF-8", errors: str = "replace", locale: str = "en_US"
6219 ) -> str:
6220 """Return a JSON representation.
6221
6222 Display names/values are used if present.
6223
6224 Args:
6225 encoding (str, optional): Encoding to use for the JSON string.
6226 Defaults to "UTF-8".
6227 errors (str, optional): Error handling scheme for encoding.
6228 Defaults to "replace".
6229 locale (str, optional): Locale to use for localized names/values.
6230 Defaults to "en_US".
6231
6232 Returns:
6233 str: JSON representation of the DictType object.
6234 """
6235 return DictTypeJSONEncoder(locale=locale).encode(self)
6236
6237
6238 class DictTypeJSONEncoder(json.JSONEncoder):
6239 """JSON Encoder for the DictType class."""
6240
6241 def __init__(self, *args, **kwargs) -> None:
6242 self.locale = kwargs.pop("locale") or "en_US"
6243 super().__init__(*args, **kwargs)
6244
6245 def default(self, obj: Any) -> dict: # noqa: ANN401
6246 """Default method for encoding objects to JSON.
6247
6248 Args:
6249 obj (object): The object to encode.
6250
6251 Returns:
6252 dict: Encoded object as a dictionary.
6253 """
6254 return_data = {}
6255 regex = re.compile(r"\\x([0-9a-f]{2})")
6256 repl_str = r"\\u00\1"
6257 for name in obj:
6258 value = obj.getvalue(name, None, self.locale)
6259 name = obj.getname(name, None, self.locale)
6260 value = '"{}"'.format(repr(str(value))[2:-1].replace('"', '\\"'))
6261 name = regex.sub(repl_str, name)
6262 value = regex.sub(repl_str, value)
6263 return_data[name] = value
6264 return return_data
6265
6266
6267 class MakeAndModelType(ICCProfileTag, ADict):
6268 """ICC makeAndModelType tag.
6269
6270 Args:
6271 tagData (bytes): The raw tag data.
6272 tagSignature (str): The signature of the tag.
6273 """
6274
6275 def __init__(self, tagData: bytes, tagSignature: str) -> None: # noqa: N803
6276 ICCProfileTag.__init__(self, tagData, tagSignature)
6277 self.update({"manufacturer": tagData[10:12], "model": tagData[14:16]})
6278
6279
6280 class MeasurementType(ICCProfileTag, ADict):
6281 """ICC measurementType tag.
6282
6283 Args:
6284 tagData (bytes): The raw tag data.
6285 tagSignature (str): The signature of the tag.
6286 """
6287
6288 def __init__(self, tagData: bytes, tagSignature: str) -> None: # noqa: N803
6289 ICCProfileTag.__init__(self, tagData, tagSignature)
6290
6291 print(f"tagData[8:12]: {tagData[8:12]}")
6292
6293 self.update(
6294 {
6295 "observer": Observer(tagData[8:12]),
6296 "backing": XYZNumber(tagData[12:24]),
6297 "geometry": Geometry(tagData[24:28]),
6298 "flare": u16Fixed16Number(tagData[28:32]),
6299 "illuminantType": Illuminant(tagData[32:36]),
6300 }
6301 )
6302
6303
6304 class MultiLocalizedUnicodeType(ICCProfileTag, AODict): # ICC v4
6305 """ICC v4 MultiLocalizedUnicodeType tag.
6306
6307 Args:
6308 tagData (None | bytes, optional): Raw tag data. Defaults to None.
6309 tagSignature (None | str, optional): Tag signature. Defaults to None.
6310 """
6311
6312 def __init__(
6313 self,
6314 tagData: None | bytes = None, # noqa: N803
6315 tagSignature: None | str = None, # noqa: N803
6316 ) -> None:
6317 ICCProfileTag.__init__(self, tagData, tagSignature)
6318 AODict.__init__(self)
6319 if not tagData:
6320 return
6321 records_count = uInt32Number(tagData[8:12])
6322 record_size = uInt32Number(tagData[12:16]) # 12
6323 if record_size != 12:
6324 print(
6325 f"Warning (non-critical): '{tagData[:4]}' invalid record length "
6326 f"(expected 12, got {record_size})"
6327 )
6328 record_size = max(record_size, 12)
6329 records = tagData[16 : 16 + record_size * records_count]
6330 for _count in range(records_count):
6331 record = records[:record_size]
6332 if len(record) < 12:
6333 continue
6334 record_language_code = record[:2]
6335 record_country_code = record[2:4]
6336 record_length = uInt32Number(record[4:8])
6337 record_offset = uInt32Number(record[8:12])
6338 self.add_localized_string(
6339 record_language_code,
6340 record_country_code,
6341 str(
6342 tagData[record_offset : record_offset + record_length],
6343 "utf-16-be",
6344 "replace",
6345 ),
6346 )
6347 records = records[record_size:]
6348
6349 def __str__(self) -> str:
6350 """Return tag as string.
6351
6352 Returns:
6353 str: The first localized string in the tag, or an empty string if
6354 no localized strings are available.
6355 """
6356 # TODO: Needs some work re locales
6357 # (currently if en-UK or en-US is not found, simply the first entry
6358 # is returned)
6359 if b"en" in self:
6360 for country_code in (b"UK", b"US"):
6361 if country_code in self[b"en"]:
6362 return self[b"en"][country_code]
6363 if self[b"en"]:
6364 # return first value
6365 return next(iter(self[b"en"].values()))
6366 return ""
6367 if len(self):
6368 # return first value of the first dictionary
6369 return next(iter(next(iter(self.values())).values()))
6370 return ""
6371
6372 def add_localized_string(
6373 self, languagecode: str, countrycode: str, localized_string: str
6374 ) -> None:
6375 """Convenience function for adding localized strings."""
6376 if languagecode not in self:
6377 self[languagecode] = AODict()
6378 self[languagecode][countrycode] = localized_string.strip("\0")
6379
6380 def get_localized_string(
6381 self, languagecode: str = "en", countrycode: str = "US"
6382 ) -> str:
6383 """Convenience function for retrieving localized strings.
6384
6385 Falls back to first locale available if the requested one isn't
6386
6387 Args:
6388 languagecode (str): The language code to retrieve the string for.
6389 Defaults to "en".
6390 countrycode (str): The country code to retrieve the string for.
6391 Defaults to "US".
6392
6393 Returns:
6394 str: The localized string for the given language and country code,
6395 or the first available string if the requested one is not
6396 found.
6397 """
6398 try:
6399 return self[languagecode][countrycode]
6400 except KeyError:
6401 return str(self)
6402
6403 @property
6404 def tagData(self) -> bytes: # noqa: N802
6405 """Return raw tag data."""
6406 tag_data = [b"mluc", b"\0" * 4]
6407 records_count = 0
6408 for language_code in self:
6409 for _ in self[language_code]:
6410 records_count += 1
6411 tag_data.append(uInt32Number_tohex(records_count))
6412 record_size = 12
6413 tag_data.append(uInt32Number_tohex(record_size))
6414 storage_offset = 16 + record_size * records_count
6415 storage = []
6416 offsets = []
6417 for language_code in self:
6418 for country_code in self[language_code]:
6419 tag_data.append(language_code + country_code)
6420 data = self[language_code][country_code].encode("UTF-16-BE")
6421 if data in storage:
6422 offset, record_length = offsets[storage.index(data)]
6423 else:
6424 record_length = len(data)
6425 offset = len("".join(storage))
6426 offsets.append((offset, record_length))
6427 storage.append(data)
6428 tag_data.append(uInt32Number_tohex(record_length))
6429 tag_data.append(uInt32Number_tohex(storage_offset + offset))
6430 tag_data.append(
6431 b"".join(storage)
6432 ) # TODO: Are you sure that this needs to be bytes
6433 return b"".join(tag_data)
6434
6435 @tagData.setter
6436 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
6437 """Set raw tag data.
6438
6439 Does nothing, as this tag is read-only.
6440
6441 Args:
6442 tagData (bytes): Raw tag data to set.
6443 """
6444
6445
6446 class ProfileSequenceDescType(ICCProfileTag, list):
6447 """ICC profileSequenceDescType tag.
6448
6449 Args:
6450 tagData (None | bytes, optional): Raw tag data. Defaults to None.
6451 tagSignature (None | str, optional): Tag signature. Defaults to None.
6452 profile (None | ICCProfile, optional): The ICC profile associated with
6453 this tag. Defaults to None.
6454 """
6455
6456 def __init__(
6457 self,
6458 tagData: None | bytes = None, # noqa: N803
6459 tagSignature: None | str = None, # noqa: N803
6460 profile: None | ICCProfile = None,
6461 ) -> None:
6462 ICCProfileTag.__init__(self, tagData, tagSignature)
6463 self.profile = profile
6464 if not tagData:
6465 return
6466 count = uInt32Number(tagData[8:12])
6467 desc_data = tagData[12:]
6468 while count:
6469 # NOTE: Like in the profile header, the attributes are a 64 bit
6470 # value, but the least significant 32 bits (big-endian) are
6471 # reserved for the ICC.
6472 attributes = uInt32Number(desc_data[8:12])
6473 desc = {
6474 "manufacturer": desc_data[0:4],
6475 "model": desc_data[4:8],
6476 "attributes": {
6477 "reflective": attributes & 1 == 0,
6478 "glossy": attributes & 2 == 0,
6479 "positive": attributes & 4 == 0,
6480 "color": attributes & 8 == 0,
6481 },
6482 "tech": desc_data[16:20],
6483 }
6484 desc_data = desc_data[20:]
6485 for desc_type in ("dmnd", "dmdd"):
6486 tag_type = desc_data[0:4]
6487 if tag_type == "desc":
6488 cls = TextDescriptionType
6489 elif tag_type == "mluc":
6490 cls = MultiLocalizedUnicodeType
6491 else:
6492 print(
6493 "Error (non-critical): could not fully decode 'pseq' - "
6494 f"unknown {desc_type!r} tag type {tag_type!r}"
6495 )
6496 count = 1 # Skip remaining
6497 break
6498 desc[desc_type] = cls(desc_data)
6499 desc_data = desc_data[len(desc[desc_type].tagData) :]
6500 self.append(desc)
6501 count -= 1
6502
6503 def add(self, profile: ICCProfile) -> None:
6504 """Add description structure of profile.
6505
6506 Args:
6507 profile (ICCProfile): The ICC profile to add.
6508 """
6509 desc = {}
6510 desc.update(profile.device)
6511 desc["tech"] = profile.tags.get("tech", b"").ljust(4, b"\0")[:4]
6512 for desc_type in ("dmnd", "dmdd"):
6513 if self.profile.version >= 4:
6514 cls = MultiLocalizedUnicodeType
6515 else:
6516 cls = TextDescriptionType
6517 if self.profile.version < 4 and profile.version < 4:
6518 # Both profiles not v4
6519 tag = profile.tags.get(desc_type, cls())
6520 else:
6521 tag = cls()
6522 description = str(profile.tags.get(desc_type, ""))
6523 if self.profile.version < 4:
6524 # Other profile is v4
6525 tag.ASCII = description.encode("ASCII", "asciize")
6526 if description != tag.ASCII:
6527 tag.Unicode = description
6528 else:
6529 # Other profile is v2
6530 tag.add_localized_string("en", "US", description)
6531 desc[desc_type] = tag
6532 self.append(desc)
6533
6534 @property
6535 def tagData(self) -> bytes: # noqa: N802
6536 """Return raw tag data.
6537
6538 Returns:
6539 bytes: The raw tag data formatted as bytes.
6540 """
6541 tag_data = [b"pseq", b"\0" * 4, uInt32Number_tohex(len(self))]
6542 for desc in self:
6543 tag_data.append(desc.get("manufacturer", b"").ljust(4, b"\0")[:4])
6544 tag_data.append(desc.get("model", b"").ljust(4, b"\0")[:4])
6545 attributes = 0
6546 for name, bit in {
6547 "reflective": 1,
6548 "glossy": 2,
6549 "positive": 4,
6550 "color": 8,
6551 }.items():
6552 if not desc.get("attributes", {}).get(name):
6553 attributes |= bit
6554 tag_data.append(uInt32Number_tohex(attributes) + b"\0" * 4)
6555 tag_data.append(desc.get("tech", b"").ljust(4, b"\0")[:4])
6556 tag_data.extend(
6557 desc.get(desc_type, b"").tagData for desc_type in ("dmnd", "dmdd")
6558 )
6559 return b"".join(tag_data)
6560
6561 @tagData.setter
6562 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
6563 """Set raw tag data.
6564
6565 Does nothing, as this tag is read-only.
6566
6567 Args:
6568 tagData (bytes): Raw tag data to set.
6569 """
6570
6571
6572 class S15Fixed16ArrayType(ICCProfileTag, list):
6573 """ICC s15Fixed16ArrayType tag.
6574
6575 Args:
6576 tagData (bytes, optional): Raw tag data. Defaults to None.
6577 tagSignature (str, optional): Tag signature. Defaults to None.
6578 """
6579
6580 def __init__(
6581 self,
6582 tagData: None | bytes = None, # noqa: N803
6583 tagSignature: None | str = None, # noqa: N803
6584 ) -> None:
6585 ICCProfileTag.__init__(self, tagData, tagSignature)
6586 if tagData:
6587 data = tagData[8:]
6588 while data:
6589 self.append(s15Fixed16Number(data[0:4]))
6590 data = data[4:]
6591
6592 @property
6593 def tagData(self) -> bytes: # noqa: N802
6594 """Return raw tag data.
6595
6596 Returns:
6597 bytes: The raw tag data formatted as bytes.
6598 """
6599 tag_data = [b"sf32", b"\0" * 4]
6600 tag_data.extend(s15Fixed16Number_tohex(value) for value in self)
6601 return b"".join(tag_data)
6602
6603 @tagData.setter
6604 def tagData(self, tag_data: bytes) -> None: # noqa: N802
6605 """Set raw tag data.
6606
6607 Does nothing, as this tag is read-only.
6608
6609 Args:
6610 tag_data (bytes): Raw tag data to set.
6611 """
6612
6613
6614 def SignatureType(tagData: bytes, tagSignature: str) -> Text: # noqa: N802, N803
6615 """Generate ICC signatureType tag.
6616
6617 Args:
6618 tagData (bytes): The raw tag data containing the signature.
6619 tagSignature (str): The signature of the tag.
6620
6621 Returns:
6622 Text: An instance of the Text class representing the tag.
6623 """
6624 tag = Text(tagData[8:12].rstrip(b"\0"))
6625 tag.tagData = tagData
6626 tag.tagSignature = tagSignature
6627 return tag
6628
6629
6630 class TextDescriptionType(ICCProfileTag, ADict): # ICC v2
6631 """ICC textDescriptionType tag.
6632
6633 Args:
6634 tagData (None | bytes, optional): Raw tag data. Defaults to None.
6635 tagSignature (None | str, optional): Tag signature. Defaults to None.
6636 """
6637
6638 def __init__(
6639 self,
6640 tagData: None | bytes = None, # noqa: N803
6641 tagSignature: None | str = None, # noqa: N803
6642 ) -> None:
6643 ICCProfileTag.__init__(self, tagData, tagSignature)
6644 self.ASCII = b""
6645 if not tagData:
6646 return
6647 ascii_description_length = uInt32Number(tagData[8:12])
6648 if ascii_description_length:
6649 ascii_description = tagData[12 : 12 + ascii_description_length].strip(
6650 b"\0\n\r "
6651 )
6652 if ascii_description:
6653 self.ASCII = ascii_description
6654 unicode_offset = 12 + ascii_description_length
6655 self.unicodeLanguageCode = uInt32Number(
6656 tagData[unicode_offset : unicode_offset + 4]
6657 )
6658 unicode_description_length = uInt32Number(
6659 tagData[unicode_offset + 4 : unicode_offset + 8]
6660 )
6661 if unicode_description_length:
6662 if unicode_offset + 8 + unicode_description_length * 2 > len(tagData):
6663 # Damn you MS. The Unicode character count should be the number of
6664 # double-byte characters (including trailing unicode NUL), not the
6665 # number of bytes as in the profiles created by Vista and later
6666 print(
6667 f"Warning (non-critical): '{tagData[:4]}' Unicode part end points "
6668 "past the tag data, assuming number of bytes instead "
6669 "of number of characters for length"
6670 )
6671 unicode_description_length /= 2
6672 if (
6673 tagData[
6674 unicode_offset + 8 + unicode_description_length : unicode_offset
6675 + 8
6676 + unicode_description_length
6677 + 2
6678 ]
6679 == b"\0\0"
6680 ):
6681 print(
6682 f"Warning (non-critical): '{tagData[:4]}' Unicode part "
6683 "seems to be a single-byte string (double-byte "
6684 "string expected)"
6685 )
6686 char_bytes = 1 # fix for fubar'd desc
6687 else:
6688 char_bytes = 2
6689 unicode_description = tagData[
6690 unicode_offset + 8 : unicode_offset
6691 + 8
6692 + (unicode_description_length) * char_bytes
6693 ]
6694 try:
6695 if char_bytes == 1:
6696 unicode_description = str(unicode_description, errors="replace")
6697 elif unicode_description[:2] == b"\xfe\xff":
6698 # UTF-16 Big Endian
6699 if DEBUG:
6700 print("UTF-16 Big endian")
6701 unicode_description = unicode_description[2:]
6702 if (
6703 len(unicode_description.split(b" "))
6704 == unicode_description_length - 1
6705 ):
6706 print(
6707 f"Warning (non-critical): '{tagData[:4]}' "
6708 "Unicode part starts with UTF-16 big "
6709 "endian BOM, but actual contents seem "
6710 "to be UTF-16 little endian"
6711 )
6712 # fix fubar'd desc
6713 unicode_description = str(
6714 b"\0".join(unicode_description.split(b" ")),
6715 "utf-16-le",
6716 errors="replace",
6717 )
6718 else:
6719 unicode_description = str(
6720 unicode_description, "utf-16-be", errors="replace"
6721 )
6722 elif unicode_description[:2] == b"\xff\xfe":
6723 # UTF-16 Little Endian
6724 if DEBUG:
6725 print("UTF-16 Little endian")
6726 unicode_description = unicode_description[2:]
6727 if unicode_description[0] == b"\0":
6728 print(
6729 f"Warning (non-critical): '{tagData[:4]}' "
6730 "Unicode part starts with UTF-16 "
6731 "little endian BOM, but actual "
6732 "contents seem to be UTF-16 big "
6733 "endian"
6734 )
6735 # fix fubar'd desc
6736 unicode_description = str(
6737 unicode_description, "utf-16-be", errors="replace"
6738 )
6739 else:
6740 unicode_description = str(
6741 unicode_description, "utf-16-le", errors="replace"
6742 )
6743 else:
6744 if DEBUG:
6745 print("ASSUMED UTF-16 Big Endian")
6746 unicode_description = str(
6747 unicode_description, "utf-16-be", errors="replace"
6748 )
6749 unicode_description = unicode_description.strip("\0\n\r ")
6750 if unicode_description:
6751 if unicode_description.find("\0") < 0:
6752 self.Unicode = unicode_description
6753 else:
6754 print(
6755 "Error (non-critical): could not decode "
6756 f"'{tagData[:4]}' Unicode part - null byte(s) "
6757 "encountered"
6758 )
6759 except UnicodeDecodeError:
6760 print(
6761 "UnicodeDecodeError (non-critical): could not "
6762 f"decode '{tagData[:4]}' Unicode part"
6763 )
6764 else:
6765 char_bytes = 1
6766 mac_offset = unicode_offset + 8 + unicode_description_length * char_bytes
6767 self.macScriptCode = 0
6768 if len(tagData) > mac_offset + 2:
6769 self.macScriptCode = uInt16Number(tagData[mac_offset : mac_offset + 2])
6770 mac_description_length = ord(tagData[mac_offset + 2 : mac_offset + 3])
6771 if mac_description_length:
6772 try:
6773 mac_description = str(
6774 tagData[
6775 mac_offset + 3 : mac_offset + 3 + mac_description_length
6776 ],
6777 "mac-" + ENCODINGS["mac"][self.macScriptCode],
6778 errors="replace",
6779 ).strip("\0\n\r ")
6780 if mac_description:
6781 self.Macintosh = mac_description
6782 except KeyError:
6783 print(
6784 f"KeyError (non-critical): could not decode '{tagData[:4]}' "
6785 f"Macintosh part (unsupported encoding {self.macScriptCode})"
6786 )
6787 except LookupError:
6788 print(
6789 f"LookupError (non-critical): could not decode '{tagData[:4]}' "
6790 "Macintosh part (unsupported encoding "
6791 f"'{ENCODINGS['mac'][self.macScriptCode]}')"
6792 )
6793 except UnicodeDecodeError:
6794 print(
6795 "UnicodeDecodeError (non-critical): could not decode "
6796 f"'{tagData[:4]}' Macintosh part"
6797 )
6798
6799 @property
6800 def tagData(self) -> bytes: # noqa: N802
6801 """Return raw tag data.
6802
6803 Returns:
6804 bytes: The raw tag data for the textDescriptionType tag.
6805 """
6806 tag_data = [
6807 b"desc",
6808 b"\0" * 4,
6809 uInt32Number_tohex(len(self.ASCII) + 1), # count of ASCII chars + 1
6810 self.ASCII + b"\0", # ASCII desc, \0 terminated
6811 uInt32Number_tohex(self.get("unicodeLanguageCode", 0)),
6812 ]
6813 if "Unicode" in self:
6814 tag_data.extend(
6815 [
6816 # count of Unicode chars + 2 (UTF-16-BE BOM + trailing UTF-16 NUL,
6817 # 1 char = 2 byte)
6818 uInt32Number_tohex(len(self.Unicode) + 2),
6819 b"\xfe\xff" + self.Unicode.encode("utf-16-be", "replace") + b"\0\0",
6820 ]
6821 ) # Unicode desc, \0\0 terminated
6822 else:
6823 tag_data.append(uInt32Number_tohex(0)) # Unicode desc length = 0
6824 tag_data.append(uInt16Number_tohex(self.get("macScriptCode", 0)))
6825 if "Macintosh" in self:
6826 mac_description = self.Macintosh[:66]
6827 tag_data.extend(
6828 [
6829 uInt8Number_tohex(
6830 len(mac_description) + 1
6831 ), # count of Macintosh chars + 1
6832 mac_description.encode(
6833 "mac-" + ENCODINGS["mac"][self.get("macScriptCode", 0)],
6834 "replace",
6835 )
6836 + (b"\0" * (67 - len(mac_description))),
6837 ]
6838 )
6839 else:
6840 tag_data.extend([b"\0", b"\0" * 67]) # Mac desc length = 0
6841 return b"".join(tag_data)
6842
6843 @tagData.setter
6844 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
6845 """Set tag data.
6846
6847 Does nothing, as this tag is read-only.
6848
6849 Args:
6850 tagData (bytes): The raw tag data to set.
6851 """
6852
6853 def __str__(self) -> str:
6854 """Return tag as string.
6855
6856 Returns:
6857 str: The localized string if available, otherwise the ASCII
6858 representation of the tag.
6859 """
6860 if "Unicode" not in self and len(str(self.ASCII)) < 67:
6861 # Do not use Macintosh description if ASCII length >= 67
6862 localized_types = ("Macintosh", "ASCII")
6863 else:
6864 localized_types = ("Unicode", "ASCII")
6865
6866 for localized_type in localized_types:
6867 if localized_type not in self:
6868 continue
6869 value = self[localized_type]
6870 if not isinstance(value, str):
6871 # Even ASCII description may contain non-ASCII chars, so
6872 # assume system encoding and convert to unicode, replacing
6873 # unknown chars
6874 value = value.decode("utf-8", "replace")
6875 return value
6876 return None
6877
6878
6879 def TextType(tagData: bytes, tagSignature: str) -> Text: # noqa: N802, N803
6880 """Generate an ICC textType tag.
6881
6882 Args:
6883 tagData (bytes): The raw tag data.
6884 tagSignature (str): The signature of the tag, usually "text".
6885
6886 Returns:
6887 Text: An instance of the Text class containing the tag data and
6888 signature.
6889 """
6890 tag = Text(tagData[8:].rstrip(b"\0"))
6891 tag.tagData = tagData
6892 tag.tagSignature = tagSignature
6893 return tag
6894
6895
6896 class VideoCardGammaType(ICCProfileTag, ADict):
6897 """Video Card Gamma Tag.
6898
6899 This tag contains the gamma correction values for the red, green and blue
6900 channels of the video card. The values are stored in a table or as a
6901 formula. The table is a 256-entry table with values ranging from 0 to
6902 65535. The formula is a gamma correction formula with the following
6903 parameters: redMin, redMax, redGamma, greenMin, greenMax, greenGamma,
6904 blueMin, blueMax, blueGamma.
6905
6906 Private tag
6907 http://developer.apple.com/documentation/GraphicsImaging/Reference/ColorSync_Manager/Reference/reference.html#//apple_ref/doc/uid/TP30000259-CH3g-C001473
6908
6909 Args:
6910 tagData (bytes): The raw tag data.
6911 tagSignature (str): The signature of the tag, usually "vcgt".
6912 """
6913
6914 def __init__(self, tagData: bytes, tagSignature: str) -> None: # noqa: N803
6915 ICCProfileTag.__init__(self, tagData, tagSignature)
6916
6917 def is_linear(self, r: bool = True, g: bool = True, b: bool = True) -> bool:
6918 """Check if the gamma correction is linear for the red, green and blue channels.
6919
6920 Args:
6921 r (bool): Whether to check the red channel.
6922 g (bool): Whether to check the green channel.
6923 b (bool): Whether to check the blue channel.
6924
6925 Returns:
6926 bool: True if the gamma correction is linear for the specified
6927 channels.
6928 """
6929 r_points, g_points, b_points, linear_points = self.get_values()
6930 if (
6931 (r and g and b and r_points == g_points == b_points)
6932 or (r and g and r_points == g_points)
6933 or not (g or b)
6934 ):
6935 points = r_points
6936 elif (
6937 (r and b and r_points == b_points)
6938 or (g and b and g_points == b_points)
6939 or not (r or g)
6940 ):
6941 points = b_points
6942 elif g:
6943 points = g_points
6944 return points == linear_points
6945
6946 def get_unique_values(
6947 self, r: bool = True, g: bool = True, b: bool = True
6948 ) -> tuple:
6949 """Return unique values for the red, green and blue channels.
6950
6951 Args:
6952 r (bool): Whether to include red channel values.
6953 g (bool): Whether to include green channel values.
6954 b (bool): Whether to include blue channel values.
6955
6956 Returns:
6957 tuple: Three sets containing the unique values for the red,
6958 """
6959 r_points, g_points, b_points, linear_points = self.get_values()
6960 r_unique = {round(y) for x, y in r_points}
6961 g_unique = {round(y) for x, y in g_points}
6962 b_unique = {round(y) for x, y in b_points}
6963 return r_unique, g_unique, b_unique
6964
6965 def get_values(self, r: bool = True, g: bool = True, b: bool = True) -> tuple:
6966 """Return the gamma correction values for the red, green and blue channels.
6967
6968 Args:
6969 r (bool, optional): Whether to include red channel values.
6970 g (bool, optional): Whether to include green channel values.
6971 b (bool, optional): Whether to include blue channel values.
6972
6973 Returns:
6974 tuple: Four lists containing the red, green, blue, and linear
6975 """
6976 r_points = []
6977 g_points = []
6978 b_points = []
6979 linear_points = []
6980 vcgt = self
6981 if "data" in vcgt: # table
6982 data = list(vcgt["data"])
6983 while len(data) < 3:
6984 data.append(data[0])
6985 irange = list(range(vcgt["entryCount"]))
6986 vmax = math.pow(256, vcgt["entrySize"]) - 1
6987 for i in irange:
6988 j = i * (255.0 / (vcgt["entryCount"] - 1))
6989 linear_points.append(
6990 [j, round(i / float(vcgt["entryCount"] - 1) * 65535)]
6991 )
6992 if r:
6993 n = round(float(data[0][i]) / vmax * 65535)
6994 r_points.append([j, n])
6995 if g:
6996 n = round(float(data[1][i]) / vmax * 65535)
6997 g_points.append([j, n])
6998 if b:
6999 n = round(float(data[2][i]) / vmax * 65535)
7000 b_points.append([j, n])
7001 else: # formula
7002 irange = list(range(256))
7003 step = 100.0 / 255.0
7004 for i in irange:
7005 linear_points.append([i, i / 255.0 * 65535])
7006 if r:
7007 vmin = vcgt["redMin"] * 65535
7008 v = math.pow(step * i / 100.0, vcgt["redGamma"])
7009 vmax = vcgt["redMax"] * 65535
7010 r_points.append([i, round(vmin + v * (vmax - vmin))])
7011 if g:
7012 vmin = vcgt["greenMin"] * 65535
7013 v = math.pow(step * i / 100.0, vcgt["greenGamma"])
7014 vmax = vcgt["greenMax"] * 65535
7015 g_points.append([i, round(vmin + v * (vmax - vmin))])
7016 if b:
7017 vmin = vcgt["blueMin"] * 65535
7018 v = math.pow(step * i / 100.0, vcgt["blueGamma"])
7019 vmax = vcgt["blueMax"] * 65535
7020 b_points.append([i, round(vmin + v * (vmax - vmin))])
7021 return r_points, g_points, b_points, linear_points
7022
7023 def printNormalizedValues( # noqa: N802
7024 self, amount: None | int = None, digits: int = 12
7025 ) -> None:
7026 """Normalize and prints all values in the vcgt (range of 0.0...1.0).
7027
7028 For a 256-entry table with linear values from 0 to 65535:
7029 # REF C1 C2 C3
7030 001 0.000000000000 0.000000000000 0.000000000000 0.000000000000
7031 002 0.003921568627 0.003921568627 0.003921568627 0.003921568627
7032 003 0.007843137255 0.007843137255 0.007843137255 0.007843137255
7033 ...
7034 You can also specify the amount of values to print (where a value
7035 lesser than the entry count will leave out intermediate values)
7036 and the number of digits.
7037
7038 Args:
7039 amount (None | int, optional): The number of values to print.
7040 If None, it defaults to the entryCount if available, otherwise
7041 to 256.
7042 digits (int, optional): The number of digits to round the values
7043 to. Defaults to 12.
7044 """
7045 if amount is None:
7046 # use entryCount if exists, otherwise use the common value
7047 amount = self.entryCount if hasattr(self, "entryCount") else 256
7048 values = self.getNormalizedValues(amount)
7049 entry_count = len(values)
7050 channels = len(values[0])
7051 header = ["REF"]
7052 header.extend(f"C{k + 1}" for k in range(channels))
7053 header = [title.ljust(digits + 2) for title in header]
7054 print("#".ljust(len(str(amount)) + 1) + " ".join(header))
7055 for i, value in enumerate(values):
7056 formatted_values = [
7057 str(round(channel, digits)).ljust(digits + 2, "0") for channel in value
7058 ]
7059 print(
7060 str(i + 1).rjust(len(str(amount)), "0"),
7061 str(round(i / float(entry_count - 1), digits)).ljust(digits + 2, "0"),
7062 " ".join(formatted_values),
7063 )
7064
7065
7066 class VideoCardGammaFormulaType(VideoCardGammaType):
7067 """Video card gamma formula type class.
7068
7069 Args:
7070 tagData (bytes): The raw tag data containing the video LUT curves.
7071 tagSignature (str): The signature of the tag, typically "vcgt".
7072 """
7073
7074 def __init__(self, tagData: bytes, tagSignature: str) -> None: # noqa: N803
7075 VideoCardGammaType.__init__(self, tagData, tagSignature)
7076 data = tagData[12:]
7077 self.update(
7078 {
7079 "redGamma": u16Fixed16Number(data[0:4]),
7080 "redMin": u16Fixed16Number(data[4:8]),
7081 "redMax": u16Fixed16Number(data[8:12]),
7082 "greenGamma": u16Fixed16Number(data[12:16]),
7083 "greenMin": u16Fixed16Number(data[16:20]),
7084 "greenMax": u16Fixed16Number(data[20:24]),
7085 "blueGamma": u16Fixed16Number(data[24:28]),
7086 "blueMin": u16Fixed16Number(data[28:32]),
7087 "blueMax": u16Fixed16Number(data[32:36]),
7088 }
7089 )
7090
7091 def getNormalizedValues(self, amount: None | int = None) -> list: # noqa: N802
7092 """Return normalized values of the video LUT curves.
7093
7094 Args:
7095 amount (None | int, optional): The number of values to return. If
7096 None, it defaults to 256.
7097
7098 Returns:
7099 list: A list of tuples, each containing normalized values for the
7100 red, green, and blue channels.
7101 """
7102 if amount is None:
7103 amount = 256 # common value
7104 step = 1.0 / float(amount - 1)
7105 rgb = AODict([("red", []), ("green", []), ("blue", [])])
7106 for i in range(amount):
7107 for key in rgb:
7108 rgb[key].append(
7109 float(self[key + "Min"])
7110 + math.pow(step * i / 1.0, float(self[key + "Gamma"]))
7111 * float(self[key + "Max"] - self[key + "Min"])
7112 )
7113 return list(zip(*list(rgb.values())))
7114
7115 def getTableType( # noqa: N802
7116 self,
7117 entryCount: int = 256, # noqa: N803
7118 entrySize: int = 2, # noqa: N803
7119 quantizer: Callable = round, # noqa: N803
7120 ) -> VideoCardGammaTableType:
7121 """Return gamma as table type.
7122
7123 Args:
7124 entryCount (int, optional): The number of entries in the table.
7125 Defaults to 256.
7126 entrySize (int, optional): The size of each entry in bytes.
7127 Defaults to 2.
7128 quantizer (Callable, optional): A function to quantize the values.
7129 Defaults to `round`.
7130
7131 Returns:
7132 VideoCardGammaTableType: A new instance of VideoCardGammaTableType
7133 containing the gamma table data.
7134 """
7135 max_value = math.pow(256, entrySize) - 1
7136 tag_data = [
7137 self.tagData[:8],
7138 uInt32Number_tohex(0), # type 0 = table
7139 uInt16Number_tohex(3), # channels
7140 uInt16Number_tohex(entryCount),
7141 uInt16Number_tohex(entrySize),
7142 ]
7143 int2hex = {
7144 1: uInt8Number_tohex,
7145 2: uInt16Number_tohex,
7146 4: uInt32Number_tohex,
7147 8: uInt64Number_tohex,
7148 }
7149 for key in ("red", "green", "blue"):
7150 for i in range(entryCount):
7151 vmin = float(self[key + "Min"])
7152 vmax = float(self[key + "Max"])
7153 gamma = float(self[key + "Gamma"])
7154 v = vmin + math.pow(1.0 / (entryCount - 1) * i, gamma) * float(
7155 vmax - vmin
7156 )
7157 tag_data.append(int2hex[entrySize](quantizer(v * max_value)))
7158 return VideoCardGammaTableType(b"".join(tag_data), self.tagSignature)
7159
7160
7161 class VideoCardGammaTableType(VideoCardGammaType):
7162 """Video card gamma table type class.
7163
7164 Args:
7165 tagData (bytes): The raw tag data containing the video LUT curves.
7166 tagSignature (str): The signature of the tag, typically "vcgt".
7167 """
7168
7169 def __init__(self, tagData: bytes, tagSignature: str) -> None: # noqa: N803
7170 VideoCardGammaType.__init__(self, tagData, tagSignature)
7171 if not tagData:
7172 self.update({"channels": 0, "entryCount": 0, "entrySize": 0, "data": []})
7173 return
7174 data = tagData[12:]
7175 channels = uInt16Number(data[0:2])
7176 entry_count = uInt16Number(data[2:4])
7177 entry_size = uInt16Number(data[4:6])
7178 self.update(
7179 {
7180 "channels": channels,
7181 "entryCount": entry_count,
7182 "entrySize": entry_size,
7183 "data": [],
7184 }
7185 )
7186 hex2int = {1: uInt8Number, 2: uInt16Number, 4: uInt32Number, 8: uInt64Number}
7187 if entry_size not in hex2int:
7188 raise ValueError(
7189 f"Invalid VideoCardGammaTableType entry size {int(entry_size):d}"
7190 )
7191 i = 0
7192 while i < channels:
7193 self.data.append([])
7194 j = 0
7195 while j < entry_count:
7196 index = 6 + i * entry_count * entry_size + j * entry_size
7197 self.data[i].append(
7198 hex2int[entry_size](data[index : index + entry_size])
7199 )
7200 j = j + 1
7201 i = i + 1
7202
7203 def getNormalizedValues(self, amount: None | int = None) -> list: # noqa: N802
7204 """Return normalized values of the video LUT curves.
7205
7206 Args:
7207 amount (None | int, optional): The number of values to return. If
7208 None, it defaults to the entryCount of the video LUT curves.
7209
7210 Returns:
7211 list: A list of tuples, each containing normalized values for the
7212 red, green, and blue channels.
7213 """
7214 if amount is None:
7215 amount = self.entryCount
7216 max_value = math.pow(256, self.entrySize) - 1
7217 values = list(
7218 zip(*[[entry / max_value for entry in channel] for channel in self.data])
7219 )
7220 if amount <= self.entryCount:
7221 step = self.entryCount / float(amount - 1)
7222 all_values = values
7223 values = []
7224 for i, value in enumerate(all_values):
7225 if i == 0 or (i + 1) % step < 1 or i + 1 == self.entryCount:
7226 values.append(value)
7227 return values
7228
7229 def getFormulaType(self) -> VideoCardGammaFormulaType: # noqa: N802
7230 """Return formula representing gamma value at 50% input.
7231
7232 Returns:
7233 VideoCardGammaFormulaType: A new instance of
7234 VideoCardGammaFormulaType with the calculated gamma values and
7235 min/max values for each channel.
7236 """
7237 max_value = math.pow(256, self.entrySize) - 1
7238 tag_data = [self.tagData[:8], uInt32Number_tohex(1)] # type 1 = formula
7239 data = list(self.data)
7240 while len(data) < 3:
7241 data.append(data[0])
7242 for channel in data:
7243 channel_length = (len(channel) - 1) / 2.0
7244 floor = float(channel[math.floor(channel_length)])
7245 ceil = float(channel[math.ceil(channel_length)])
7246 vmin = channel[0] / max_value
7247 vmax = channel[-1] / max_value
7248 v = (vmin + ((floor + ceil) / 2.0) * (vmax - vmin)) / max_value
7249 gamma = math.log(v) / math.log(0.5)
7250 print(vmin, gamma, vmax)
7251 tag_data.append(u16Fixed16Number_tohex(gamma))
7252 tag_data.append(u16Fixed16Number_tohex(vmin))
7253 tag_data.append(u16Fixed16Number_tohex(vmax))
7254 return VideoCardGammaFormulaType(b"".join(tag_data), self.tagSignature)
7255
7256 def quantize(self, bits: int = 16, quantizer: Callable = round) -> None:
7257 """Quantize to n bits of precision.
7258
7259 Note that when the quantize bits are not 8, 16, 32 or 64, double
7260 quantization will occur: First from the table precision bits according
7261 to entrySize to the chosen quantization bits, and then back to the
7262 table precision bits.
7263
7264 Args:
7265 bits (int, optional): The number of bits to quantize to. Must be
7266 one of 8, 16, 32, or 64. Defaults to 16.
7267 quantizer (callable, optional): A function to quantize the values.
7268 Defaults to the built-in `round` function.
7269 """
7270 oldmax = math.pow(256, self.entrySize) - 1
7271 if bits in (8, 16, 32, 64):
7272 self.entrySize = int(bits / 8)
7273 bitv = 2.0**bits
7274 newmax = math.pow(256, self.entrySize) - 1
7275 for _i, channel in enumerate(self.data):
7276 for j, value in enumerate(channel):
7277 channel[j] = int(quantizer(value / oldmax * bitv) / bitv * newmax)
7278
7279 def resize(self, length: int = 128) -> None:
7280 """Resize video LUT curves to a given length.
7281
7282 Args:
7283 length (int): The desired length of the resized LUT curves.
7284 """
7285 data = [[], [], []]
7286 for i, channel in enumerate(self.data):
7287 for j in range(length):
7288 j *= (len(channel) - 1) / float(length - 1)
7289 if int(j) != j:
7290 floor = channel[math.floor(j)]
7291 ceil = channel[min(math.ceil(j), len(channel) - 1)]
7292 interpolated = range(floor, ceil + 1)
7293 fraction = j - int(j)
7294 index = round(fraction * (ceil - floor))
7295 v = interpolated[index]
7296 else:
7297 v = channel[int(j)]
7298 data[i].append(v)
7299 self.data = data
7300 self.entryCount = len(data[0])
7301
7302 def resized(self, length: int = 128) -> VideoCardGammaTableType:
7303 """Return a resized version of the video LUT curves.
7304
7305 Args:
7306 length (int): The desired length of the resized LUT curves.
7307
7308 Returns:
7309 VideoCardGammaTableType: A new instance of VideoCardGammaTableType
7310 with the resized LUT curves.
7311 """
7312 resized = self.__class__(self.tagData, self.tagSignature)
7313 resized.resize(length)
7314 return resized
7315
7316 def smooth_cr(self, length: int = 64) -> None:
7317 """Smooth video LUT curves (Catmull-Rom).
7318
7319 Args:
7320 length (int): The desired length of the smoothed LUT curves.
7321 Defaults to 64.
7322 """
7323 resized = self.resized(length)
7324 for i in range(len(self.data)):
7325 step = float(length - 1) / (len(self.data[i]) - 1)
7326 interpolation = CRInterpolation(resized.data[i])
7327 for j in range(len(self.data[i])):
7328 self.data[i][j] = interpolation(j * step)
7329
7330 def smooth_avg(self, passes: int = 1, window: None | list | tuple = None) -> None:
7331 """Smooth video LUT curves (moving average).
7332
7333 Args:
7334 passes (int): Number of passes to perform. Defaults to 1.
7335 window (None | list | tuple , optional): Tuple or list containing
7336 weighting factors. Its length determines the size of the window
7337 to use. Defaults to (1.0, 1.0, 1.0).
7338 """
7339 for i, channel in enumerate(self.data):
7340 self.data[i] = colormath.smooth_avg(channel, passes, window)
7341 self.entryCount = len(self.data[0])
7342
7343 @property
7344 def tagData(self) -> bytes: # noqa: N802
7345 """Return raw tag data.
7346
7347 Returns:
7348 bytes: The raw tag data formatted as bytes.
7349 """
7350 tag_data = [
7351 b"vcgt",
7352 b"\0" * 4,
7353 uInt32Number_tohex(0), # type 0 = table
7354 uInt16Number_tohex(len(self.data)), # channels
7355 uInt16Number_tohex(self.entryCount),
7356 uInt16Number_tohex(self.entrySize),
7357 ]
7358 int2hex = {
7359 1: uInt8Number_tohex,
7360 2: uInt16Number_tohex,
7361 4: uInt32Number_tohex,
7362 8: uInt64Number_tohex,
7363 }
7364 tag_data.extend(
7365 int2hex[self.entrySize](channel[i])
7366 for channel in self.data
7367 for i in range(self.entryCount)
7368 )
7369 return b"".join(tag_data)
7370
7371 @tagData.setter
7372 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
7373 """Set the tag data.
7374
7375 Does nothing in this case, as the tagData is generated
7376 from the internal data structure.
7377
7378 Args:
7379 tagData (bytes): The raw tag data to set.
7380 """
7381
7382
7383 class ViewingConditionsType(ICCProfileTag, ADict):
7384 """ICC viewing conditions tag type.
7385
7386 Args:
7387 tagData (bytes): The raw tag data.
7388 tagSignature (str): The signature of the tag.
7389 """
7390
7391 def __init__(self, tagData: bytes, tagSignature: str) -> None: # noqa: N803
7392 ICCProfileTag.__init__(self, tagData, tagSignature)
7393 self.update(
7394 {
7395 "illuminant": XYZNumber(tagData[8:20]),
7396 "surround": XYZNumber(tagData[20:32]),
7397 "illuminantType": Illuminant(tagData[32:36]),
7398 }
7399 )
7400
7401
7402 class TagData:
7403 """ICC tag data type.
7404
7405 Args:
7406 tagData (bytes): The raw tag data.
7407 offset (int): The offset in the tag data where this tag starts.
7408 size (int): The size of the tag data.
7409 """
7410
7411 def __init__(self, tagData: bytes, offset: int, size: int) -> None: # noqa: N803
7412 self.tagData = tagData
7413 self.offset = offset
7414 self.size = size
7415
7416 def __contains__(self, item: bytes) -> bool:
7417 """Check if the item is in the tag data.
7418
7419 Args:
7420 item (bytes): The item to check for.
7421
7422 Returns:
7423 bool: True if the item is in the tag data, False otherwise.
7424 """
7425 return item in bytes(self)
7426
7427 def __bytes__(self) -> bytes:
7428 """Return the bytes representation of the object.
7429
7430 Returns:
7431 bytes: Bytes representation of the object.
7432 """
7433 return self.tagData[self.offset : self.offset + self.size]
7434
7435
7436 class WcsProfilesTagType(ICCProfileTag, ADict):
7437 """ICC WCS profiles tag type.
7438
7439 Args:
7440 tagData (bytes): The raw tag data.
7441 tagSignature (str): The signature of the tag.
7442 profile (ICCProfile): The ICC profile to which this tag belongs.
7443 """
7444
7445 def __init__(self, tagData: bytes, tagSignature: str, profile: ICCProfile) -> None: # noqa: N803
7446 ICCProfileTag.__init__(self, tagData, tagSignature)
7447 self.profile = profile
7448 for i, modelname in enumerate(
7449 ["ColorDeviceModel", "ColorAppearanceModel", "GamutMapModel"]
7450 ):
7451 j = i * 8
7452 if len(tagData) < 16 + j:
7453 break
7454 offset = uInt32Number(tagData[8 + j : 12 + j])
7455 size = uInt32Number(tagData[12 + j : 16 + j])
7456 if offset and size:
7457 from io import StringIO
7458
7459 from defusedxml import ElementTree
7460
7461 it = ElementTree.iterparse(StringIO(tagData[offset : offset + size]))
7462 for _event, elem in it:
7463 elem.tag = elem.tag.split("}", 1)[-1] # Strip all namespaces
7464 self[modelname] = it.root
7465
7466 def get_vcgt(
7467 self,
7468 quantize: int | bool = False,
7469 quantizer: Callable = round,
7470 ) -> None | VideoCardGammaType:
7471 """Return calibration information (if present) as VideoCardGammaType.
7472
7473 If quantize is set, a table quantized to <quantize> bits is returned.
7474
7475 Note that when the quantize bits are not 8, 16, 32 or 64, multiple
7476 quantizations will occur: For quantization bits below 32, first to 32
7477 bits, then to the chosen quantization bits, then back to 32 bits (which
7478 will be the final table precision bits).
7479
7480 Args:
7481 quantize (bool | int, optional): If True, quantize to 16 bits
7482 (default). If an integer, quantize to that many bits.
7483 quantizer (Callable, optional): A quantization function, defaults to
7484 `round`.
7485
7486 Returns:
7487 None | VideoCardGammaType: Returns a VideoCardGammaType object if
7488 calibration information is present, otherwise None.
7489 """
7490 if quantize and not isinstance(quantize, int):
7491 raise ValueError(f"Invalid quantization bits: {quantize!r}")
7492
7493 if "ColorDeviceModel" not in self:
7494 return None
7495
7496 # Parse calibration information to VCGT
7497 cal = self.ColorDeviceModel.find("Calibration")
7498 if cal is None:
7499 return None
7500 agammaconf = cal.find("AdapterGammaConfiguration")
7501 if agammaconf is None:
7502 return None
7503 pcurves = agammaconf.find("ParameterizedCurves")
7504 if pcurves is None:
7505 return None
7506 vcgt_data = "vcgt"
7507 vcgt_data += b"\0" * 4
7508 vcgt_data += uInt32Number_tohex(1) # Type 1 = formula
7509 for color in ("Red", "Green", "Blue"):
7510 trc = pcurves.find(color + "TRC")
7511 if trc is None:
7512 trc = {}
7513 vcgt_data += u16Fixed16Number_tohex(float(trc.get("Gamma", 1)))
7514 vcgt_data += u16Fixed16Number_tohex(float(trc.get("Offset1", 0)))
7515 vcgt_data += u16Fixed16Number_tohex(float(trc.get("Gain", 1)))
7516 vcgt = VideoCardGammaFormulaType(vcgt_data, "vcgt")
7517 if quantize:
7518 if quantize in (8, 16, 32, 64):
7519 entry_size = quantize / 8
7520 elif quantize < 32:
7521 entry_size = 4
7522 else:
7523 entry_size = 8
7524 vcgt = vcgt.getTableType(entrySize=entry_size, quantizer=quantizer)
7525 if quantize not in (8, 16, 32, 64):
7526 vcgt.quantize(quantize, quantizer)
7527 return vcgt
7528
7529
7530 class XYZNumber(AODict):
7531 """XYZNumber class.
7532
7533 Byte Offset Content Encoded as...
7534 0..3 CIE X s15Fixed16Number
7535 4..7 CIE Y s15Fixed16Number
7536 8..11 CIE Z s15Fixed16Number
7537
7538 Args:
7539 binaryString (None | bytes, optional): Binary string containing XYZ values.
7540 """
7541
7542 def __init__(self, binaryString: None | bytes = None) -> None: # noqa: N803
7543 if binaryString is None:
7544 binaryString = b"\0" * 12 # noqa: N806
7545 AODict.__init__(self)
7546 self.X, self.Y, self.Z = [
7547 s15Fixed16Number(chunk)
7548 for chunk in (binaryString[:4], binaryString[4:8], binaryString[8:12])
7549 ]
7550
7551 def __repr__(self) -> str:
7552 """Return the string representation of the object.
7553
7554 Returns:
7555 str: String representation of the object.
7556 """
7557 XYZ = [] # noqa: N806
7558 for key in self:
7559 value = self[key]
7560 XYZ.append(f"({key!r}, {value})")
7561 return "{}.{}([{}])".format(
7562 self.__class__.__module__,
7563 self.__class__.__name__,
7564 ", ".join(XYZ),
7565 )
7566
7567 def adapt(
7568 self,
7569 whitepoint_source: None | float | str | list | tuple = None,
7570 whitepoint_destination: None | float | str | list | tuple = None,
7571 cat: str = "Bradford",
7572 ) -> XYZNumber:
7573 """Adapt XYZ values to a different white point.
7574
7575 Args:
7576 whitepoint_source (None | float | str | list | tuple): Source white
7577 point, defaults to None.
7578 whitepoint_destination (None | float | str | list | tuple): Destination
7579 white point, defaults to None.
7580 cat (str, optional): Chromatic adaptation transform to use.
7581 Defaults to "Bradford".
7582
7583 Returns:
7584 XYZNumber: A new instance of XYZNumber with adapted values.
7585 """
7586 XYZ = self.__class__() # noqa: N806
7587 XYZ.X, XYZ.Y, XYZ.Z = colormath.adapt(
7588 self.X, self.Y, self.Z, whitepoint_source, whitepoint_destination, cat
7589 )
7590 return XYZ
7591
7592 def round(self, digits: int = 4) -> XYZNumber:
7593 """Round XYZ values to a specified number of digits.
7594
7595 Args:
7596 digits (int, optional): Number of digits to round to. Defaults to 4.
7597
7598 Returns:
7599 XYZNumber: A new instance of XYZNumber with rounded values.
7600 """
7601 XYZ = self.__class__() # noqa: N806
7602 for key in self:
7603 XYZ[key] = round(self[key], digits)
7604 return XYZ
7605
7606 def tohex(self) -> bytes:
7607 """Return the hexadecimal representation of the XYZ values.
7608
7609 Returns:
7610 bytes: Hexadecimal string of the XYZ values.
7611 """
7612 data = [s15Fixed16Number_tohex(n) for n in list(self.values())]
7613 return b"".join(data)
7614
7615 @property
7616 def hex(self) -> str:
7617 """Return the hexadecimal representation of the XYZ values.
7618
7619 Returns:
7620 str: Hexadecimal string of the XYZ values.
7621 """
7622 return self.tohex()
7623
7624 @property
7625 def Lab(self) -> tuple[float, float, float]: # noqa: N802
7626 """Return Lab values relative to the profile.
7627
7628 Returns:
7629 tuple[float, float, float]: A tuple containing the Lab values.
7630 """
7631 return colormath.XYZ2Lab(*[v * 100 for v in list(self.values())])
7632
7633 @property
7634 def xyY(self) -> colormath.NumberTuple: # noqa: N802
7635 """Return xyY values relative to the profile.
7636
7637 Returns:
7638 colormath.NumberTuple: xyY values as a NumberTuple.
7639 """
7640 return colormath.NumberTuple(colormath.XYZ2xyY(self.X, self.Y, self.Z))
7641
7642
7643 class XYZType(ICCProfileTag, XYZNumber):
7644 """XYZType class.
7645
7646 This class represents the XYZ color space in ICC profiles.
7647 It inherits from ICCProfileTag and XYZNumber.
7648 """
7649
7650 def __init__(
7651 self,
7652 tagData: bytes = b"\0" * 20, # noqa: N803
7653 tagSignature: None | str = None, # noqa: N803
7654 profile: None | ICCProfile = None,
7655 ) -> None:
7656 ICCProfileTag.__init__(self, tagData, tagSignature)
7657 XYZNumber.__init__(self, tagData[8:20])
7658 self.profile = profile
7659
7660 __repr__ = XYZNumber.__repr__
7661
7662 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
7663 """Set attribute value.
7664
7665 Args:
7666 name (str): Name of the attribute to set.
7667 value (Any): Value to set the attribute to.
7668 """
7669 if name in ("_keys", "profile", "tagData", "tagSignature"):
7670 object.__setattr__(self, name, value)
7671 else:
7672 self[name] = value
7673
7674 def adapt(
7675 self,
7676 whitepoint_source: None | float | str | list | tuple = None,
7677 whitepoint_destination: None | float | str | list | tuple = None,
7678 cat: None | str = None,
7679 ) -> XYZType:
7680 """Adapt XYZ values to a different white point.
7681
7682 Args:
7683 whitepoint_source (None | float | str | list | tuple, optional):
7684 Source white point. Defaults to None.
7685 whitepoint_destination (None | float | str | list | tuple, optional):
7686 Destination white point. Defaults to None.
7687 cat (str, optional): Chromatic adaptation transform to use.
7688 Defaults to "Bradford".
7689
7690 Returns:
7691 XYZType: A new instance of XYZType with adapted values.
7692 """
7693 if cat is None:
7694 if self.profile and isinstance(
7695 self.profile.tags.get("arts"), ChromaticAdaptionTag
7696 ):
7697 cat = self.profile.tags.arts
7698 else:
7699 cat = "Bradford"
7700 XYZ = self.__class__(profile=self.profile) # noqa: N806
7701 XYZ.X, XYZ.Y, XYZ.Z = colormath.adapt(
7702 self.X, self.Y, self.Z, whitepoint_source, whitepoint_destination, cat
7703 )
7704 return XYZ
7705
7706 @property
7707 def ir(self) -> Self | XYZType:
7708 """Get illuminant-relative values."""
7709 pcs_illuminant = list(self.profile.illuminant.values())
7710 if b"chad" in self.profile.tags and self.profile.creator != b"appl":
7711 # Apple profiles have a bug where they contain a 'chad' tag,
7712 # but the media white is not under PCS illuminant
7713 if self is self.profile.tags.wtpt:
7714 XYZ = self.__class__(profile=self.profile) # noqa: N806
7715 XYZ.X, XYZ.Y, XYZ.Z = list(self.values())
7716 else:
7717 # Go from XYZ mediawhite-relative under PCS illuminant to XYZ
7718 # under PCS illuminant
7719 if isinstance(self.profile.tags.get("arts"), ChromaticAdaptionTag):
7720 cat = self.profile.tags.arts
7721 else:
7722 cat = "XYZ scaling"
7723 XYZ = self.adapt( # noqa: N806
7724 pcs_illuminant, list(self.profile.tags.wtpt.values()), cat=cat
7725 )
7726 # Go from XYZ under PCS illuminant to XYZ illuminant-relative
7727 XYZ.X, XYZ.Y, XYZ.Z = self.profile.tags.chad.inverted() * list(XYZ.values())
7728 return XYZ
7729 if self in (self.profile.tags.wtpt, self.profile.tags.get("bkpt")):
7730 # For profiles without 'chad' tag, the white/black point should
7731 # already be illuminant-relative
7732 return self
7733 if "chad" in self.profile.tags:
7734 XYZ = self.__class__(profile=self.profile) # noqa: N806
7735 # Go from XYZ under PCS illuminant to XYZ illuminant-relative
7736 XYZ.X, XYZ.Y, XYZ.Z = self.profile.tags.chad.inverted() * list(
7737 self.values()
7738 )
7739 return XYZ
7740 # Go from XYZ under PCS illuminant to XYZ illuminant-relative
7741 return self.adapt(pcs_illuminant, list(self.profile.tags.wtpt.values()))
7742
7743 @property
7744 def pcs(self) -> Self | XYZType:
7745 """Get PCS-relative values."""
7746 if self in (self.profile.tags.wtpt, self.profile.tags.get("bkpt")) and (
7747 "chad" not in self.profile.tags or self.profile.creator == b"appl"
7748 ):
7749 # Apple profiles have a bug where they contain a 'chad' tag,
7750 # but the media white is not under PCS illuminant
7751 if "chad" in self.profile.tags:
7752 XYZ = self.__class__(profile=self.profile) # noqa: N806
7753 XYZ.X, XYZ.Y, XYZ.Z = self.profile.tags.chad * list(self.values())
7754 return XYZ
7755 pcs_illuminant = list(self.profile.illuminant.values())
7756 return self.adapt(list(self.profile.tags.wtpt.values()), pcs_illuminant)
7757 # Values should already be under PCS illuminant
7758 return self
7759
7760 @property
7761 def tagData(self) -> bytes: # noqa: N802
7762 """Return raw tag data.
7763
7764 Returns:
7765 bytes: Raw tag data containing XYZ values.
7766 """
7767 tag_data = [b"XYZ ", b"\0" * 4]
7768 tag_data.append(self.tohex())
7769 return b"".join(tag_data)
7770
7771 @tagData.setter
7772 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
7773 """Set tag data.
7774
7775 Does nothing, as XYZType is immutable.
7776
7777 Args:
7778 tagData (bytes): Raw tag data to set.
7779 """
7780
7781 @property
7782 def xyY(self) -> colormath.NumberTuple: # noqa: N802
7783 """Get xyY values relative to the profile's reference white.
7784
7785 Returns:
7786 colormath.NumberTuple: xyY values relative to the profile's
7787 reference white.
7788 """
7789 if self is self.profile.tags.get("bkpt"):
7790 ref = self.profile.tags.bkpt
7791 else:
7792 ref = self.profile.tags.wtpt
7793 return colormath.NumberTuple(
7794 colormath.XYZ2xyY(self.X, self.Y, self.Z, (ref.X, ref.Y, ref.Z))
7795 )
7796
7797
7798 class ChromaticAdaptionTag(colormath.Matrix3x3, S15Fixed16ArrayType):
7799 """Chromatic Adaptation Matrix.
7800
7801 The Chromatic Adaptation Matrix is a 3x3 matrix that transforms
7802 color values from one illuminant to another. It is used in
7803 color management systems to ensure that colors appear consistent
7804 across different devices and lighting conditions.
7805
7806 The matrix is represented as a list of 3 rows, each containing
7807 3 values. The values are stored as s15Fixed16Number, which is a
7808 fixed-point representation with 15 bits for the integer part
7809 and 16 bits for the fractional part:
7810
7811 Offset Content Encoded as:
7812
7813 0..3 CIE X s15Fixed16Number
7814 4..7 CIE Y s15Fixed16Number
7815 8..11 CIE Z s15Fixed16Number
7816 ...
7817
7818 Args:
7819 tagData (None | bytes, optional): Binary data containing the chromatic
7820 adaptation matrix values. If None, an empty matrix is created.
7821 tagSignature (None | str, optional): Signature of the tag, typically
7822 "chad". If None, defaults to "chad".
7823 """
7824
7825 def __init__(
7826 self,
7827 tagData: None | bytes = None, # noqa: N803
7828 tagSignature: None | str = None, # noqa: N803
7829 ) -> None:
7830 ICCProfileTag.__init__(self, tagData, tagSignature)
7831 if tagData:
7832 data = tagData[8:]
7833 if data:
7834 matrix = []
7835 while data:
7836 if len(matrix) == 0 or len(matrix[-1]) == 3:
7837 matrix.append([])
7838 matrix[-1].append(s15Fixed16Number(data[0:4]))
7839 data = data[4:]
7840 self.update(matrix)
7841 else:
7842 self._reset()
7843
7844 @property
7845 def tagData(self) -> bytes: # noqa: N802
7846 """Return raw tag data.
7847
7848 Args:
7849 tagData (bytes): Raw tag data containing the chromatic adaptation
7850 matrix values.
7851
7852 Returns:
7853 bytes: Raw tag data containing the chromatic adaptation matrix
7854 values in the format expected by ICC profiles.
7855 """
7856 tag_data = [b"sf32", b"\0" * 4]
7857 tag_data.extend(
7858 s15Fixed16Number_tohex(column) for row in self for column in row
7859 )
7860 return b"".join(tag_data)
7861
7862 @tagData.setter
7863 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
7864 """Set tag data.
7865
7866 Does nothing, as ChromaticAdaptionTag is immutable.
7867
7868 Args:
7869 tagData (bytes): Raw tag data to set.
7870 """
7871
7872 def get_cat(self) -> None | str:
7873 """Compare to known CAT matrices and return matching name (if any)."""
7874
7875 def q(v: int) -> float:
7876 """Quantize value to 16-bit fixed-point representation.
7877
7878 Args:
7879 v (int): Value to quantize.
7880
7881 Returns:
7882 float: Quantized value as float.
7883 """
7884 return s15Fixed16Number(s15Fixed16Number_tohex(v))
7885
7886 for cat_name in colormath.CAT_MATRICES:
7887 cat_matrix = colormath.CAT_MATRICES[cat_name]
7888 if colormath.is_similar_matrix(self.applied(q), cat_matrix.applied(q), 4):
7889 return cat_name
7890
7891 return None
7892
7893
7894 class NamedColor2Value:
7895 """Named Color 2 Value.
7896
7897 Args:
7898 valueData (bytes, optional): Binary data containing the named color
7899 values.
7900 deviceCoordCount (int, optional): Number of device coordinates.
7901 pcs (str, optional): PCS name, either "XYZ" or "Lab".
7902 device (str, optional): Device name, either "RGB" or "Lab".
7903 """
7904
7905 def __init__(
7906 self,
7907 valueData: bytes = b"\0" * 38, # noqa: N803
7908 deviceCoordCount: int = 0, # noqa: N803
7909 pcs: str = "XYZ",
7910 device: str = "RGB",
7911 ) -> None:
7912 self._pcsname = pcs
7913 self._devicename = device
7914 end = valueData[0:32].find(b"\0")
7915 if end < 0:
7916 end = 32
7917 self.rootName = valueData[0:end]
7918 self.pcsvalues = [
7919 uInt16Number(valueData[32:34]),
7920 uInt16Number(valueData[34:36]),
7921 uInt16Number(valueData[36:38]),
7922 ]
7923
7924 self.pcs = AODict()
7925 for i, pcsvalue in enumerate(self.pcsvalues):
7926 if pcs == "Lab":
7927 if i == 0:
7928 # L* range 0..100 + (25500 / 65280.0)
7929 self.pcs[pcs[i]] = pcsvalue / 65536.0 * 256 / 255.0 * 100
7930 else:
7931 # a, b range -128..127 + (255/256.0)
7932 self.pcs[pcs[i]] = -128 + (pcsvalue / 65536.0 * 256)
7933 elif pcs == "XYZ":
7934 # X, Y, Z range 0..100 + (32767 / 32768.0)
7935 self.pcs[pcs[i]] = pcsvalue / 32768.0 * 100
7936
7937 device_coords = []
7938 if deviceCoordCount > 0:
7939 device_coords.extend(
7940 uInt16Number(valueData[i : i + 2])
7941 for i in range(38, 38 + deviceCoordCount * 2, 2)
7942 )
7943 self.devicevalues = device_coords
7944 if device == "Lab":
7945 # L* range 0..100 + (25500 / 65280.0)
7946 # a, b range range -128..127 + (255 / 256.0)
7947 self.device = tuple(
7948 (
7949 v / 65536.0 * 256 / 255.0 * 100
7950 if i == 0
7951 else -128 + (v / 65536.0 * 256)
7952 )
7953 for i, v in enumerate(device_coords)
7954 )
7955 elif device == "XYZ":
7956 # X, Y, Z range 0..100 + (32767 / 32768.0)
7957 self.device = tuple(v / 32768.0 * 100 for v in device_coords)
7958 else:
7959 # Device range 0..100
7960 self.device = tuple(v / 65535.0 * 100 for v in device_coords)
7961
7962 @property
7963 def name(self) -> str:
7964 """Return the name of the named color.
7965
7966 Returns:
7967 str: The name of the named color, decoded from bytes using
7968 'latin-1' encoding.
7969 """
7970 return str(Text(self.rootName.strip(b"\0")), "latin-1")
7971
7972 def __repr__(self) -> str:
7973 """Return the string representation of the object.
7974
7975 Returns:
7976 str: The string representation of the object.
7977 """
7978 pcs = []
7979 for key in self.pcs:
7980 value = self.pcs[key]
7981 pcs.append(f"{key}={value}")
7982 dev = [f"{value}" for value in self.device]
7983 return "{}({}, {{{}}}, [{}])".format(
7984 self.__class__.__name__,
7985 self.name,
7986 ", ".join(pcs),
7987 ", ".join(dev),
7988 )
7989
7990 @property
7991 def tagData(self) -> bytes: # noqa: N802
7992 """Return raw tag data.
7993
7994 Returns:
7995 bytes: Raw tag data containing the named color values.
7996 """
7997 value_data = []
7998 value_data.append(self.rootName.ljust(32, b"\0"))
7999 value_data.extend([uInt16Number_tohex(pcsval) for pcsval in self.pcsvalues])
8000 value_data.extend(
8001 [uInt16Number_tohex(deviceval) for deviceval in self.devicevalues]
8002 )
8003 return b"".join(value_data)
8004
8005 @tagData.setter
8006 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
8007 """Set tag data.
8008
8009 Does nothing, as NamedColor2Value is immutable.
8010
8011 Args:
8012 tagData (bytes): Raw tag data to set.
8013 """
8014
8015
8016 class NamedColor2ValueTuple(tuple):
8017 """Tuple subclass for NamedColor2Value.
8018
8019 This class is used to represent a tuple of NamedColor2Value objects.
8020 """
8021
8022 __slots__ = ()
8023 REPR_OUTPUT_SIZE = 10
8024
8025 def __repr__(self) -> str:
8026 """Return the string representation of the object.
8027
8028 Truncates the output if it exceeds the specified size.
8029
8030 Returns:
8031 str: The string representation of the object.
8032 """
8033 data = list(self[: self.REPR_OUTPUT_SIZE + 1])
8034 if len(data) > self.REPR_OUTPUT_SIZE:
8035 data[-1] = "...(remaining elements truncated)..."
8036 return repr(data)
8037
8038 @property
8039 def tagData(self) -> bytes: # noqa: N802
8040 """Return raw tag data.
8041
8042 Returns:
8043 bytes: Concatenated tag data from all NamedColor2Value objects in
8044 the tuple.
8045 """
8046 return b"".join([val.tagData for val in self])
8047
8048 @tagData.setter
8049 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
8050 pass
8051
8052
8053 class NamedColor2Type(ICCProfileTag, AODict):
8054 """Named Color 2 Type.
8055
8056 This tag contains a list of named colors, each with a set of device
8057 coordinates and a set of PCS coordinates. The device coordinates
8058 are used to identify the color on the device, while the PCS
8059 coordinates are used to identify the color in a device-independent
8060 color space. The tag also contains a prefix and suffix that are
8061 used to format the name of the color.
8062
8063 Byte offset content encoded as:
8064
8065 0..3 vendorData s4Fixed32Number
8066 4..7 colorCount uInt32Number
8067 8..11 deviceCoordCount uInt32Number
8068 12..15 reserved uInt32Number
8069 16..19 reserved uInt32Number
8070 20..51 prefix s32Fixed32Number
8071 52..83 suffix s32Fixed32Number
8072 84..n colorValues NamedColor2Value
8073
8074 Args:
8075 tagData (bytes): The raw tag data.
8076 tagSignature (None | str): The signature of the tag.
8077 pcs (None | str): The PCS name, either "XYZ" or "Lab".
8078 device (None | str): The device name, either "RGB" or "Lab".
8079 """
8080
8081 REPR_OUTPUT_SIZE = 10
8082
8083 def __init__(
8084 self,
8085 tagData: bytes = b"\0" * 84, # noqa: N803
8086 tagSignature: None | str = None, # noqa: N803
8087 pcs: None | str = None,
8088 device: None | str = None,
8089 ) -> None:
8090 ICCProfileTag.__init__(self, tagData, tagSignature)
8091 AODict.__init__(self)
8092
8093 colorCount = uInt32Number(tagData[12:16]) # noqa: N806
8094 deviceCoordCount = uInt32Number(tagData[16:20]) # noqa: N806
8095 stride = 38 + 2 * deviceCoordCount
8096
8097 self.vendorData = tagData[8:12]
8098 self.colorCount = colorCount
8099 self.deviceCoordCount = deviceCoordCount
8100 self._prefix = Text(tagData[20:52])
8101 self._suffix = Text(tagData[52:84])
8102 self._pcsname = pcs
8103 self._devicename = device
8104
8105 keys = []
8106 values = []
8107 if colorCount > 0:
8108 start = 84
8109 end = start + (stride * colorCount)
8110 for i in range(start, end, stride):
8111 nc2 = NamedColor2Value(
8112 tagData[i : i + stride], deviceCoordCount, pcs=pcs, device=device
8113 )
8114 keys.append(nc2.name)
8115 values.append(nc2)
8116 self.update(dict(list(zip(keys, values))))
8117
8118 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
8119 """Set an attribute of the object.
8120
8121 Args:
8122 name (str): The name of the attribute to set.
8123 value (Any): The value to set the attribute to.
8124 """
8125 object.__setattr__(self, name, value)
8126
8127 @property
8128 def prefix(self) -> str:
8129 """Return the prefix of the named color profile.
8130
8131 Returns:
8132 str: The prefix of the named color profile, decoded from bytes
8133 using 'latin-1' encoding.
8134 """
8135 return str(self._prefix.strip(b"\0"), "latin-1")
8136
8137 @property
8138 def suffix(self) -> str:
8139 """Return the suffix of the named color profile.
8140
8141 Returns:
8142 str: The suffix of the named color profile, decoded from bytes
8143 using 'latin-1' encoding.
8144 """
8145 return str(self._suffix.strip(b"\0"), "latin-1")
8146
8147 @property
8148 def colorValues(self) -> NamedColor2ValueTuple: # noqa: N802
8149 """Return a tuple of NamedColor2Value objects.
8150
8151 Returns:
8152 NamedColor2ValueTuple: A tuple containing all NamedColor2Value
8153 objects in the profile.
8154 """
8155 return NamedColor2ValueTuple(list(self.values()))
8156
8157 def add_color(
8158 self,
8159 root_name: str,
8160 *device_coordinates: list[float],
8161 **pcs_coordinates: dict[str, float],
8162 ) -> None:
8163 """Add a named color to the profile.
8164
8165 Args:
8166 root_name (str): The name of the color.
8167 device_coordinates (list): Device coordinates for the color.
8168 pcs_coordinates (dict): PCS coordinates for the color.
8169
8170 Raises:
8171 ICCProfileInvalidError: If the required PCS coordinates or device
8172 coordinates are not provided, or if the color name already
8173 exists.
8174 """
8175 if self._pcsname == "Lab":
8176 keys = ["L", "a", "b"]
8177 elif self._pcsname == "XYZ":
8178 keys = ["X", "Y", "Z"]
8179 else:
8180 keys = ["X", "Y", "Z"]
8181
8182 if not set(pcs_coordinates.keys()).issuperset(set(keys)):
8183 raise ICCProfileInvalidError(
8184 "Can't add namedColor2 without all 3 PCS coordinates: " # noqa: UP032
8185 "'{}'".format(set(keys) - set(pcs_coordinates.keys()))
8186 )
8187
8188 if len(device_coordinates) != self.deviceCoordCount:
8189 raise ICCProfileInvalidError(
8190 f"Can't add namedColor2 without all {self.deviceCoordCount} "
8191 f"device coordinates (called with {len(device_coordinates)})"
8192 )
8193
8194 nc2value = NamedColor2Value()
8195 nc2value._pcsname = self._pcsname
8196 nc2value._devicename = self._devicename
8197 nc2value.rootName = root_name
8198
8199 if root_name in list(self.keys()):
8200 raise ICCProfileInvalidError(
8201 f"Can't add namedColor2 with existant name: '{root_name}'"
8202 )
8203
8204 nc2value.devicevalues = []
8205 nc2value.device = tuple(device_coordinates)
8206 nc2value.pcs = AODict(copy(pcs_coordinates))
8207
8208 for idx, key in enumerate(keys):
8209 val = nc2value.pcs[key]
8210 if key == "L":
8211 nc2value.pcsvalues[idx] = val * 65536 / (256 / 255.0) / 100.0
8212 elif key in ("a", "b"):
8213 nc2value.pcsvalues[idx] = (val + 128) * 65536 / 256.0
8214 elif key in ("X", "Y", "Z"):
8215 nc2value.pcsvalues[idx] = val * 32768 / 100.0
8216
8217 for idx, val in enumerate(nc2value.device):
8218 if self._devicename == "Lab":
8219 if idx == 0:
8220 # L* range 0..100 + (25500 / 65280.0)
8221 nc2value.devicevalues[idx] = val * 65536 / (256 / 255.0) / 100.0
8222 else:
8223 # a, b range -128..127 + (255/256.0)
8224 nc2value.devicevalues[idx] = (val + 128) * 65536 / 256.0
8225 elif self._devicename == "XYZ":
8226 # X, Y. Z range 0..100 + (32767 / 32768.0)
8227 nc2value.devicevalues[idx] = val * 32768 / 100.0
8228 else:
8229 # Device range 0..100
8230 nc2value.devicevalues[idx] = val * 65535 / 100.0
8231
8232 self[nc2value.name] = nc2value
8233
8234 def __repr__(self) -> str:
8235 """Return the string representation of the object.
8236
8237 Truncates the output if it exceeds the specified size.
8238
8239 Returns:
8240 str: The string representation of the object.
8241 """
8242 data = list(self.items())[: self.REPR_OUTPUT_SIZE + 1]
8243 if len(data) > self.REPR_OUTPUT_SIZE:
8244 data[-1] = ("...", "(remaining elements truncated)")
8245 return repr(dict(data))
8246
8247 @property
8248 def tagData(self) -> bytes: # noqa: N802
8249 """Return raw tag data.
8250
8251 Returns:
8252 bytes: Raw tag data containing vendor data, color count,
8253 device coordinate count, prefix, suffix, and color values.
8254 """
8255 tagData = [ # noqa: N806
8256 b"ncl2",
8257 b"\0" * 4,
8258 self.vendorData,
8259 uInt32Number_tohex(len(list(self.items()))),
8260 uInt32Number_tohex(self.deviceCoordCount),
8261 self._prefix.ljust(32),
8262 self._suffix.ljust(32),
8263 self.colorValues.tagData,
8264 ]
8265 return b"".join(tagData)
8266
8267 @tagData.setter
8268 def tagData(self, tagData: bytes) -> None: # noqa: N802, N803
8269 pass
8270
8271
8272 TAG_SIGNATURE_TO_TAG = {"arts": ChromaticAdaptionTag, "chad": ChromaticAdaptionTag}
8273
8274 TYPE_SIGNATURE_TO_TYPE = {
8275 b"chrm": ChromaticityType,
8276 b"clrt": ColorantTableType,
8277 b"curv": CurveType,
8278 b"desc": TextDescriptionType, # ICC v2
8279 b"dict": DictType, # ICC v2 + v4
8280 b"dtim": DateTimeType,
8281 b"meas": MeasurementType,
8282 b"mluc": MultiLocalizedUnicodeType, # ICC v4
8283 b"mft2": LUT16Type,
8284 b"mmod": MakeAndModelType, # Apple private tag
8285 b"ncl2": NamedColor2Type,
8286 b"para": ParametricCurveType,
8287 b"pseq": ProfileSequenceDescType,
8288 b"sf32": S15Fixed16ArrayType,
8289 b"sig ": SignatureType,
8290 b"text": TextType,
8291 b"vcgt": videoCardGamma,
8292 b"view": ViewingConditionsType,
8293 b"MS10": WcsProfilesTagType,
8294 b"XYZ ": XYZType,
8295 }
8296
8297
8298 class ICCProfileInvalidError(IOError):
8299 """Exception raised when an invalid ICC profile is encountered."""
8300
8301
8302 _ICCPROFILE_CACHE = WeakValueDictionary()
8303
8304
8305 class ICCProfile:
8306 """Return a new ICCProfile object.
8307
8308 Optionally initialized with a string containing binary profile data or
8309 a filename, or a file-like object. Also, if the 'load' keyword argument
8310 is False (default True), only the header will be read initially and
8311 loading of the tags will be deferred to when they are accessed the
8312 first time.
8313
8314 Args:
8315 profile (None | str | pathlib.Path | bytes | BinaryIO | TextIO, optional):
8316 The ICC profile data to load. This can be a string or
8317 pathlib.Path representing a file path, a bytes object
8318 containing the profile data, or a file-like object.
8319 load (bool, optional): If True, the profile will be loaded
8320 immediately. If False, only the header will be read.
8321 use_cache (bool, optional): If True, the profile will be cached
8322 to avoid reloading it if it has already been loaded.
8323 """
8324
8325 _recent: ClassVar[list] = []
8326
8327 def __new__(
8328 cls,
8329 profile: None | bytes | str | pathlib.Path | BinaryIO | TextIO = None,
8330 load: bool = True,
8331 use_cache: bool = False,
8332 ) -> Self:
8333 """Create a new ICCProfile instance.
8334
8335 Args:
8336 profile (None, bytes, str, pathlib.Path, file-like object, optional):
8337 The ICC profile data to load. This can be a string or
8338 pathlib.Path representing a file path, a bytes object
8339 containing the profile data, or a file-like object.
8340 load (bool, optional): If True, the profile will be loaded
8341 immediately. If False, only the header will be read.
8342 use_cache (bool, optional): If True, the profile will be cached
8343 to avoid reloading it if it has already been loaded.
8344
8345 Raises:
8346 ICCProfileInvalidError: If the profile data is invalid or
8347 if the profile cannot be loaded.
8348
8349 Returns:
8350 ICCProfile: A new instance of the ICCProfile class.
8351 """
8352 key = None
8353 # the content of the profile should be passed as bytes in Python 3.
8354 if isinstance(profile, (str, pathlib.Path)):
8355 # Filename
8356 if not profile:
8357 raise ICCProfileInvalidError("Empty path given")
8358
8359 p = pathlib.Path(profile) if isinstance(profile, str) else profile
8360
8361 if not p.is_file() and not p.is_absolute():
8362 search_paths = list(set(ICCPROFILES_HOME + ICCPROFILES))
8363 found_profile = False
8364 while search_paths and not found_profile:
8365 search_path = pathlib.Path(search_paths.pop(0))
8366 if not search_path.is_dir(): # only look in to directories
8367 continue
8368 for entry in search_path.glob(profile):
8369 if not entry.is_file():
8370 continue
8371 profile = str(entry)
8372 # TODO: update this to stay a Path instance after
8373 # migration to pathlib is completed
8374 found_profile = True
8375 break
8376
8377 if use_cache:
8378 stat = os.stat(profile)
8379 key = (profile, stat.st_dev, stat.st_ino, stat.st_mtime, stat.st_size)
8380 else:
8381 key = ()
8382 elif isinstance(profile, bytes):
8383 # Binary string
8384 if use_cache:
8385 key = md5(profile).hexdigest() # noqa: S324
8386
8387 if use_cache:
8388 chk = _ICCPROFILE_CACHE.get(key)
8389 if chk:
8390 return chk
8391
8392 self = super().__new__(cls)
8393
8394 if use_cache and key:
8395 _ICCPROFILE_CACHE[key] = self
8396
8397 # Make sure most recent three are not garbage collected
8398 if len(ICCProfile._recent) == 3:
8399 ICCProfile._recent.pop(0)
8400 ICCProfile._recent.append(self)
8401
8402 self._key = key
8403 self.ID = b"\0" * 16
8404 self._data = b""
8405 self._file = None
8406 self._tagoffsets = [] # Original tag offsets
8407 self._tags = LazyLoadTagAODict(self)
8408 self.filename = None
8409 self.is_loaded = False
8410 self.size = 0
8411
8412 if isinstance(key, tuple):
8413 # Filename
8414 profile = open(profile, "rb") # noqa: SIM115
8415
8416 if profile is None:
8417 self.set_defaults()
8418 return self
8419
8420 if isinstance(profile, bytes):
8421 # Binary string
8422 data = profile
8423 self.is_loaded = True
8424 else:
8425 # File object
8426 self._file = profile
8427 self.filename = self._file.name
8428 self._file.seek(0)
8429 data = self._file.read(128)
8430 self.close()
8431
8432 if not data or len(data) < 128:
8433 raise ICCProfileInvalidError("Not enough data")
8434
8435 if data[:5] == b"<?xml" or data[:10] == b"<\0?\0x\0m\0l\0":
8436 # Microsoft WCS profile
8437 from io import BytesIO
8438
8439 from defusedxml import ElementTree
8440
8441 self.filename = None
8442 self._data = data
8443 self.load()
8444 data = self._data
8445 self._data = b""
8446 self.set_defaults()
8447 it = ElementTree.iterparse(BytesIO(data))
8448 try:
8449 for _event, elem in it:
8450 # Strip all namespaces
8451 elem.tag = elem.tag.split("}", 1)[-1]
8452 except ElementTree.ParseError as e:
8453 raise ICCProfileInvalidError("Invalid WCS profile") from e
8454 desc = it.root.find(b"Description")
8455 if desc is not None:
8456 desc = desc.find(b"Text")
8457 if desc is not None:
8458 self.setDescription(str(desc.text, "UTF-8"))
8459 author = it.root.find(b"Author")
8460 if author is not None:
8461 author = author.find(b"Text")
8462 if author is not None:
8463 self.setCopyright(str(author.text, "UTF-8"))
8464 device = it.root.find(b"RGBVirtualDevice")
8465 if device is not None:
8466 measurement_data = device.find(b"MeasurementData")
8467 if measurement_data is not None:
8468 for color in (b"White", b"Red", b"Green", b"Blue", b"Black"):
8469 prim = measurement_data.find(color + b"Primary")
8470 if prim is None:
8471 continue
8472 XYZ = [] # noqa: N806
8473 for component in b"XYZ":
8474 try:
8475 XYZ.append(float(prim.get(component)) / 100.0)
8476 except (TypeError, ValueError) as e:
8477 raise ICCProfileInvalidError(
8478 "Invalid WCS profile"
8479 ) from e
8480 if color == b"White":
8481 tag_name = "wtpt"
8482 elif color == b"Black":
8483 tag_name = "bkpt"
8484 else:
8485 XYZ = colormath.adapt( # noqa: N806
8486 *XYZ,
8487 whitepoint_source=list(self.tags.wtpt.values()),
8488 )
8489 tag_name = color[0].lower().decode() + "XYZ"
8490 tag = self.tags[tag_name] = XYZType(profile=self)
8491 tag.X, tag.Y, tag.Z = XYZ
8492 gamma = measurement_data.find(b"GammaOffsetGainLinearGain")
8493 if gamma is None:
8494 gamma = measurement_data.find(b"GammaOffsetGain")
8495 if gamma is not None:
8496 params = {
8497 "Gamma": 1,
8498 "Offset": 0,
8499 "Gain": 1,
8500 "LinearGain": 1,
8501 "TransitionPoint": -1,
8502 }
8503 for att in list(params.keys()):
8504 try:
8505 params[att] = float(gamma.get(att))
8506 except (TypeError, ValueError) as e:
8507 if (
8508 att not in ("LinearGain", "TransitionPoint")
8509 or gamma.tag != "GammaOffsetGain"
8510 ):
8511 raise ICCProfileInvalidError(
8512 "Invalid WCS profile"
8513 ) from e
8514
8515 def power(a: float) -> float:
8516 """Calculate power value based on gamma and parameters.
8517
8518 Args:
8519 a (float): The input value to calculate the power for.
8520 """
8521 if a <= params["TransitionPoint"]:
8522 v = a / params["LinearGain"]
8523 else:
8524 v = math.pow(
8525 (a + params["Offset"]) * params["Gain"],
8526 params["Gamma"],
8527 )
8528 return v
8529
8530 else:
8531 gamma = measurement_data.find("Gamma")
8532 if gamma is not None:
8533 try:
8534 power = float(gamma.get("value"))
8535 except (TypeError, ValueError) as e:
8536 raise ICCProfileInvalidError(
8537 "Invalid WCS profile"
8538 ) from e
8539 if gamma is not None:
8540 self.set_trc_tags(True, power)
8541 if it.root.tag == "ColorDeviceModel":
8542 ms00 = WcsProfilesTagType(b"", "MS00", self)
8543 ms00["ColorDeviceModel"] = it.root
8544 vcgt = ms00.get_vcgt()
8545 if vcgt:
8546 self.tags["vcgt"] = vcgt
8547 self.size = len(self.data)
8548 return self
8549
8550 if data[36:40] != b"acsp":
8551 raise ICCProfileInvalidError(
8552 "Profile signature mismatch - expected 'acsp', found '"
8553 + data[36:40].decode("utf-8")
8554 + "'"
8555 )
8556
8557 # ICC profile
8558 header = data[:128]
8559 self.size = uInt32Number(header[0:4])
8560 self.preferredCMM = header[4:8]
8561 minorrev_bugfixrev = binascii.hexlify(header[8:12][1:2])
8562 self.version = float(
8563 "{}.{}".format(
8564 header[8:12][0],
8565 str(int(b"0x0" + minorrev_bugfixrev[0:1], 16))
8566 + str(int(b"0x0" + minorrev_bugfixrev[1:2], 16)),
8567 )
8568 )
8569 self.profileClass = header[12:16]
8570 self.colorSpace = header[16:20].strip()
8571 self.connectionColorSpace = header[20:24].strip()
8572 try:
8573 self.dateTime = dateTimeNumber(header[24:36])
8574 except ValueError as e:
8575 raise ICCProfileInvalidError("Profile creation date/time invalid") from e
8576 self.platform = header[40:44]
8577 flags = uInt32Number(header[44:48])
8578 self.embedded = flags & 1 != 0
8579 self.independent = flags & 2 == 0
8580 deviceAttributes = uInt32Number(header[56:60]) # noqa: N806
8581
8582 self.device = {
8583 "manufacturer": header[48:52],
8584 "model": header[52:56],
8585 "attributes": {
8586 "reflective": deviceAttributes & 1 == 0,
8587 "glossy": deviceAttributes & 2 == 0,
8588 "positive": deviceAttributes & 4 == 0,
8589 "color": deviceAttributes & 8 == 0,
8590 },
8591 }
8592 self.intent = uInt32Number(header[64:68])
8593 self.illuminant = XYZNumber(header[68:80])
8594 self.creator = header[80:84]
8595 if header[84:100] != b"\0" * 16:
8596 self.ID = header[84:100]
8597
8598 self._data = data[: self.size]
8599
8600 if load:
8601 _ = self.tags
8602
8603 return self
8604
8605 def set_defaults(self) -> None:
8606 """Set default values for the ICC profile."""
8607 if hasattr(self, "version"):
8608 return # Already initialized
8609 # Default to RGB display device profile
8610 self.preferredCMM = b"argl"
8611 self.version = 2.4
8612 self.profileClass = b"mntr"
8613 self.colorSpace = b"RGB"
8614 self.connectionColorSpace = b"XYZ"
8615 self.dateTime = datetime.datetime.now()
8616 if sys.platform == "win32":
8617 platform_id = b"MSFT" # Microsoft
8618 elif sys.platform == "darwin":
8619 platform_id = b"APPL" # Apple
8620 else:
8621 platform_id = b"*nix"
8622 self.platform = platform_id
8623 self.embedded = False
8624 self.independent = True
8625 self.device = {
8626 "manufacturer": b"",
8627 "model": b"",
8628 "attributes": {
8629 "reflective": True,
8630 "glossy": True,
8631 "positive": True,
8632 "color": True,
8633 },
8634 }
8635 self.intent = 0
8636 self.illuminant = XYZNumber(b"\0\0\xf6\xd6\0\x01\0\0\0\0\xd3-") # D50
8637 self.creator = b"DCAL" # DisplayCAL
8638
8639 def __len__(self) -> int:
8640 """Return the number of tags.
8641
8642 Can also be used in boolean comparisons (profiles with no tags
8643 evaluate to false).
8644
8645 Returns:
8646 int: The number of tags in the profile.
8647 """
8648 return len(self.tags)
8649
8650 @property
8651 def data(self) -> bytes:
8652 """Get raw binary profile data.
8653
8654 This will re-assemble the various profile parts (header, tag table and data)
8655 on-the-fly.
8656
8657 Returns:
8658 bytes: The raw binary profile data.
8659 """
8660 # Assemble tag table and tag data
8661 tagCount = len(self.tags) # noqa: N806
8662 tagTable = {} # noqa: N806
8663 tagTableSize = tagCount * 12 # noqa: N806
8664 tagsData = [] # noqa: N806
8665 tagsDataOffset = [] # noqa: N806
8666 tagDataOffset = 128 + 4 + tagTableSize # noqa: N806
8667 tags = []
8668 # Order of tag table and actual tag data may be different.
8669 # Keep order of tags according to original offsets (if any).
8670 for _oOffset, tagSignature in sorted(self._tagoffsets): # noqa: N806
8671 if tagSignature in self.tags:
8672 tags.append(tagSignature)
8673
8674 # Keep tag table order
8675 for tagSignature in self.tags: # noqa: N806
8676 tagTable[tagSignature] = tagSignature.encode()
8677 if tagSignature not in tags:
8678 tags.append(tagSignature)
8679
8680 for tagSignature in tags: # noqa: N806
8681 tag = AODict.__getitem__(self.tags, tagSignature)
8682 if isinstance(tag, ICCProfileTag):
8683 tagData = self.tags[tagSignature].tagData # noqa: N806
8684 else:
8685 tagData = tag[3] # noqa: N806
8686 tagDataSize = len(tagData) # noqa: N806
8687 # Pad all data with binary zeros, so it lies on 4-byte boundaries
8688 padding = math.ceil(tagDataSize / 4.0) * 4 - tagDataSize
8689 tagData += b"\0" * padding # noqa: N806
8690 if (
8691 tagDataOffset,
8692 tagSignature,
8693 ) not in self._tagoffsets and tagData in tagsData:
8694 tagTable[tagSignature] += uInt32Number_tohex(
8695 tagsDataOffset[tagsData.index(tagData)]
8696 )
8697 else:
8698 tagTable[tagSignature] += uInt32Number_tohex(tagDataOffset)
8699 tagsData.append(tagData)
8700 tagsDataOffset.append(tagDataOffset)
8701 tagDataOffset += tagDataSize + padding # noqa: N806
8702 tagTable[tagSignature] += uInt32Number_tohex(tagDataSize)
8703 tagsData = b"".join(tagsData) # noqa: N806
8704 header = self.header(tagTableSize, len(tagsData))
8705 return b"".join(
8706 [
8707 header,
8708 uInt32Number_tohex(tagCount),
8709 b"".join(list(tagTable.values())),
8710 tagsData,
8711 ]
8712 )
8713
8714 def header(self, tagTableSize: int, tagDataSize: int) -> bytes: # noqa: N803
8715 """Profile Header.
8716
8717 Args:
8718 tagTableSize (int): Size of the tag table in bytes.
8719 tagDataSize (int): Size of the tag data in bytes.
8720
8721 Returns:
8722 bytes: The profile header as a byte string.
8723 """
8724 # Profile size: 128 bytes header + 4 bytes tag count + tag table + data
8725 header = [
8726 uInt32Number_tohex(128 + 4 + tagTableSize + tagDataSize),
8727 self.preferredCMM[:4].ljust(4, b" ") if self.preferredCMM else b"\0" * 4,
8728 # Next three lines are ICC version
8729 chr(int(str(self.version).split(".")[0])).encode(),
8730 binascii.unhexlify((f"{self.version:.2f}").split(".")[1]),
8731 b"\0" * 2,
8732 self.profileClass[:4].ljust(4, b" "),
8733 self.colorSpace[:4].ljust(4, b" "),
8734 self.connectionColorSpace[:4].ljust(4, b" "),
8735 dateTimeNumber_tohex(self.dateTime),
8736 b"acsp",
8737 self.platform[:4].ljust(4, b" ") if self.platform else b"\0" * 4,
8738 ]
8739
8740 flags = 0
8741 if self.embedded:
8742 flags += 1
8743 if not self.independent:
8744 flags += 2
8745
8746 header.extend(
8747 [
8748 uInt32Number_tohex(flags),
8749 (
8750 self.device["manufacturer"][:4].rjust(4, b"\0")
8751 if self.device["manufacturer"]
8752 else b"\0" * 4
8753 ),
8754 (
8755 self.device["model"][:4].rjust(4, b"\0")
8756 if self.device["model"]
8757 else b"\0" * 4
8758 ),
8759 ]
8760 )
8761 deviceAttributes = 0 # noqa: N806
8762 for name, bit in {
8763 "reflective": 1,
8764 "glossy": 2,
8765 "positive": 4,
8766 "color": 8,
8767 }.items():
8768 if not self.device["attributes"][name]:
8769 deviceAttributes += bit # noqa: N806
8770 if sys.platform == "darwin" and self.version < 4:
8771 # Dont't include ID under Mac OS X unless v4 profile
8772 # to stop pedantic ColorSync utility from complaining
8773 # about header padding not being null
8774 id_ = b""
8775 else:
8776 id_ = self.ID[:16]
8777
8778 if isinstance(self._data, str):
8779 self._data = self._data.encode()
8780
8781 header.extend(
8782 [
8783 uInt32Number_tohex(deviceAttributes) + b"\0" * 4,
8784 uInt32Number_tohex(self.intent),
8785 self.illuminant.tohex(),
8786 self.creator[:4].ljust(4, b" ") if self.creator else b"\0" * 4,
8787 id_.ljust(16, b"\0"),
8788 self._data[100:128] if len(self._data[100:128]) == 28 else b"\0" * 28,
8789 ]
8790 )
8791
8792 return b"".join(header)
8793
8794 @property
8795 def tags(self) -> LazyLoadTagAODict:
8796 """Profile Tag Table.
8797
8798 Raises:
8799 ICCProfileInvalidError: If the tag table is truncated or
8800 if a tag signature is already encountered.
8801
8802 Returns:
8803 LazyLoadTagAODict: A dictionary-like object containing the
8804 profile's tags.
8805 """
8806 if self._tags:
8807 return self._tags
8808
8809 self.load()
8810 if not self._data or len(self._data) <= 131:
8811 return self._tags
8812
8813 # tag table and tagged element data
8814 tagCount = uInt32Number(self._data[128:132]) # noqa: N806
8815 if DEBUG:
8816 print("tagCount:", tagCount)
8817
8818 tagTable = self._data[132 : 132 + tagCount * 12] # noqa: N806
8819 self._tagoffsets = []
8820 discard_len = 0
8821 tags = {}
8822 while tagTable:
8823 tag = tagTable[:12]
8824 if len(tag) < 12:
8825 raise ICCProfileInvalidError("Tag table is truncated")
8826
8827 tagSignature = tag[:4].decode() # noqa: N806
8828 if DEBUG:
8829 print("tagSignature:", tagSignature)
8830
8831 tagDataOffset = uInt32Number(tag[4:8]) # noqa: N806
8832 self._tagoffsets.append((tagDataOffset, tagSignature))
8833 if DEBUG:
8834 print(" tagDataOffset:", tagDataOffset)
8835
8836 tagDataSize = uInt32Number(tag[8:12]) # noqa: N806
8837 if DEBUG:
8838 print(" tagDataSize:", tagDataSize)
8839
8840 if tagSignature in self._tags:
8841 print(
8842 f"Error (non-critical): Tag '{tagSignature}' "
8843 "already encountered. Skipping..."
8844 )
8845 else:
8846 if (tagDataOffset, tagDataSize) in tags:
8847 if DEBUG:
8848 print(" tagDataOffset and tagDataSize indicate shared tag")
8849 else:
8850 start = tagDataOffset - discard_len
8851 if DEBUG:
8852 print(" tagData start:", start)
8853
8854 end = tagDataOffset - discard_len + tagDataSize
8855 if DEBUG:
8856 print(" tagData end:", end)
8857
8858 tagData = self._data[start:end] # noqa: N806
8859 if len(tagData) < tagDataSize:
8860 print(
8861 f"Warning: Tag data for tag {tagSignature!r} "
8862 f"is truncated (offset {int(tagDataOffset):d}, "
8863 f"expected size {int(tagDataSize):d}, "
8864 f"actual size {len(tagData):d})"
8865 )
8866 tagDataSize = len(tagData) # noqa: N806
8867 typeSignature = tagData[:4] # noqa: N806
8868 if len(typeSignature) < 4:
8869 print(
8870 "Warning: Tag type signature for tag "
8871 f"{tagSignature!r} is truncated "
8872 f"(offset {int(tagDataOffset):d}, "
8873 f"size {int(tagDataSize):d})"
8874 )
8875 typeSignature = typeSignature.ljust(4, b" ") # noqa: N806
8876 if DEBUG:
8877 print(" typeSignature:", typeSignature)
8878 tags[(tagDataOffset, tagDataSize)] = (
8879 typeSignature,
8880 tagDataOffset,
8881 tagDataSize,
8882 tagData,
8883 )
8884 self._tags[tagSignature] = tags[(tagDataOffset, tagDataSize)]
8885 tagTable = tagTable[12:] # noqa: N806
8886
8887 self._data = self._data[:128]
8888 return self._tags
8889
8890 def calculate_id(self, set_id: bool = True) -> bytes:
8891 """Calculates, sets, and returns the profile's ID (checksum).
8892
8893 Calling this function always recalculates the checksum on-the-fly,
8894 in contrast to just accessing the ID property.
8895
8896 The entire profile, based on the size field in the header, is used
8897 to calculate the ID after the values in the Profile Flags field
8898 (bytes 44 to 47), Rendering Intent field (bytes 64 to 67) and
8899 Profile ID field (bytes 84 to 99) in the profile header have been
8900 temporarily replaced with zeros.
8901
8902 Args:
8903 set_id (bool, optional): If True, the calculated ID will be set as
8904 the profile's ID. If False, the ID will not be set, but still
8905 returned. Defaults to True.
8906
8907 Returns:
8908 bytes: The calculated ID as a 16-byte binary string.
8909 """
8910 data = self.data
8911 data = (
8912 data[:44]
8913 + b"\0\0\0\0"
8914 + data[48:64]
8915 + b"\0\0\0\0"
8916 + data[68:84]
8917 + b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
8918 + data[100:]
8919 )
8920 id_ = md5(data).digest() # noqa: S324
8921 if set_id:
8922 if id_ != self.ID:
8923 # No longer reflects original profile
8924 self._delfromcache()
8925 self.ID = id_
8926 return id_
8927
8928 def close(self) -> None:
8929 """Close the associated file object (if any)."""
8930 if self._file and not self._file.closed:
8931 self._file.close()
8932
8933 def convert_iccv4_tags_to_iccv2(
8934 self,
8935 version: float = 2.4,
8936 undo_wtpt_chad: bool = False,
8937 ) -> bool:
8938 """Convert ICCv4 parametric curve tags to ICCv2-compatible curve tags.
8939
8940 If desired version after conversion is < 2.4 and undo_wtpt_chad is True,
8941 also set whitepoint to illuinant relative values, and remove any
8942 chromatic adaptation tag.
8943
8944 If ICC profile version is < 4 or no [rgb]TRC tags or LUT16Type tags,
8945 return False.
8946 Otherwise, convert curve tags and return True.
8947
8948 Args:
8949 version (float, optional): The desired ICC profile version after
8950 conversion. Defaults to 2.4.
8951 undo_wtpt_chad (bool, optional): If True, set whitepoint to
8952 illuminant relative values and remove chromatic adaptation tag
8953 if present. Defaults to False.
8954
8955 Returns:
8956 bool: True if conversion was successful, False if the profile
8957 """
8958 if self.version < 4:
8959 return False
8960 # Fail if any LUT tag is not LUT16Type as we currently
8961 # have not implemented conversion (which may not even
8962 # be possible, depending on LUT contents)
8963 has_lut_tags = False
8964 for direction in ("A2B", "B2A"):
8965 for tableno in range(3):
8966 tag = self.tags.get(f"{direction}{tableno}")
8967 if tag:
8968 if isinstance(tag, LUT16Type):
8969 has_lut_tags = True
8970 else:
8971 return False
8972 if self.has_trc_tags():
8973 for channel in "rgb":
8974 tag = self.tags[channel + "TRC"]
8975 if isinstance(tag, ParametricCurveType):
8976 # Convert to CurveType
8977 self.tags[channel + "TRC"] = tag.get_trc()
8978 elif not has_lut_tags:
8979 return False
8980 # Set filename to None because our profile no longer reflects the file
8981 # on disk and remove from cache
8982 self.filename = None
8983 self._delfromcache()
8984 if version < 2.4 and undo_wtpt_chad:
8985 # Set whitepoint tag to illuminant relative and remove chromatic
8986 # adaptation tag afterwards(!)
8987 self.tags.wtpt = self.tags.wtpt.ir
8988 if "chad" in self.tags:
8989 del self.tags["chad"]
8990 # Get all multiLocalizedUnicodeType tags
8991 mluc = {}
8992 for tagname in self.tags:
8993 tag = self.tags[tagname]
8994 if isinstance(tag, MultiLocalizedUnicodeType):
8995 mluc[tagname] = str(tag)
8996 # Set profile version
8997 self.version = version
8998 # Convert to textDescriptionType/textType (after setting version to 2.x)
8999 for tagname in mluc:
9000 unistr = mluc[tagname]
9001 if tagname == "cprt":
9002 self.setCopyright(unistr)
9003 else:
9004 self.set_localizable_desc(tagname, unistr)
9005 return True
9006
9007 def convert_iccv2_tags_to_iccv4(self) -> bool:
9008 """Convert ICCv2 text description tags to ICCv4 multi-localized unicode.
9009
9010 Also sets whitepoint to D50, and stores illuminant-relative to D50
9011 matrix as chromatic adaptation tag.
9012
9013 If ICC profile version is >= 4, return False.
9014 Otherwise, convert and return True.
9015
9016 After conversion, the profile version is 4.3
9017
9018 Returns:
9019 bool: True if conversion was successful, False if the profile
9020 version is already >= 4.
9021 """
9022 if self.version >= 4:
9023 return False
9024 # Set filename to None because our profile no longer reflects the file
9025 # on disk and remove from cache
9026 self.filename = None
9027 self._delfromcache()
9028 wtpt = list(self.tags.wtpt.ir.values())
9029 # Set whitepoint tag to D50
9030 self.tags.wtpt = self.tags.wtpt.pcs
9031 if "chad" not in self.tags:
9032 # Set chromatic adaptation matrix
9033 self.tags["chad"] = ChromaticAdaptionTag()
9034 wpam = colormath.wp_adaption_matrix(
9035 wtpt, cat=self.tags.get("arts", "Bradford")
9036 )
9037 self.tags["chad"].update(wpam)
9038 # Get all textDescriptionType tags
9039 text = {}
9040 for tagname in self.tags:
9041 tag = self.tags[tagname]
9042 if tagname == "cprt" or isinstance(tag, TextDescriptionType):
9043 text[tagname] = str(tag)
9044 # Set profile version to 4.3
9045 self.version = 4.3
9046 # Convert to multiLocalizedUnicodeType (after setting version to 4.x)
9047 for tagname in text:
9048 unistr = text[tagname]
9049 self.set_localizable_text(tagname, unistr)
9050 return True
9051
9052 @staticmethod
9053 def from_named_rgb_space(
9054 rgb_space_name: str,
9055 iccv4: bool = False,
9056 cat: str = "Bradford",
9057 profile_class: bytes = b"mntr",
9058 ) -> ICCProfile:
9059 """Create an ICC Profile from a named RGB space and return it.
9060
9061 Args:
9062 rgb_space_name (str): The name of the RGB space, e.g. "sRGB",
9063 "AdobeRGB".
9064 iccv4 (bool): Whether to create an ICC v4 profile.
9065 cat (str): Chromatic adaptation transform to use.
9066 profile_class (bytes): The profile class, e.g. b'mntr' for monitor
9067 profiles.
9068
9069 Returns:
9070 ICCProfile: The created ICC profile.
9071 """
9072 rgb_space = colormath.get_rgb_space(rgb_space_name)
9073 return ICCProfile.from_rgb_space(
9074 rgb_space, rgb_space_name, iccv4, cat, profile_class
9075 )
9076
9077 @staticmethod
9078 def from_rgb_space(
9079 rgb_space: tuple[
9080 tuple[float, float, float],
9081 tuple[float, float, float],
9082 tuple[float, float, float],
9083 ],
9084 description: str,
9085 iccv4: bool = False,
9086 cat: str = "Bradford",
9087 profile_class: bytes = b"mntr",
9088 ) -> ICCProfile:
9089 """Create an ICC Profile from RGB space and return it.
9090
9091 Args:
9092 rgb_space (None | str | list | tuple): The RGB space to use for
9093 conversion. Defaults to sRGB if not set. If a string is given,
9094 it must be a valid RGB space name. If a list or tuple is given,
9095 it must be in the format (gamma, whitepoint, red, green, blue).
9096 The whitepoint can be a string (e.g. "D50"), a tuple of XYZ
9097 coordinates, or a color temperature in degrees K (float or
9098 int). The gamma should be a float. The RGB primaries red,
9099 green, blue should be lists or tuples of xyY coordinates (only
9100 x and y will be used, so Y can be zero or None).
9101 description (str): A description for the profile.
9102 iccv4 (bool): Whether to create an ICC v4 profile.
9103 cat (str): Chromatic adaptation transform to use.
9104 profile_class (bytes): The profile class, e.g. b'mntr' for monitor
9105 profiles.
9106
9107 Returns:
9108 ICCProfile: The created ICC profile.
9109 """
9110 rx, ry = rgb_space[2:][0][:2]
9111 gx, gy = rgb_space[2:][1][:2]
9112 bx, by = rgb_space[2:][2][:2]
9113 wx, wy = colormath.XYZ2xyY(*rgb_space[1])[:2]
9114 return ICCProfile.from_chromaticities(
9115 rx,
9116 ry,
9117 gx,
9118 gy,
9119 bx,
9120 by,
9121 wx,
9122 wy,
9123 rgb_space[0],
9124 description,
9125 "No copyright",
9126 iccv4=iccv4,
9127 cat=cat,
9128 profile_class=profile_class,
9129 )
9130
9131 @staticmethod
9132 def from_edid(
9133 edid: dict,
9134 iccv4: bool = False,
9135 cat: str = "Bradford",
9136 ) -> ICCProfile:
9137 """Create an ICC Profile from EDID data and return it.
9138
9139 You may override the gamma from EDID by setting it to a list of curve
9140 values.
9141
9142 Args:
9143 edid (dict): EDID data as a dictionary.
9144 iccv4 (bool, optional): Whether to create an ICC v4 profile.
9145 cat (str, optional): Chromatic adaptation transform to use.
9146
9147 Returns:
9148 ICCProfile: The created ICC profile.
9149 """
9150 description = edid.get(
9151 "monitor_name", edid.get("ascii", str(edid["product_id"] or edid["hash"]))
9152 )
9153 manufacturer = edid.get("manufacturer", b"")
9154 manufacturer_id = edid["edid"][8:10]
9155 model_name = description
9156 model_id = edid["edid"][10:12]
9157 copyright_str = "Created from EDID"
9158 # Get chromaticities of primaries0
9159 xy = {}
9160 for color in ("red", "green", "blue", "white"):
9161 x, y = edid.get(color + "_x", 0.0), edid.get(color + "_y", 0.0)
9162 xy[color[0] + "x"] = x
9163 xy[color[0] + "y"] = y
9164 gamma = edid.get("gamma", 2.2)
9165 profile = ICCProfile.from_chromaticities(
9166 xy["rx"],
9167 xy["ry"],
9168 xy["gx"],
9169 xy["gy"],
9170 xy["bx"],
9171 xy["by"],
9172 xy["wx"],
9173 xy["wy"],
9174 gamma,
9175 description,
9176 copyright_str,
9177 manufacturer,
9178 model_name,
9179 manufacturer_id,
9180 model_id,
9181 iccv4,
9182 cat,
9183 )
9184 profile.set_edid_metadata(edid)
9185 spec_prefixes = "DATA_,OPENICC_"
9186 prefix = profile.tags.meta.getvalue("prefix", b"", None)
9187 if isinstance(prefix, bytes):
9188 prefix = prefix.decode("utf-8")
9189 prefixes = (prefix or spec_prefixes).split(",")
9190 for prefix in spec_prefixes.split(","):
9191 if prefix not in prefixes:
9192 prefixes.append(prefix)
9193 profile.tags.meta["prefix"] = ",".join(prefixes)
9194 profile.tags.meta["OPENICC_automatic_generated"] = "1"
9195 profile.tags.meta["DATA_source"] = "edid"
9196 profile.calculate_id()
9197 return profile
9198
9199 @staticmethod
9200 def from_chromaticities(
9201 rx: float,
9202 ry: float,
9203 gx: float,
9204 gy: float,
9205 bx: float,
9206 by: float,
9207 wx: float,
9208 wy: float,
9209 gamma: float | list,
9210 description: str,
9211 copyright_: str,
9212 manufacturer: None | str = None,
9213 model_name: None | str = None,
9214 manufacturer_id: bytes = b"\0\0",
9215 model_id: bytes = b"\0\0",
9216 iccv4: bool = False,
9217 cat: str = "Bradford",
9218 profile_class: bytes = b"mntr",
9219 ) -> ICCProfile:
9220 r"""Create an ICC Profile from chromaticities and return it.
9221
9222 Args:
9223 rx (float): Red primary x chromaticity.
9224 ry (float): Red primary y chromaticity.
9225 gx (float): Green primary x chromaticity.
9226 gy (float): Green primary y chromaticity.
9227 bx (float): Blue primary x chromaticity.
9228 by (float): Blue primary y chromaticity.
9229 wx (float): White point x chromaticity.
9230 wy (float): White point y chromaticity.
9231 gamma (float | list): Gamma value or list of curve values.
9232 description (str): A description for the profile.
9233 copyright_ (str): Copyright information for the profile.
9234 manufacturer (None | str, optional): Manufacturer name. Defaults to
9235 None.
9236 model_name (None | str, optional): Model name. Defaults to None.
9237 manufacturer_id (bytes, optional): Manufacturer ID as a 4-byte
9238 string. Defaults to b"\0\0".
9239 model_id (bytes, optional): Model ID as a 4-byte string. Defaults
9240 to b"\0\0".
9241 iccv4 (bool, optional): Whether to create an ICC v4 profile.
9242 Defaults to False.
9243 cat (str, optional): Chromatic adaptation transform to use.
9244 Defaults to "Bradford".
9245 profile_class (bytes, optional): The profile class, e.g. b'mntr'
9246 for monitor profiles. Defaults to b'mntr'.
9247
9248 Returns:
9249 ICCProfile: The created ICC profile.
9250 """
9251 wXYZ = colormath.xyY2XYZ(wx, wy, 1.0) # noqa: N806
9252 # Calculate RGB to XYZ matrix from chromaticities and white
9253 mtx = colormath.rgb_to_xyz_matrix(rx, ry, gx, gy, bx, by, wXYZ)
9254 rgb = {"r": (1.0, 0.0, 0.0), "g": (0.0, 1.0, 0.0), "b": (0.0, 0.0, 1.0)}
9255 XYZ = {} # noqa: N806
9256 for color in "rgb":
9257 # Calculate XYZ for primaries
9258 XYZ[color] = mtx * rgb[color]
9259
9260 return ICCProfile.from_XYZ(
9261 XYZ["r"],
9262 XYZ["g"],
9263 XYZ["b"],
9264 wXYZ,
9265 gamma,
9266 description,
9267 copyright_,
9268 manufacturer,
9269 model_name,
9270 manufacturer_id,
9271 model_id,
9272 iccv4,
9273 cat,
9274 profile_class,
9275 )
9276
9277 @staticmethod
9278 def from_XYZ( # noqa: N802
9279 rXYZ: tuple[float, float, float], # noqa: N803
9280 gXYZ: tuple[float, float, float], # noqa: N803
9281 bXYZ: tuple[float, float, float], # noqa: N803
9282 wXYZ: tuple[float, float, float], # noqa: N803
9283 gamma: float | list,
9284 description: str,
9285 copyright_: str,
9286 manufacturer: None | str = None,
9287 model_name: None | str = None,
9288 manufacturer_id: bytes = b"\0\0",
9289 model_id: bytes = b"\0\0",
9290 iccv4: bool = False,
9291 cat: str = "Bradford",
9292 profile_class: bytes = b"mntr",
9293 ) -> ICCProfile:
9294 r"""Create an ICC Profile from XYZ values and return it.
9295
9296 Args:
9297 rXYZ (tuple[float, float, float]): Red primary in absolute XYZ.
9298 gXYZ (tuple[float, float, float]): Green primary in absolute XYZ.
9299 bXYZ (tuple[float, float, float]): Blue primary in absolute XYZ.
9300 wXYZ (tuple[float, float, float]): White point in absolute XYZ.
9301 gamma (float | list): Gamma value or list of curve values.
9302 description (str): A description for the profile.
9303 copyright_ (str): Copyright information for the profile.
9304 manufacturer (None | str, optional): Manufacturer name. Defaults to
9305 None.
9306 model_name (None | str, optional): Model name. Defaults to None.
9307 manufacturer_id (bytes, optional): Manufacturer ID as a 4-byte
9308 string. Defaults to b"\0\0".
9309 model_id (bytes, optional): Model ID as a 4-byte string. Defaults
9310 to b"\0\0".
9311 iccv4 (bool, optional): Whether to create an ICC v4 profile.
9312 Defaults to False.
9313 cat (str, optional): Chromatic adaptation transform to use.
9314 Defaults to "Bradford".
9315 profile_class (bytes, optional): The profile class, e.g. b'mntr'
9316 for monitor profiles. Defaults to b'mntr'.
9317
9318 Returns:
9319 ICCProfile: The created ICC profile.
9320 """
9321 profile = ICCProfile()
9322 profile.profileClass = profile_class
9323 D50 = colormath.get_whitepoint("D50") # noqa: N806
9324 if iccv4:
9325 profile.version = 4.3
9326 elif not s15f16_is_equal(wXYZ, D50) and (
9327 profile.profileClass not in (b"mntr", b"prtr")
9328 or colormath.is_similar_matrix(
9329 colormath.get_cat_matrix(cat), colormath.get_cat_matrix("Bradford")
9330 )
9331 ):
9332 profile.version = 2.2 # Match ArgyllCMS
9333 profile.setDescription(description)
9334 profile.setCopyright(copyright_)
9335 if manufacturer:
9336 profile.setDeviceManufacturerDescription(manufacturer)
9337 if model_name:
9338 profile.setDeviceModelDescription(model_name)
9339
9340 profile.device["manufacturer"] = (
9341 b"\0\0" + manufacturer_id[1:] + manufacturer_id[:1]
9342 )
9343 profile.device["model"] = b"\0\0" + model_id[1:] + model_id[:1]
9344 # Add Apple-specific 'mmod' tag (TODO: need full spec)
9345 if manufacturer_id != b"\0\0" or model_id != b"\0\0":
9346 mmod = (
9347 b"mmod"
9348 + (b"\x00" * 6)
9349 + manufacturer_id
9350 + (b"\x00" * 2)
9351 + model_id[1:]
9352 + model_id[:1]
9353 + (b"\x00" * 4)
9354 + (b"\x00" * 20)
9355 )
9356 profile.tags.mmod = ICCProfileTag(mmod, "mmod")
9357 profile.set_wtpt(wXYZ, cat)
9358 profile.tags.chrm = ChromaticityType()
9359 profile.tags.chrm.type = 0
9360
9361 for color_value, color_name in ((rXYZ, "r"), (gXYZ, "g"), (bXYZ, "b")):
9362 X, Y, Z = color_value # noqa: N806
9363 # Get chromaticity of primary
9364 x, y = colormath.XYZ2xyY(X, Y, Z)[:2]
9365 profile.tags.chrm.channels.append((x, y))
9366 # Write XYZ and TRC tags (don't forget to adapt to D50)
9367 tagname = f"{color_name}XYZ"
9368 profile.tags[tagname] = XYZType(profile=profile)
9369 (
9370 profile.tags[tagname].X,
9371 profile.tags[tagname].Y,
9372 profile.tags[tagname].Z,
9373 ) = colormath.adapt(X, Y, Z, wXYZ, D50, cat)
9374 tagname = f"{color_name}TRC"
9375 profile.tags[tagname] = CurveType(profile=profile)
9376 if isinstance(gamma, (list, tuple)):
9377 profile.tags[tagname].extend(gamma)
9378 else:
9379 profile.tags[tagname].set_trc(gamma, 1)
9380 profile.calculate_id()
9381 return profile
9382
9383 def set_wtpt(self, wXYZ: tuple[float, float, float], cat: str = "Bradford") -> None: # noqa: N803
9384 """Set whitepoint, 'chad' tag and add ArgyllCMS 'arts' tag.
9385
9386 if >= v2.4 profile or CAT is not Bradford and wtpt is not D50.
9387
9388 Args:
9389 wXYZ (tuple[float, float, float]): White point in absolute XYZ, Y
9390 range 0.0..1.0.
9391 cat (str, optional): Chromatic adaptation transform to use.
9392 Defaults to 'Bradford'.
9393 """
9394 self.tags.wtpt = XYZType(profile=self)
9395 # Compatibility: ArgyllCMS will only read 'chad' if display or
9396 # output profile
9397 if self.profileClass in (b"mntr", b"prtr") and (
9398 self.version >= 2.4
9399 or not colormath.is_similar_matrix(
9400 colormath.get_cat_matrix(cat), colormath.get_cat_matrix("Bradford")
9401 )
9402 ):
9403 # Set wtpt to D50 and store actual white -> D50 transform in chad
9404 # if creating ICCv4 profile or CAT is not default Bradford
9405 D50 = colormath.get_whitepoint("D50") # noqa: N806
9406 (self.tags.wtpt.X, self.tags.wtpt.Y, self.tags.wtpt.Z) = D50
9407 if not s15f16_is_equal(wXYZ, D50):
9408 # Only create chad if actual white is not D50
9409 self.tags.chad = ChromaticAdaptionTag()
9410 matrix = colormath.wp_adaption_matrix(wXYZ, D50, cat)
9411 self.tags.chad.update(matrix)
9412 else:
9413 # Store actual white in wtpt
9414 (self.tags.wtpt.X, self.tags.wtpt.Y, self.tags.wtpt.Z) = wXYZ
9415 self.tags.arts = ChromaticAdaptionTag()
9416 self.tags.arts.update(colormath.get_cat_matrix(cat))
9417
9418 def has_trc_tags(self) -> bool:
9419 """Return whether the profile has [rgb]TRC tags.
9420
9421 Returns:
9422 bool: True if the profile has [rgb]TRC tags, False otherwise.
9423 """
9424 return False not in [channel + "TRC" in self.tags for channel in "rgb"]
9425
9426 def set_blackpoint(self, XYZbp: tuple[float, float, float]) -> None: # noqa: N803
9427 """Set the black point tag to the given XYZ value.
9428
9429 Args:
9430 XYZbp (tuple[float, float, float]): Black point in absolute XYZ, Y
9431 range 0.0..1.0.
9432 """
9433 if "chad" not in self.tags:
9434 cat = self.guess_cat() or "Bradford"
9435 XYZbp = colormath.adapt( # noqa: N806
9436 *XYZbp, whitepoint_destination=list(self.tags.wtpt.ir.values()), cat=cat
9437 )
9438 self.tags.bkpt = XYZType(tagSignature="bkpt", profile=self)
9439 self.tags.bkpt.X, self.tags.bkpt.Y, self.tags.bkpt.Z = XYZbp
9440
9441 def apply_black_offset(
9442 self,
9443 XYZbp: tuple[float, float, float], # noqa: N803
9444 power: float = 40.0,
9445 include_A2B: bool = True, # noqa: N803
9446 set_blackpoint: bool = True,
9447 logfile: None | TextIO = None,
9448 thread_abort: None | threading.Event = None,
9449 abortmessage: str = "Aborted",
9450 include_trc: bool = True,
9451 ) -> None:
9452 """Apply black point blending to the profile.
9453
9454 Args:
9455 XYZbp (tuple[float, float, float]): Black point in absolute XYZ, Y
9456 range 0.0..1.0.
9457 power (float, optional): Power of black point blending. Defaults to
9458 40.0.
9459 include_A2B (bool, optional): Whether to apply black point blending
9460 to A2B tables. Defaults to True.
9461 set_blackpoint (bool, optional): Whether to set the black point
9462 tag. Defaults to True.
9463 logfile (None | TextIO, optional): File-like object to write the
9464 log messages to. Defaults to None.
9465 thread_abort (None | threading.Event, optional): Event to signal
9466 thread abort. Defaults to None.
9467 abortmessage (str, optional): Message to display when thread is
9468 aborted. Defaults to "Aborted".
9469 include_trc (bool, optional): Whether to apply black point blending
9470 to TRC tags. Defaults to True.
9471 """
9472 # Apply only the black point blending portion of BT.1886 mapping
9473 if include_A2B:
9474 tables = []
9475 for i in range(3):
9476 a2b = self.tags.get(f"A2B{i}")
9477 if isinstance(a2b, LUT16Type) and a2b not in tables:
9478 a2b.apply_black_offset(XYZbp, logfile, thread_abort, abortmessage)
9479 tables.append(a2b)
9480 if set_blackpoint:
9481 self.set_blackpoint(XYZbp)
9482 if not self.tags.get("rTRC") or not include_trc:
9483 return
9484 rXYZ = list(self.tags.rXYZ.values()) # noqa: N806
9485 gXYZ = list(self.tags.gXYZ.values()) # noqa: N806
9486 bXYZ = list(self.tags.bXYZ.values()) # noqa: N806
9487 mtx = colormath.Matrix3x3(
9488 [
9489 [rXYZ[0], gXYZ[0], bXYZ[0]],
9490 [rXYZ[1], gXYZ[1], bXYZ[1]],
9491 [rXYZ[2], gXYZ[2], bXYZ[2]],
9492 ]
9493 )
9494 imtx = mtx.inverted()
9495 for channel in "rgb":
9496 tag = CurveType(profile=self)
9497 if len(self.tags[f"{channel}TRC"]) == 1:
9498 gamma = self.tags[f"{channel}TRC"].get_gamma()
9499 tag.set_trc(gamma, 1024)
9500 else:
9501 tag.extend(self.tags[channel + "TRC"])
9502 self.tags[channel + "TRC"] = tag
9503 rgbbp_in = [self.tags[f"{channel}TRC"][0] / 65535.0 for channel in "rgb"]
9504 bp_in = mtx * rgbbp_in
9505 if tuple(bp_in) == tuple(XYZbp):
9506 return
9507 size = len(self.tags.rTRC)
9508 for i in range(size):
9509 rgb = [self.tags[f"{channel}TRC"][i] / 65535.0 for channel in "rgb"]
9510 X, Y, Z = mtx * rgb # noqa: N806
9511 XYZ = colormath.blend_blackpoint(X, Y, Z, bp_in, XYZbp, power=power) # noqa: N806
9512 rgb = imtx * XYZ
9513 for j, channel in enumerate("rgb"):
9514 self.tags[f"{channel}TRC"][i] = min(max(rgb[j], 0), 1) * 65535
9515
9516 def set_bt1886_trc(
9517 self,
9518 XYZbp: tuple[float, float, float], # noqa: N803
9519 outoffset: float = 0.0,
9520 gamma: float = 2.4,
9521 gamma_type: str = "B",
9522 size: None | int = None,
9523 ) -> None:
9524 """Set the response to the BT.1886 function.
9525
9526 Args:
9527 XYZbp (tuple): Black point in absolute XYZ, Y range 0.0..1.0.
9528 outoffset (float): Output offset (default 0.0).
9529 gamma (float): Effective gamma (default 2.4).
9530 gamma_type (str, optional): Type of gamma to use, either 'b' for
9531 BT.1886 or 'g' for gamma (default 'B').
9532 size (None | int): Number of steps. Recommended >= 1024.
9533 """
9534 if gamma_type in ("b", "g"):
9535 # Get technical gamma needed to achieve effective gamma
9536 gamma = colormath.xicc_tech_gamma(gamma, XYZbp[1], outoffset)
9537 rXYZ = list(self.tags.rXYZ.values()) # noqa: N806
9538 gXYZ = list(self.tags.gXYZ.values()) # noqa: N806
9539 bXYZ = list(self.tags.bXYZ.values()) # noqa: N806
9540 mtx = colormath.Matrix3x3(
9541 [
9542 [rXYZ[0], gXYZ[0], bXYZ[0]],
9543 [rXYZ[1], gXYZ[1], bXYZ[1]],
9544 [rXYZ[2], gXYZ[2], bXYZ[2]],
9545 ]
9546 )
9547 bt1886 = colormath.BT1886(mtx, XYZbp, outoffset, gamma)
9548 values = {}
9549 for _i, channel in enumerate(("r", "g", "b")):
9550 self.tags[channel + "TRC"] = CurveType(profile=self)
9551 self.tags[channel + "TRC"].set_trc(-709, size)
9552 for j, v in enumerate(self.tags[channel + "TRC"]):
9553 if not values.get(j):
9554 values[j] = []
9555 values[j].append(v / 65535.0)
9556 for i in values:
9557 r, g, b = values[i]
9558 X, Y, Z = mtx * (r, g, b) # noqa: N806
9559 values[i] = bt1886.apply(X, Y, Z)
9560 for i in values:
9561 XYZ = values[i] # noqa: N806
9562 rgb = mtx.inverted() * XYZ
9563 for j, channel in enumerate(("r", "g", "b")):
9564 self.tags[channel + "TRC"][i] = max(min(rgb[j] * 65535, 65535), 0)
9565 self.set_blackpoint(XYZbp)
9566
9567 def set_dicom_trc(
9568 self,
9569 XYZbp: tuple[float, float, float], # noqa: N803
9570 white_cdm2: float = 100,
9571 size: int = 1024,
9572 ) -> None:
9573 """Set the response to the DICOM Grayscale Standard Display Function.
9574
9575 This response is special in that it depends on the actual black
9576 and white level of the display.
9577
9578 XYZbp (tuple[float, float, float]: Black point in absolute XYZ, Y range
9579 0.05..white_cdm2.
9580 white_cdm2 (float, optional): White level in candelas per square
9581 meter, defaults to 100.
9582 size (int, optional): Number of steps. Recommended >= 1024.
9583 """
9584 self.set_trc_tags()
9585 for channel in "rgb":
9586 self.tags[f"{channel}TRC"].set_dicom_trc(XYZbp[1], white_cdm2, size)
9587 self.apply_black_offset(
9588 [v / white_cdm2 for v in XYZbp], 40.0 * (white_cdm2 / 40.0)
9589 )
9590
9591 def set_hlg_trc(
9592 self,
9593 XYZbp: tuple[float, float, float] = (0, 0, 0), # noqa: N803
9594 white_cdm2: float = 100,
9595 system_gamma: float = 1.2,
9596 ambient_cdm2: float = 5,
9597 maxsignal: float = 1.0,
9598 size: int = 1024,
9599 blend_blackpoint: bool = True,
9600 ) -> None:
9601 """Set the response to the Hybrid Log-Gamma (HLG) function.
9602
9603 This response is special in that it depends on the actual black and
9604 white level of the display, system gamma and ambient.
9605
9606 XYZbp (tuple[float, float, float], optional): Black point in absolute
9607 XYZ, Y range 0..white_cdm2.
9608 white_cdm2 (float, optional): White level in candelas per square
9609 meter, defaults to 100.
9610 system_gamma (float, optional): System gamma, defaults to 1.2.
9611 ambient_cdm2 (float, optional): Ambient light level in candelas per
9612 square meter, defaults to 5.
9613 maxsignal (float, optional): Set clipping point. Defaults to 1.0.
9614 size (int, optional): Number of steps. Recommended >= 1024.
9615 blend_blackpoint (bool, optional): If True, applies black point
9616 blending. Defaults to True.
9617 """
9618 self.set_trc_tags()
9619 for channel in "rgb":
9620 self.tags[f"{channel}TRC"].set_hlg_trc(
9621 XYZbp[1], white_cdm2, system_gamma, ambient_cdm2, maxsignal, size
9622 )
9623 if tuple(XYZbp) != (0, 0, 0) and blend_blackpoint:
9624 self.apply_black_offset(
9625 [v / white_cdm2 for v in XYZbp], 40.0 * (white_cdm2 / 100.0)
9626 )
9627
9628 def set_smpte2084_trc(
9629 self,
9630 XYZbp: tuple[float, float, float] = (0, 0, 0), # noqa: N803
9631 white_cdm2: float = 100,
9632 master_black_cdm2: float = 0,
9633 master_white_cdm2: float = 10000,
9634 use_alternate_master_white_clip: bool = True,
9635 rolloff: bool = False,
9636 size: int = 1024,
9637 blend_blackpoint: bool = True,
9638 ) -> None:
9639 """Set the response to the SMPTE 2084 perceptual quantizer (PQ) function.
9640
9641 This response is special in that it depends on the actual black
9642 and white level of the display.
9643
9644 Args:
9645 XYZbp (tuple[float, float, float]): Black point in absolute XYZ, Y
9646 range 0..white_cdm2
9647 white_cdm2 (float, optional): White level in candelas per square
9648 meter, defaults to 100.
9649 master_black_cdm2 (float, optional): Used to normalize PQ values.
9650 Defaults to 0.
9651 master_white_cdm2 (float, optional): Used to normalize PQ values.
9652 Defaults to 10000.
9653 use_alternate_master_white_clip (bool, optional): If True, uses the
9654 alternate master white clip. Defaults to True.
9655 rolloff (bool, optional): If True, applies the rolloff BT.2390.
9656 Defaults to False.
9657 size (int, optional): Number of steps. Recommended >= 1024.
9658 blend_blackpoint (bool, optional): If True, applies black point
9659 blending. Defaults to True.
9660 """
9661 self.set_trc_tags()
9662 for channel in "rgb":
9663 self.tags[f"{channel}TRC"].set_smpte2084_trc(
9664 XYZbp[1],
9665 white_cdm2,
9666 master_black_cdm2,
9667 master_white_cdm2,
9668 use_alternate_master_white_clip,
9669 rolloff,
9670 size,
9671 )
9672 if tuple(XYZbp) != (0, 0, 0) and blend_blackpoint:
9673 self.apply_black_offset(
9674 [v / white_cdm2 for v in XYZbp], 40.0 * (white_cdm2 / 100.0)
9675 )
9676
9677 def set_trc_tags(
9678 self, identical: bool = False, power: None | float | Callable = None
9679 ) -> None:
9680 """Set the [rgb]TRC tags.
9681
9682 Args:
9683 identical (bool, optional): If True, all channels will have the
9684 same TRC tag. Defaults to False.
9685 power (None | float | Callable, optional): If provided, sets the
9686 TRC to a power curve. Defaults to None, which means no power
9687 curve is set.
9688 """
9689 for channel in "rgb":
9690 if identical and channel != "r":
9691 tag = self.tags.rTRC
9692 else:
9693 tag = CurveType(profile=self)
9694 if power:
9695 tag.set_trc(
9696 power, size=1 if not callable(power) and power >= 0 else 1024
9697 )
9698 self.tags[f"{channel}TRC"] = tag
9699
9700 def set_localizable_desc(
9701 self,
9702 tagname: str,
9703 description: str,
9704 languagecode: str = "en",
9705 countrycode: str = "US",
9706 ) -> None:
9707 """Set a localizable description tag.
9708
9709 Args:
9710 tagname (str): The tag name to set.
9711 description (str): The description to set for the tag.
9712 languagecode (str, optional): The language code for the
9713 description. Defaults to "en".
9714 countrycode (str, optional): The country code for the description.
9715 Defaults to "US".
9716 """
9717 # Handle ICCv2 <> v4 differences and encoding
9718 if self.version < 4:
9719 self.tags[tagname] = TextDescriptionType()
9720 if isinstance(description, str):
9721 asciidesc = description.encode("ASCII", "asciize")
9722 else:
9723 asciidesc = description
9724 self.tags[tagname].ASCII = asciidesc
9725 if asciidesc != description:
9726 self.tags[tagname].Unicode = description
9727 else:
9728 self.set_localizable_text(tagname, description, languagecode, countrycode)
9729
9730 def set_localizable_text(
9731 self, tagname: str, text: str, languagecode: str = "en", countrycode: str = "US"
9732 ) -> None:
9733 """Set a localizable text tag.
9734
9735 Args:
9736 tagname (str): The tag name to set.
9737 text (str): The text to set for the tag.
9738 languagecode (str, otional): The language code for the text.
9739 Defaults to "en".
9740 countrycode (str, optioanl): The country code for the text.
9741 Defaults to "US".
9742 """
9743 # Handle ICCv2 <> v4 differences and encoding
9744 if self.version < 4:
9745 if isinstance(text, str):
9746 text = text.encode("ASCII", "asciize")
9747 self.tags[tagname] = TextType(b"text\0\0\0\0%s\0" % text, tagname)
9748 else:
9749 self.tags[tagname] = MultiLocalizedUnicodeType()
9750 self.tags[tagname].add_localized_string(languagecode, countrycode, text)
9751
9752 def setCopyright( # noqa: N802
9753 self, copyright_: str, languagecode: str = "en", countrycode: str = "US"
9754 ) -> None:
9755 """Set profile copyright.
9756
9757 Args:
9758 copyright_ (str): The profile copyright.
9759 languagecode (str, optional): The language code for the copyright.
9760 Defaults to "en".
9761 countrycode (str, optional): The country code for the copyright.
9762 Defaults to "US".
9763 """
9764 self.set_localizable_text("cprt", copyright_, languagecode, countrycode)
9765
9766 def setDescription( # noqa: N802
9767 self, description: str, languagecode: str = "en", countrycode: str = "US"
9768 ) -> None:
9769 """Set profile description.
9770
9771 Args:
9772 description (str): The profile description.
9773 languagecode (str): The language code for the description. Defaults
9774 to "en".
9775 countrycode (str): The country code for the description. Defaults
9776 to "US".
9777 """
9778 self.set_localizable_desc("desc", description, languagecode, countrycode)
9779
9780 def setDeviceManufacturerDescription( # noqa: N802
9781 self, description: str, languagecode: str = "en", countrycode: str = "US"
9782 ) -> None:
9783 """Set device manufacturer description.
9784
9785 Args:
9786 description (str): The device manufacturer description.
9787 languagecode (str, optional): The language code for the
9788 description. Defaults to "en".
9789 countrycode (str, optional): The country code for the description.
9790 Defafults to "US".
9791 """
9792 self.set_localizable_desc("dmnd", description, languagecode, countrycode)
9793
9794 def setDeviceModelDescription( # noqa: N802
9795 self, description: str, languagecode: str = "en", countrycode: str = "US"
9796 ) -> None:
9797 """Set device model description.
9798
9799 Args:
9800 description (str): The device model description.
9801 languagecode (str, optional): The language code for the
9802 description. Defaults to "en".
9803 countrycode (str, optional): The country code for the description.
9804 Defaults to "US".
9805 """
9806 self.set_localizable_desc("dmdd", description, languagecode, countrycode)
9807
9808 def getCopyright(self) -> str: # noqa: N802
9809 """Return profile copyright.
9810
9811 Returns:
9812 str: The profile copyright.
9813 """
9814 return str(self.tags.get("cprt", ""))
9815
9816 def getDescription(self) -> str: # noqa: N802
9817 """Return profile description.
9818
9819 Returns:
9820 str: The profile description.
9821 """
9822 return str(self.tags.get("desc", ""))
9823
9824 def getDeviceManufacturerDescription(self) -> str: # noqa: N802
9825 """Return device manufacturer description.
9826
9827 Returns:
9828 str: The device manufacturer description.
9829 """
9830 return str(self.tags.get("dmnd", ""))
9831
9832 def getDeviceModelDescription(self) -> str: # noqa: N802
9833 """Return device model description.
9834
9835 Returns:
9836 str: The device model description.
9837 """
9838 return str(self.tags.get("dmdd", ""))
9839
9840 def getViewingConditionsDescription(self) -> str: # noqa: N802
9841 """Return viewing conditions description.
9842
9843 Returns:
9844 str: The viewing conditions description.
9845 """
9846 return str(self.tags.get("vued", ""))
9847
9848 def guess_cat(self, matrix: bool = True) -> None | str | colormath.Matrix3x3:
9849 """Get or guess chromatic adaptation transform.
9850
9851 Args:
9852 matrix (bool): If 'matrix' is True, and 'arts' tag is present,
9853 return actual matrix instead of name if no match to known
9854 matrices.
9855
9856 Returns:
9857 None | str | colormath.Matrix3x3: The guessed chromatic adaptation
9858 transform, either as a string name or a Matrix3x3 object.
9859 Returns None if no CAT can be guessed.
9860 """
9861 illuminant = list(self.illuminant.values())
9862 if isinstance(self.tags.get("chad"), ChromaticAdaptionTag):
9863 return colormath.guess_cat(
9864 self.tags.chad, self.tags.chad.inverted() * illuminant, illuminant
9865 )
9866 if isinstance(self.tags.get("arts"), ChromaticAdaptionTag):
9867 return self.tags.arts.get_cat() or (matrix and self.tags.arts)
9868 return None
9869
9870 def is_same(
9871 self,
9872 profile: bytes | str | pathlib.Path | BinaryIO | TextIO,
9873 force_calculation: bool = False,
9874 ) -> bool:
9875 """Compare the ID of profiles.
9876
9877 Returns a boolean indicating if the profiles have the same ID.
9878
9879 profile can be a ICCProfile instance, a binary string
9880 containing profile data, a filename or a file object.
9881
9882 Args:
9883 profile (str | bytes | path.Path | BinaryIO | TextIO | ICCProfile ):
9884 The profile to compare with.
9885 force_calculation (bool, optional): If True, forces recalculation
9886 of the ID. Defautls to False.
9887
9888 Returns:
9889 bool: True if the profiles have the same ID, False otherwise.
9890 """
9891 if not isinstance(profile, self.__class__):
9892 profile = self.__class__(profile)
9893 if force_calculation or self.ID == b"\0" * 16:
9894 id1 = self.calculate_id(False)
9895 else:
9896 id1 = self.ID
9897 if force_calculation or profile.ID == b"\0" * 16:
9898 id2 = profile.calculate_id(False)
9899 else:
9900 id2 = profile.ID
9901 return id1 == id2
9902
9903 def load(self) -> None:
9904 """Load the profile from the file object.
9905
9906 Normally, you don't need to call this method, since the ICCProfile
9907 class automatically loads the profile when necessary (load does
9908 nothing if the profile was passed in as a binary string).
9909 """
9910 if self.is_loaded or not self._file:
9911 return
9912 if self._file.closed:
9913 self._file = open(self._file.name, "rb") # noqa: SIM115
9914 self._file.seek(len(self._data))
9915 read_size = self.size - len(self._data)
9916 if read_size > 0:
9917 self._data += self._file.read(read_size)
9918 self._file.close()
9919 self.is_loaded = True
9920
9921 def print_info(self) -> None:
9922 """Print profile information to stdout."""
9923 print("=" * 80)
9924 print("ICC profile information")
9925 print("-" * 80)
9926 print("File name:", os.path.basename(self.filename or ""))
9927 for label, value in self.get_info():
9928 if not value:
9929 print(label)
9930 else:
9931 print(label + ":", value)
9932
9933 @staticmethod
9934 def add_device_info(info: DictList, device: dict, level: int = 1) -> None:
9935 """Add a device structure (see profile header) to info dict.
9936
9937 Args:
9938 info (DictList): The dictionary to add the device information to.
9939 device (dict): The device structure from the profile header.
9940 level (int, optional): Indentation level for the device info.
9941 Defaults to 1.
9942 """
9943 indent = " " * 4 * level
9944 info[f"{indent}Manufacturer"] = "0x{}".format(
9945 binascii.hexlify(device.get("manufacturer", b"")).upper().decode()
9946 )
9947 if (
9948 len(device.get("manufacturer", b"")) == 4
9949 and device["manufacturer"][0:2] == b"\0\0"
9950 and device["manufacturer"][2:4] != b"\0\0"
9951 ):
9952 mnft_id = device["manufacturer"][3:4] + device["manufacturer"][2:3]
9953 mnft_id = edid.parse_manufacturer_id(mnft_id)
9954 manufacturer = edid.get_manufacturer_name(mnft_id) # this is str
9955 else:
9956 manufacturer = (
9957 re.sub(b"[^\x20-\x7e]", b"", device.get("manufacturer", b""))
9958 ).decode()
9959 if manufacturer != device.get("manufacturer"):
9960 manufacturer = None
9961 else:
9962 manufacturer = f"'{manufacturer.decode()}'"
9963 if manufacturer is not None:
9964 info[f"{indent}Manufacturer"] += f" {manufacturer}"
9965 info[f"{indent}Model"] = hexrepr(device.get("model", ""))
9966 attributes = device.get("attributes", {})
9967 info[f"{indent}Media attributes"] = ", ".join(
9968 [
9969 {True: "Reflective"}.get(attributes.get("reflective"), "Transparency"),
9970 {True: "Glossy"}.get(attributes.get("glossy"), "Matte"),
9971 {True: "Positive"}.get(attributes.get("positive"), "Negative"),
9972 {True: "Color"}.get(attributes.get("color"), "Black & white"),
9973 ]
9974 )
9975
9976 def get_info(self) -> list:
9977 """Return a list of profile information as tuples.
9978
9979 The tuples are of the form (label, value), where label is a string
9980 describing the information and value is the corresponding value.
9981 If the value is None or empty, the label is returned without a value.
9982 This method is useful for displaying profile information in a
9983 user-friendly way.
9984
9985 Returns:
9986 list: A list of tuples containing profile information.
9987 """
9988 info = DictList()
9989 info["Size"] = f"{int(self.size):d} Bytes ({self.size / 1024.0:.2f} KiB)"
9990 info["Preferred CMM"] = hexrepr(self.preferredCMM, CMMS)
9991 info["ICC version"] = f"{self.version}"
9992 info["Profile class"] = PROFILE_CLASS.get(self.profileClass, self.profileClass)
9993 info["Color model"] = self.colorSpace.decode()
9994 info["Profile connection space (PCS)"] = self.connectionColorSpace.decode()
9995 info["Created"] = "{:%Y-%m-%d %H:%M:%S}".format(self.dateTime) # noqa: UP032
9996 info["Platform"] = PLATFORM.get(self.platform, hexrepr(self.platform))
9997 info["Is embedded"] = {True: "Yes"}.get(self.embedded, "No")
9998 info["Can be used independently"] = {True: "Yes"}.get(self.independent, "No")
9999 info["Device"] = ""
10000 ICCProfile.add_device_info(info, self.device)
10001 info["Default rendering intent"] = {
10002 0: "Perceptual",
10003 1: "Media-relative colorimetric",
10004 2: "Saturation",
10005 3: "ICC-absolute colorimetric",
10006 }.get(self.intent, "Unknown")
10007 info["PCS illuminant XYZ"] = " ".join(
10008 [
10009 " ".join([f"{v * 100:6.2f}" for v in list(self.illuminant.values())]),
10010 "(xy {},".format(
10011 " ".join(f"{v:6.4f}" for v in self.illuminant.xyY[:2])
10012 ),
10013 "CCT {:d}K)".format( # noqa: UP032
10014 int(colormath.XYZ2CCT(*list(self.illuminant.values()))) or 0
10015 ),
10016 ]
10017 )
10018 info["Creator"] = hexrepr(self.creator, MANUFACTURERS)
10019 info["Checksum"] = f"0x{binascii.hexlify(self.ID).upper().decode()}"
10020 calculated_id = self.calculate_id(False)
10021 if self.ID != b"\0" * 16:
10022 info[" Checksum OK"] = {True: "Yes"}.get(calculated_id == self.ID, "No")
10023 if calculated_id != self.ID:
10024 info[" Calculated checksum"] = (
10025 f"0x{binascii.hexlify(calculated_id).upper().decode()}"
10026 )
10027 for sig in self.tags:
10028 tag = self.tags[sig]
10029 name = TAGS.get(sig, f"'{sig}'")
10030 if isinstance(tag, ChromaticAdaptionTag):
10031 info[name] = self.guess_cat(False) or "Unknown"
10032 name = " Matrix"
10033 for i, row in enumerate(tag):
10034 if i > 0:
10035 name = " " * 2
10036 info[name] = " ".join(f"{v:6.4f}" for v in row)
10037 elif isinstance(tag, ChromaticityType):
10038 info["Chromaticity (illuminant-relative)"] = ""
10039 for i, channel in enumerate(tag.channels):
10040 if self.colorSpace.endswith(b"CLR"):
10041 colorant_name = ""
10042 else:
10043 colorant_name = "({}) ".format(
10044 self.colorSpace[i : i + 1].decode("utf-8")
10045 )
10046 info[f" Channel {i + 1:d} {colorant_name}xy"] = " ".join(
10047 f"{v:6.4f}" for v in channel
10048 )
10049 elif isinstance(tag, ColorantTableType):
10050 info["Colorants (PCS-relative)"] = ""
10051 for colorant_name in tag:
10052 colorant = tag[colorant_name]
10053 values = list(colorant.values())
10054 if "".join(list(colorant.keys())) == "Lab":
10055 values = colormath.Lab2XYZ(*values)
10056 else:
10057 values = [v / 100.0 for v in values]
10058 XYZxy = [" ".join(f"{v:6.2f}" for v in list(colorant.values()))] # noqa: N806
10059 if values != [0, 0, 0]:
10060 XYZxy.append(
10061 "(xy {})".format(
10062 " ".join(
10063 f"{v:6.4f}" for v in colormath.XYZ2xyY(*values)[:2]
10064 )
10065 )
10066 )
10067 colorant_name = colorant_name.decode()
10068 info[
10069 " {} {}".format(
10070 colorant_name, "".join(list(colorant.keys()))
10071 )
10072 ] = " ".join(XYZxy)
10073 elif isinstance(tag, ParametricCurveType):
10074 params = "".join(sorted(tag.params.keys()))
10075 tag_params = dict(list(tag.params.items()))
10076 for key in tag_params:
10077 value = tag_params[key]
10078 value = f"{value:3.2f}" if key == "g" else f"{value:.6f}"
10079 value = value.rstrip("0").rstrip(".")
10080 if key == "g" and "." not in value:
10081 value += ".0"
10082 tag_params[key] = value
10083 tag_params["E"] = sig[0].upper()
10084 if params == "g":
10085 info[name] = f"Gamma {tag_params['g']}"
10086 else:
10087 info[name] = ""
10088 if params == "abg":
10089 info[" if ({E} >= - {b} / {a}):".format(**tag_params)] = (
10090 "Y = pow({a} * {E} + {b}, {g})".format(**tag_params)
10091 )
10092 info[" if ({E} < - {b} / {a}):".format(**tag_params)] = "Y = 0"
10093 elif params == "abcg":
10094 info[" if ({E} >= - {b} / {a}):".format(**tag_params)] = (
10095 "Y = pow({a} * {E} + {b}, {g}) + {c}".format(**tag_params)
10096 )
10097 info[" if ({E} < - {b} / {a}):".format(**tag_params)] = (
10098 f"Y = {tag_params['c']}"
10099 )
10100 elif params == "abcdg":
10101 info[" if ({E} >= {d}):".format(**tag_params)] = (
10102 "Y = pow({a} * {E} + {b}, {g})".format(**tag_params)
10103 )
10104 info[" if ({E} < {d}):".format(**tag_params)] = (
10105 "Y = {c} * {E}".format(**tag_params)
10106 )
10107 elif params == "abcdefg":
10108 info[" if ({E} >= {d}):".format(**tag_params)] = (
10109 "Y = pow({a} * {E} + {b}, {g}) + {e}".format(**tag_params)
10110 )
10111 info[" if ({E} < {d}):".format(**tag_params)] = (
10112 "Y = {c} * {E} + {f}".format(**tag_params)
10113 )
10114 if params != "g":
10115 tag = tag.get_trc()
10116 # info[" Average gamma"] = f"{tag.get_gamma():3.2f}"
10117 transfer_function = tag.get_transfer_function(
10118 slice_=(0, 1.0), outoffset=1.0
10119 )
10120 if round(transfer_function[1], 2) == 1.0:
10121 value = f"{transfer_function[0][0]}"
10122 elif transfer_function[1] >= 0.95:
10123 value = "≈ {} (Δ {:.2%})".format( # noqa: UP032
10124 transfer_function[0][0],
10125 1 - transfer_function[1],
10126 )
10127 else:
10128 value = "Unknown"
10129 info[" Transfer function"] = value
10130 elif isinstance(tag, CurveType):
10131 if len(tag) == 1:
10132 value = (f"{tag[0]:3.2f}").rstrip("0").rstrip(".")
10133 if "." not in value:
10134 value = f"{value}.0"
10135 info[name] = f"Gamma {value}"
10136 elif len(tag):
10137 info[name] = ""
10138 info[" Number of entries"] = f"{len(tag):d}"
10139 # info[" Average gamma"] = f"{tag.get_gamma():3.2f}"
10140 transfer_function = tag.get_transfer_function(
10141 slice_=(0, 1.0), outoffset=1.0
10142 )
10143 if round(transfer_function[1], 2) == 1.0:
10144 value = f"{transfer_function[0][0]}"
10145 elif transfer_function[1] >= 0.95:
10146 value = "≈ {} (Δ {:.2%})".format( # noqa: UP032
10147 transfer_function[0][0],
10148 1 - transfer_function[1],
10149 )
10150 else:
10151 value = "Unknown"
10152 info[" Transfer function"] = value
10153 info[" Minimum Y"] = f"{tag[0] / 65535.0 * 100:6.4f}"
10154 info[" Maximum Y"] = f"{tag[-1] / 65535.0 * 100:6.2f}"
10155 elif isinstance(tag, DictType):
10156 name = "Metadata" if sig == "meta" else "Generic name-value data"
10157 info[name] = ""
10158 for key in tag:
10159 record = tag.get(key)
10160 value = record.get("value")
10161 if value and key == "prefix":
10162 value = "\n".join(value.split(","))
10163 info[f" {key}"] = value
10164 elements = {}
10165 for subkey in ("display_name", "display_value"):
10166 entry = record.get(subkey)
10167 if isinstance(entry, MultiLocalizedUnicodeType):
10168 for language in entry:
10169 countries = entry[language]
10170 for country in countries:
10171 value = countries[country]
10172 if country.strip("\0 "):
10173 country = f"/{country}"
10174 loc = f"{language}{country}"
10175 if loc not in elements:
10176 elements[loc] = {}
10177 elements[loc][subkey] = value
10178 for loc in elements:
10179 items = elements[loc]
10180 if len(items) > 1:
10181 value = "{} = {}".format(*items.values())
10182 elif "display_name" in items:
10183 value = "{}".format(items["display_name"])
10184 else:
10185 value = " = {}".format(items["display_value"])
10186 info[f" {loc}"] = value
10187 elif isinstance(tag, LUT16Type):
10188 info[name] = ""
10189 name = " Matrix"
10190 for i, row in enumerate(tag.matrix):
10191 if i > 0:
10192 name = " " * 2
10193 info[name] = " ".join(f"{v:6.4f}" for v in row)
10194 info[" Input Table"] = ""
10195 info[" Channels"] = f"{int(tag.input_channels_count):d}"
10196 info[" Number of entries per channel"] = (
10197 f"{int(tag.input_entries_count):d}"
10198 )
10199 info[" Color Look Up Table"] = ""
10200 info[" Grid Steps"] = f"{int(tag.clut_grid_steps):d}"
10201 info[" Entries"] = "{:d}".format( # noqa: UP032
10202 int(tag.clut_grid_steps**tag.input_channels_count)
10203 )
10204 info[" Output Table"] = ""
10205 info[" Channels"] = f"{int(tag.output_channels_count):d}"
10206 info[" Number of entries per channel"] = (
10207 f"{int(tag.output_entries_count):d}"
10208 )
10209 elif isinstance(tag, MakeAndModelType):
10210 info[name] = ""
10211 manufacturer_code = tag.manufacturer
10212 manufacturer_name = edid.get_manufacturer_name(
10213 edid.parse_manufacturer_id(manufacturer_code.ljust(2, b"\0")[:2])
10214 )
10215 info[" Manufacturer"] = "0x{} {}".format(
10216 binascii.hexlify(manufacturer_code).decode("utf-8").upper(),
10217 manufacturer_name or "",
10218 )
10219 info[" Model"] = "0x{}".format(
10220 binascii.hexlify(tag.model).decode("utf-8").upper()
10221 )
10222 elif isinstance(tag, MeasurementType):
10223 info[name] = ""
10224 info[" Observer"] = tag.observer.description
10225 info[" Backing XYZ"] = " ".join(
10226 f"{v:6.2f}" for v in list(tag.backing.values())
10227 )
10228 info[" Geometry"] = tag.geometry.description
10229 info[" Flare"] = f"{tag.flare:.2%}"
10230 info[" Illuminant"] = tag.illuminantType.description
10231 elif isinstance(tag, MultiLocalizedUnicodeType):
10232 info[name] = ""
10233 for language in tag:
10234 countries = tag[language]
10235 for country in countries:
10236 value = countries[country]
10237 country = country.decode()
10238 if country.strip("\0 "):
10239 country = "/" + country
10240 language = language.decode()
10241 info[f" {language}{country}"] = value
10242 elif isinstance(tag, NamedColor2Type):
10243 info[name] = ""
10244 info[" Device color components"] = f"{int(tag.deviceCoordCount):d}"
10245 info[" Colors (PCS-relative)"] = (
10246 f"{int(tag.colorCount):d} ({len(tag.tagData):d} Bytes) "
10247 )
10248 i = 1
10249 for k in tag:
10250 v = tag[k]
10251 pcsout = []
10252 for _kk in v.pcs:
10253 vv = v.pcs[_kk]
10254 pcsout.append(f"{vv:03.2f}")
10255 devout = [f"{vv:03.2f}" for vv in v.device]
10256 formatstr = (
10257 f" {{:0{len(str(tag.colorCount)):d}}} {{}}{{}}{{}}"
10258 )
10259 key = formatstr.format(i, tag.prefix, k, tag.suffix)
10260 info[key] = "{} {}".format(
10261 "".join(list(v.pcs.keys())),
10262 " ".join(pcsout),
10263 )
10264 if self.colorSpace != self.connectionColorSpace or " ".join(
10265 pcsout
10266 ) != " ".join(devout):
10267 info[key] += " ({} {})".format(
10268 self.colorSpace, " ".join(devout)
10269 )
10270 i += 1
10271 elif isinstance(tag, ProfileSequenceDescType):
10272 info[name] = ""
10273 for i, desc in enumerate(tag):
10274 info[" " * 4 + f"{i + 1:d}"] = ""
10275 ICCProfile.add_device_info(info, desc, 2)
10276 for desc_type in ("dmnd", "dmdd"):
10277 description = str(desc[desc_type])
10278 if description:
10279 info[" " * 8 + TAGS[desc_type]] = description
10280 elif isinstance(tag, Text):
10281 if sig == "cprt":
10282 info[name] = str(tag)
10283 elif sig == "ciis":
10284 info[name] = CIIS.get(tag, f"'{tag}'")
10285 elif sig == "tech":
10286 print(f"tag: {tag}")
10287 print(f"type(tag): {type(tag)}")
10288 info[name] = TECH.get(tag, f"'{tag}'")
10289 elif tag.find(b"\n") > -1 or tag.find(b"\r") > -1:
10290 info[name] = f"[{len(tag):d} Bytes]"
10291 else:
10292 info[name] = tag[: 60 - len(name)] + (
10293 b"...[%i more Bytes]" % (len(tag) - (60 - len(name)))
10294 if len(tag) > 60 - len(name)
10295 else b""
10296 )
10297 elif isinstance(tag, TextDescriptionType):
10298 if not tag.get("Unicode") and not tag.get("Macintosh"):
10299 info[f"{name} (ASCII)"] = tag.ASCII.decode("utf-8")
10300 else:
10301 info[name] = ""
10302 info[" ASCII"] = tag.ASCII.decode("utf-8")
10303 if tag.get("Unicode"):
10304 info[" Unicode"] = tag.Unicode
10305 if tag.get("Macintosh"):
10306 info[" Macintosh"] = tag.Macintosh
10307 elif isinstance(tag, VideoCardGammaFormulaType):
10308 info[name] = ""
10309 # linear = tag.is_linear()
10310 # info[" Is linear"] = {0: "No", 1: "Yes"}[linear]
10311 for key in ("red", "green", "blue"):
10312 info[f" {key.capitalize()} gamma"] = "{:.2f}".format(
10313 tag[f"{key}Gamma"]
10314 )
10315 info[f" {key.capitalize()} minimum"] = "{:.2f}".format(
10316 tag[f"{key}Min"]
10317 )
10318 info[f" {key.capitalize()} maximum"] = "{:.2f}".format(
10319 tag[f"{key}Max"]
10320 )
10321 elif isinstance(tag, VideoCardGammaTableType):
10322 info[name] = ""
10323 info[" Bitdepth"] = f"{int(tag.entrySize * 8):d}"
10324 info[" Channels"] = f"{int(tag.channels):d}"
10325 info[" Number of entries per channel"] = f"{int(tag.entryCount):d}"
10326 r_points, g_points, b_points, linear_points = tag.get_values()
10327 points = r_points, g_points, b_points
10328 # if r_points == g_points == b_points == linear_points:
10329 # info[" Is linear".format(i)] = {
10330 # True: "Yes"
10331 # }.get(points[i] == linear_points, "No")
10332 # else:
10333 if True:
10334 unique = tag.get_unique_values()
10335 for i, channel in enumerate(tag.data):
10336 scale = math.pow(2, tag.entrySize * 8) - 1
10337 vmin = 0
10338 vmax = scale
10339 gamma = colormath.get_gamma(
10340 [
10341 (
10342 (len(channel) / 2 - 1)
10343 / (len(channel) - 1.0)
10344 * scale,
10345 channel[int(len(channel) / 2 - 1)],
10346 )
10347 ],
10348 scale,
10349 vmin,
10350 vmax,
10351 False,
10352 False,
10353 )
10354 if gamma:
10355 info[f" Channel {i + 1} gamma at 50% input"] = (
10356 f"{gamma[0]:.2f}"
10357 )
10358 vmin = channel[0]
10359 vmax = channel[-1]
10360 info[f" Channel {i + 1} minimum"] = f"{vmin / scale:6.4%}"
10361 info[f" Channel {i + 1} maximum"] = f"{vmax / scale:6.2%}"
10362 info[f" Channel {i + 1} unique values"] = (
10363 f"{len(unique[i])} @ 8 Bit"
10364 )
10365 info[f" Channel {i + 1} is linear"] = (
10366 "Yes" if points[i] == linear_points else "No"
10367 )
10368 elif isinstance(tag, ViewingConditionsType):
10369 info[name] = ""
10370 info[" Illuminant"] = tag.illuminantType.description
10371 info[" Illuminant XYZ"] = "{} (xy {})".format(
10372 " ".join(f"{v:6.2f}" for v in list(tag.illuminant.values())),
10373 " ".join(f"{v:6.4f}" for v in tag.illuminant.xyY[:2]),
10374 )
10375 XYZxy = [" ".join(f"{v:6.2f}" for v in list(tag.surround.values()))] # noqa: N806
10376 if list(tag.surround.values()) != [0, 0, 0]:
10377 XYZxy.append(
10378 "(xy {})".format(
10379 " ".join(f"{v:6.4f}" for v in tag.surround.xyY[:2])
10380 )
10381 )
10382 info[" Surround XYZ"] = " ".join(XYZxy)
10383 elif isinstance(tag, XYZType):
10384 if sig == "lumi":
10385 info[name] = f"{self.tags.lumi.Y:.2f} cd/m²"
10386 elif sig in ("bkpt", "wtpt"):
10387 file_format = {"bkpt": "{:6.4f}", "wtpt": "{:6.2f}"}[sig]
10388 info[name] = ""
10389 if self.profileClass == b"mntr" and sig == "wtpt":
10390 info[" Is illuminant"] = "Yes"
10391 if self.profileClass != b"prtr":
10392 label = "Illuminant-relative"
10393 else:
10394 label = "PCS-relative"
10395 # if (self.connectionColorSpace == "Lab"
10396 # and self.profileClass == "prtr"):
10397 if self.profileClass == b"prtr":
10398 color = [" ".join([file_format.format(v) for v in tag.ir.Lab])]
10399 info[f" {label} Lab"] = " ".join(color)
10400 else:
10401 color = [
10402 " ".join(
10403 file_format.format(v * 100)
10404 for v in list(tag.ir.values())
10405 )
10406 ]
10407 if list(tag.ir.values()) != [0, 0, 0]:
10408 xy = " ".join(f"{v:6.4f}" for v in tag.ir.xyY[:2])
10409 color.append(f"(xy {xy})")
10410 cct, delta = colormath.xy_CCT_delta(*tag.ir.xyY[:2])
10411 else:
10412 cct = None
10413 info[f" {label} XYZ"] = " ".join(color)
10414 if cct:
10415 info[f" {label} CCT"] = f"{int(cct):d}K"
10416 if delta:
10417 info[" ΔE 2000 to daylight locus"] = (
10418 f"{delta['E']:.2f}"
10419 )
10420 kwargs = {"daylight": False}
10421 cct, delta = colormath.xy_CCT_delta(
10422 *tag.ir.xyY[:2], **kwargs
10423 )
10424 if delta:
10425 info[" ΔE 2000 to blackbody locus"] = (
10426 f"{delta['E']:.2f}"
10427 )
10428 if "chad" in self.tags:
10429 color = [
10430 " ".join(
10431 file_format.format(v * 100)
10432 for v in list(tag.pcs.values())
10433 )
10434 ]
10435 if list(tag.pcs.values()) != [0, 0, 0]:
10436 xy = " ".join(f"{v:6.4f}" for v in tag.pcs.xyY[:2])
10437 color.append(f"(xy {xy})")
10438 info[" PCS-relative XYZ"] = " ".join(color)
10439 cct, delta = colormath.xy_CCT_delta(*tag.pcs.xyY[:2])
10440 if cct:
10441 info[" PCS-relative CCT"] = f"{int(cct):d}K"
10442 # if delta:
10443 # info[u" ΔE 2000 to daylight locus"] = (
10444 # f"{delta['E']:.2f}"
10445 # )
10446 # kwargs = {"daylight": False}
10447 # cct, delta = colormath.xy_CCT_delta(
10448 # *tag.pcs.xyY[:2], **kwargs
10449 # )
10450 # if delta:
10451 # info[u" ΔE 2000 to blackbody locus"] = (
10452 # f"{delta['E']:.2f}"
10453 # )
10454 else:
10455 info[name] = ""
10456 info[" Illuminant-relative XYZ"] = " ".join(
10457 [
10458 " ".join(f"{v * 100:6.2f}" for v in list(tag.ir.values())),
10459 "(xy {})".format(
10460 " ".join(f"{v:6.4f}" for v in tag.ir.xyY[:2])
10461 ),
10462 ]
10463 )
10464 info[" PCS-relative XYZ"] = " ".join(
10465 [
10466 " ".join(f"{v * 100:6.2f}" for v in list(tag.values())),
10467 "(xy {})".format(
10468 " ".join(f"{v:6.4f}" for v in tag.xyY[:2])
10469 ),
10470 ]
10471 )
10472 elif isinstance(tag, ICCProfileTag):
10473 info[name] = (
10474 f"'{tag.tagData[:4].decode()}' [{len(tag.tagData):d} Bytes]"
10475 )
10476 return info
10477
10478 def get_rgb_space(
10479 self, relation: str = "ir", gamma: None | bool = None
10480 ) -> bool | list:
10481 """Get RGB space from profile tags.
10482
10483 Args:
10484 relation (str, optional): 'ir' for illuminant-relative, 'pcs' for
10485 PCS-relative.
10486 gamma (None | bool, optional): If True, return gamma values,
10487 otherwise TRC values.
10488
10489 Returns:
10490 bool | list: False if the required tags are not present or a list
10491 containing the gamma/TRC values, the illuminant XYZ values, and
10492 the RGB XYZ values in the specified relation.
10493 """
10494 tags = self.tags
10495 if "wtpt" not in tags:
10496 return False
10497 rgb_space = [gamma or [], list(getattr(tags.wtpt, relation).values())]
10498 for component in ("r", "g", "b"):
10499 if f"{component}XYZ" not in tags or (
10500 not gamma
10501 and (
10502 f"{component}TRC" not in tags
10503 or not isinstance(tags[f"{component}TRC"], CurveType)
10504 )
10505 ):
10506 return False
10507 rgb_space.append(getattr(tags[f"{component}XYZ"], relation).xyY)
10508 if not gamma:
10509 if len(tags[f"{component}TRC"]) > 1:
10510 rgb_space[0].append([v / 65535.0 for v in tags[f"{component}TRC"]])
10511 else:
10512 rgb_space[0].append(tags[f"{component}TRC"][0])
10513 return rgb_space
10514
10515 def get_chardata_bkpt(self, illuminant_relative: bool = False) -> None | list:
10516 """Get blackpoint from embeded characterization data ('targ' tag).
10517
10518 Args:
10519 illuminant_relative (bool): If True, return the blackpoint
10520 relative to the profile's illuminant, otherwise return it
10521 relative to D50.
10522
10523 Returns:
10524 None | list: A list containing the blackpoint XYZ values, or None
10525 if the blackpoint could not be determined.
10526 """
10527 if not isinstance(self.tags.get("targ"), Text):
10528 return None
10529
10530 from DisplayCAL.cgats import CGATS
10531
10532 ti3 = CGATS(self.tags.targ)
10533 if 0 not in ti3:
10534 return None
10535
10536 black = ti3[0].queryi({"RGB_R": 0, "RGB_G": 0, "RGB_B": 0})
10537 # May be several samples for black. Average them.
10538 if not black:
10539 return None
10540
10541 XYZbp = [0, 0, 0] # noqa: N806
10542 for sample in black.values():
10543 for i, component in enumerate("XYZ"):
10544 if "XYZ_" + component in sample:
10545 XYZbp[i] += sample["XYZ_" + component] / 100.0
10546 for i in range(3):
10547 XYZbp[i] /= len(black)
10548 if not illuminant_relative:
10549 # Adapt to D50
10550 white = ti3.get_white_cie()
10551 if white:
10552 XYZwp = [ # noqa: N806
10553 v / 100.0
10554 for v in (
10555 white["XYZ_X"],
10556 white["XYZ_Y"],
10557 white["XYZ_Z"],
10558 )
10559 ]
10560 else:
10561 XYZwp = list(self.tags.wtpt.ir.values()) # noqa: N806
10562 cat = self.guess_cat() or "Bradford"
10563 XYZbp = colormath.adapt(*XYZbp, whitepoint_source=XYZwp, cat=cat) # noqa: N806
10564 return XYZbp
10565
10566 def optimize(
10567 self, return_bytes_saved: bool = False, update_id: bool = True
10568 ) -> bool | int:
10569 """Optimize the tag data so that shared tags are only recorded once.
10570
10571 Return whether or not optimization was performed (not necessarily
10572 indicative of a reduction in profile size).
10573 If return_bytes_saved is True, return number of bytes saved instead
10574 (this sets the 'size' property of the profile to the new size).
10575
10576 If update_id is True, a non-NULL profile ID will also be updated.
10577
10578 Note that for profiles created by ICCProfile (and not read from disk),
10579 this will always be superfluous because they are optimized by default.
10580
10581 Args:
10582 return_bytes_saved (bool): If True, return the number of bytes
10583 saved by the optimization instead of a boolean indicating
10584 whether optimization was performed.
10585 update_id (bool): If True, update the profile ID after
10586 optimization.
10587
10588 Returns:
10589 bool | int: If return_bytes_saved is True, returns the number of
10590 bytes saved by the optimization. If return_bytes_saved is False,
10591 returns True if optimization was performed, otherwise False.
10592 """
10593 numoffsets = len(self._tagoffsets)
10594 offsets = [
10595 (-(numoffsets - i), tag_sig)
10596 for i, (offset, tag_sig) in enumerate(sorted(self._tagoffsets))
10597 ]
10598 if self._tagoffsets != offsets:
10599 if return_bytes_saved:
10600 oldsize = len(self.data)
10601 # Discard original offsets
10602 self._tagoffsets = offsets
10603 if update_id and self.ID != b"\0" * 16:
10604 self.calculate_id()
10605 else:
10606 # No longer reflects original profile
10607 self._delfromcache()
10608 if return_bytes_saved:
10609 self.size = len(self.data)
10610 return oldsize - self.size
10611 return True
10612 return 0 if return_bytes_saved else False
10613
10614 def read(self, profile: str | pathlib.Path | bytes | BinaryIO | TextIO) -> None:
10615 """Read profile from binary string, filename or file object.
10616
10617 Same as self.__init__(profile)
10618
10619 Args:
10620 profile (str | pathlib.Path | bytes | BinaryIO | TextIO): The
10621 profile to read, which can be a filename, a file-like
10622 object, or a bytes object containing the profile data.
10623 """
10624 self.__init__(profile)
10625
10626 def set_edid_metadata(self, edid: dict) -> None:
10627 """Set metadata from EDID.
10628
10629 Key names follow the ICC meta Tag for Monitor Profiles specification
10630 http://www.oyranos.org/wiki/index.php?title=ICC_meta_Tag_for_Monitor_Profiles_0.1
10631 and the GNOME Color Manager metadata specification
10632 http://gitorious.org/colord/master/blobs/master/doc/metadata-spec.txt
10633
10634 Args:
10635 edid (dict): A dictionary containing EDID data, which should
10636 include keys like 'manufacturer_id', 'product_id',
10637 'year_of_manufacture', 'week_of_manufacture', 'red_x', 'red_y',
10638 'green_x', 'green_y', 'blue_x', 'blue_y', 'white_x', 'white_y',
10639 'hash', 'manufacturer', 'monitor_name', 'serial_ascii',
10640 'serial_32', and 'gamma'.
10641 """
10642 if "meta" not in self.tags:
10643 self.tags.meta = DictType()
10644 spec_prefixes = "EDID_"
10645 prefix = self.tags.meta.getvalue("prefix", b"", None)
10646 if isinstance(prefix, bytes):
10647 prefix = prefix.decode("utf-8")
10648 prefixes = (prefix or spec_prefixes).split(",")
10649 for prefix in spec_prefixes.split(","):
10650 if prefix not in prefixes:
10651 prefixes.append(prefix)
10652 # OpenICC keys (some shared with GCM)
10653 self.tags.meta.update(
10654 (
10655 ("prefix", ",".join(prefixes)),
10656 ("EDID_mnft", edid["manufacturer_id"]),
10657 ("EDID_mnft_id", struct.unpack(">H", edid["edid"][8:10])[0]),
10658 ("EDID_model_id", edid["product_id"]),
10659 (
10660 "EDID_date",
10661 "{:04d}-T{:d}".format(
10662 int(edid["year_of_manufacture"]),
10663 int(edid["week_of_manufacture"]),
10664 ),
10665 ),
10666 ("EDID_red_x", edid["red_x"]),
10667 ("EDID_red_y", edid["red_y"]),
10668 ("EDID_green_x", edid["green_x"]),
10669 ("EDID_green_y", edid["green_y"]),
10670 ("EDID_blue_x", edid["blue_x"]),
10671 ("EDID_blue_y", edid["blue_y"]),
10672 ("EDID_white_x", edid["white_x"]),
10673 ("EDID_white_y", edid["white_y"]),
10674 )
10675 )
10676 manufacturer = edid.get("manufacturer")
10677 if manufacturer:
10678 self.tags.meta["EDID_manufacturer"] = manufacturer
10679 if "gamma" in edid:
10680 self.tags.meta["EDID_gamma"] = edid["gamma"]
10681 monitor_name = edid.get("monitor_name", edid.get("ascii"))
10682 if monitor_name:
10683 self.tags.meta["EDID_model"] = monitor_name
10684 if edid.get("serial_ascii"):
10685 self.tags.meta["EDID_serial"] = edid["serial_ascii"]
10686 elif edid.get("serial_32"):
10687 # don't try to convert the following ``str`` to ``bytes``.
10688 # the edid["serial_32"] is a huge number and bytes({int}) is not working
10689 # like str({int}). What it tries is to create a b"\0" * {int}.
10690 self.tags.meta["EDID_serial"] = str(edid["serial_32"])
10691 # Gnome Color Management keys
10692 self.tags.meta["EDID_md5"] = edid["hash"]
10693
10694 def set_gamut_metadata(
10695 self, gamut_volume: None | float = None, gamut_coverage: None | dict = None
10696 ) -> None:
10697 """Set gamut volume and coverage metadata keys.
10698
10699 Args:
10700 gamut_volume (None | float, optional): The gamut volume in cubic
10701 colorspace units (L*a*b*).
10702 gamut_coverage (None | dict, optional): A dictionary with gamut
10703 coverage factors for different color spaces, e.g.
10704 {'sRGB': 0.95, 'AdobeRGB': 0.85}.
10705 """
10706 if not gamut_volume and not gamut_coverage:
10707 return
10708 if "meta" not in self.tags:
10709 self.tags.meta = DictType()
10710 # Update meta prefix
10711 prefix = self.tags.meta.getvalue("prefix", b"", None)
10712 if isinstance(prefix, bytes):
10713 prefix = prefix.decode("utf-8")
10714 prefixes = (prefix or "GAMUT_").split(",")
10715 if "GAMUT_" not in prefixes:
10716 prefixes.append("GAMUT_")
10717 self.tags.meta["prefix"] = ",".join(prefixes)
10718 if gamut_volume:
10719 # Set gamut size
10720 self.tags.meta["GAMUT_volume"] = gamut_volume
10721 if gamut_coverage:
10722 # Set gamut coverage
10723 for key in gamut_coverage:
10724 factor = gamut_coverage[key]
10725 self.tags.meta[f"GAMUT_coverage({key})"] = factor
10726
10727 def write(self, stream_or_filename: None | str | BinaryIO = None) -> None:
10728 """Write profile to stream.
10729
10730 This will re-assemble the various profile parts (header,
10731 tag table and data) on-the-fly.
10732
10733 Args:
10734 stream_or_filename (None | str | BinaryIO): The stream or
10735 filename to write the profile to. If None, the profile will
10736 be written to the filename it was loaded from.
10737 """
10738 if not stream_or_filename:
10739 if self._file and not self._file.closed:
10740 self.close()
10741 stream_or_filename = self.filename
10742 if isinstance(stream_or_filename, str):
10743 with open(stream_or_filename, "wb") as stream:
10744 if not self.filename:
10745 self.filename = stream_or_filename
10746 stream.write(self.data)
10747 else:
10748 stream_or_filename.write(self.data)
10749
10750 def __getattribute__(self, name: str) -> Any: # noqa: ANN401
10751 """Get attribute, but also update the cache if necessary.
10752
10753 Args:
10754 name (str): The name of the attribute to get.
10755
10756 Returns:
10757 Any: The value of the attribute.
10758 """
10759 if name == "write" or name.startswith(("set", "apply")):
10760 # No longer reflects original profile
10761 self._delfromcache()
10762 return object.__getattribute__(self, name)
10763
10764 def _delfromcache(self) -> None:
10765 """Remove ourselves from the cache."""
10766 # Make double sure to remove ourselves from the cache
10767 if self._key and self._key in _ICCPROFILE_CACHE:
10768 with contextlib.suppress(KeyError):
10769 del _ICCPROFILE_CACHE[self._key]
10770 # GC was faster