"""
Serialize a ColorSpace into ICC profile bytes.
"""
from __future__ import annotations
import struct
from collections.abc import Sequence
from typing import TYPE_CHECKING
import numpy as np
from ..._errors import ICCWriteError
from ...colorimetry import D50
from .._io import tagtypes as tt
from .._io.constants import CLASS_COLORSPACE, CLASS_DISPLAY, CLASS_INPUT, CS_GRAY, CS_RGB, CS_XYZ
from .._io.profile import ICCProfile
from .clut import write_clut
from .context import Context
from .lut import write_exact_lut
from .trc import write_gray_trc, write_matrix_trc
from .v5 import write_calc, write_mpet
if TYPE_CHECKING:
from ...spaces import ColorSpace
# LittleCMS scales floats of these data colour spaces; crsD makes readers pass plain [0, 1] values.
_SCALED_FLOAT_SPACES = frozenset(
{b"XYZ ", b"Lab ", b"CMY ", b"CMYK"} | {f"{c}CLR".encode() for c in "56789ABCDEF"}
)
def _colour_space_signature(colorspace: ColorSpace) -> bytes:
explicit = colorspace.icc_colour_space_signature
if explicit is not None:
return explicit
n = colorspace.n_channels
if n == 3:
return CS_RGB
if n == 1:
return CS_GRAY
if n <= 15:
return f"{n:X}CLR".encode("ascii")
raise ICCWriteError(f"ICC supports at most 15 device channels, got {n}")
def _text_tags(description: str, copyright: str, version_major: int) -> dict:
if version_major == 2:
return {b"desc": tt.encode_desc_v2(description), b"cprt": tt.encode_text(copyright)}
return {
b"desc": tt.encode_mluc({("en", "US"): description}),
b"cprt": tt.encode_mluc({("en", "US"): copyright}),
}
def _fallback_reasons(ctx: Context, forced: bool) -> list:
"""Why no exact representation was written."""
if forced:
return ["force_clut=True"]
if ctx.trace_failures:
return list(ctx.trace_failures.values())
if ctx.major == 5:
return ["the functions trace, but no matrix/curve chain or calculator program reproduces them"]
return [
"the functions are not a per-channel curve and matrix chain, which is all a v2/v4 "
"profile can hold exactly (version=5 adds calculator elements)"
]
def _require_traceable(ctx: Context) -> None:
"""Raise `ICCWriteError` naming why `to_xyz`/`from_xyz` cannot be traced, if they cannot."""
ctx.fwd_root, ctx.bwd_root # noqa: B018 - runs the tracer and records failures
if ctx.trace_failures:
raise ICCWriteError("cannot write an exact profile: " + "; ".join(ctx.trace_failures.values()))
[docs]
def write_icc_bytes(
colorspace: ColorSpace,
*,
version: Sequence[int] = (4, 4, 0),
rendering_intent: int = 1,
grid_size: int | None = None,
description: str | None = None,
copyright: str = "No copyright, generated by python-lcms2",
force_clut: bool = False,
strict: bool = False,
) -> dict:
"""Serialize a ColorSpace into ICC profile bytes.
Parameters
----------
colorspace : ColorSpace
The space to write.
version : tuple of int, optional
``(major, minor, bugfix)``. Default ``(4, 4, 0)``.
rendering_intent : int, optional
Header rendering intent. Default 1.
grid_size : int, optional
CLUT grid points per axis for a sampled fallback.
description, copyright : str, optional
Profile description and copyright text.
force_clut : bool, optional
Always write sampled CLUTs.
strict : bool, optional
Require an exact profile built from traced functions: raise `ICCWriteError`, naming the
operation that could not be traced, instead of falling back to sampled CLUTs (or to
probing the functions numerically).
Returns
-------
dict
``{'bytes': bytes, 'method': str, 'notes': list of str}``. When the sampled
fallback is used, `notes` says why (naming the untraceable operation).
Raises
------
ICCWriteError
If the space cannot be written at all, or with ``strict=True`` when only a sampled
fallback would be possible.
"""
ctx = Context(colorspace, version[0], grid_size)
description = description or f"{type(colorspace).__name__} (python-lcms2)"
tags = _text_tags(description, copyright, ctx.major)
tags[b"wtpt"] = tt.encode_XYZType([tuple(D50)])
notes = []
method = None
if ctx.one_way is not None:
if strict:
raise ICCWriteError(f"cannot write an exact profile: {ctx.one_way}")
write_clut(ctx, tags, notes, a2b_only=True)
notes.append(f"A2B0 only (an input profile): {ctx.one_way}")
force_clut, method = True, "clut_fallback"
elif strict and not force_clut:
_require_traceable(ctx)
if not force_clut:
ctx.fwd_root # noqa: B018 - traces, so `trace_failures` is complete
if not force_clut and ctx.deterministic:
if ctx.major in (2, 4):
if ctx.n == 3 and write_matrix_trc(ctx, tags, notes):
method = "exact_matrix_trc"
elif ctx.n == 1 and write_gray_trc(ctx, tags, notes):
method = "exact_gray_trc"
elif write_exact_lut(ctx, tags, notes):
method = "exact_lut"
else:
if write_mpet(ctx, tags, notes):
method = "exact_mpet"
elif write_calc(ctx, tags, notes):
method = "exact_calc"
if method is None:
reasons = _fallback_reasons(ctx, force_clut)
if strict and not force_clut:
raise ICCWriteError("no exact ICC representation: " + "; ".join(reasons))
write_clut(ctx, tags, notes)
notes.extend(f"sampled fallback: {r}" for r in reasons)
method = "clut_fallback"
elif ctx.trace_failures:
notes.extend(f"structure found by probing: {r}" for r in ctx.trace_failures.values())
lo = [d[0] for d in ctx.domain]
hi = [d[1] for d in ctx.domain]
if _colour_space_signature(colorspace) in _SCALED_FLOAT_SPACES or not (
np.allclose(lo, 0.0) and np.allclose(hi, 1.0)
):
tags[b"crsD"] = struct.pack(">I", ctx.n) + b"".join(struct.pack(">ff", a, b) for a, b in ctx.domain)
notes.append(f"device_domain {ctx.domain} mapped onto [0, 1] and stored in a 'crsD' tag")
circular = sorted(colorspace.circular_device_channels)
if circular:
tags[b"crsC"] = struct.pack(">I", len(circular)) + b"".join(struct.pack(">I", i) for i in circular)
notes.append(f"circular device channel(s) {circular} stored in a 'crsC' tag")
raw = ICCProfile.build_bytes(
version=version,
device_class=(
CLASS_INPUT
if ctx.one_way is not None
else CLASS_DISPLAY
if method in ("exact_matrix_trc", "exact_gray_trc")
else CLASS_COLORSPACE
),
data_colour_space=_colour_space_signature(colorspace),
pcs=CS_XYZ,
rendering_intent=rendering_intent,
pcs_illuminant=tuple(D50),
tags=tags,
)
return {"bytes": raw, "method": method, "notes": notes}