cmapkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cmapkit/__init__.py +17 -0
- cmapkit/_machado.py +50 -0
- cmapkit/bounds.py +257 -0
- cmapkit/calibrate.py +181 -0
- cmapkit/hdrmaps/__init__.py +33 -0
- cmapkit/hdrmaps/curve.py +313 -0
- cmapkit/hdrmaps/data/maps.json +746 -0
- cmapkit/hdrmaps/library.py +130 -0
- cmapkit/hdrmaps/measure.py +62 -0
- cmapkit/hdrmaps/noise.py +176 -0
- cmapkit/hdrmaps/paths.py +143 -0
- cmapkit/mccp/__init__.py +6 -0
- cmapkit/mccp/data/palettes.json +5782 -0
- cmapkit/mccp/figures.py +222 -0
- cmapkit/mccp/optimise.py +914 -0
- cmapkit/mccp/order.py +124 -0
- cmapkit/mpl.py +180 -0
- cmapkit/space.py +314 -0
- cmapkit-0.1.0.dist-info/METADATA +363 -0
- cmapkit-0.1.0.dist-info/RECORD +24 -0
- cmapkit-0.1.0.dist-info/WHEEL +5 -0
- cmapkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- cmapkit-0.1.0.dist-info/licenses/NOTICE +34 -0
- cmapkit-0.1.0.dist-info/top_level.txt +1 -0
cmapkit/mccp/order.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Ordering and grouping of a palette (docs/design.md, Section 7)."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def distance_matrix(rgb, space):
|
|
7
|
+
"""Least distance over observers between each pair of colours."""
|
|
8
|
+
u = space.coords(rgb)
|
|
9
|
+
d = np.linalg.norm(u[:, :, None] - u[:, None, :], axis=-1)
|
|
10
|
+
return d.min(axis=0)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _path_length(d, order):
|
|
14
|
+
return d[order[:-1], order[1:]].sum()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _two_opt(d, order, sign):
|
|
18
|
+
"""Improve an open path; sign=+1 minimises length, -1 maximises it."""
|
|
19
|
+
order = list(order)
|
|
20
|
+
n = len(order)
|
|
21
|
+
improved = True
|
|
22
|
+
while improved:
|
|
23
|
+
improved = False
|
|
24
|
+
for i in range(n - 2):
|
|
25
|
+
for j in range(i + 2, n):
|
|
26
|
+
a, b = order[i], order[i + 1]
|
|
27
|
+
c = order[j]
|
|
28
|
+
e = order[j + 1] if j + 1 < n else None
|
|
29
|
+
old = d[a, b] + (d[c, e] if e is not None else 0.0)
|
|
30
|
+
new = d[a, c] + (d[b, e] if e is not None else 0.0)
|
|
31
|
+
if sign * (new - old) < -1e-12:
|
|
32
|
+
order[i + 1:j + 1] = order[i + 1:j + 1][::-1]
|
|
33
|
+
improved = True
|
|
34
|
+
return order
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def path_order(d, kind="similar"):
|
|
38
|
+
"""Open path through all colours, shortest ('similar') or longest
|
|
39
|
+
('contrasting'). Nearest-neighbour construction from every start,
|
|
40
|
+
followed by 2-opt; deterministic."""
|
|
41
|
+
n = len(d)
|
|
42
|
+
if n < 3:
|
|
43
|
+
return list(range(n))
|
|
44
|
+
sign = 1.0 if kind == "similar" else -1.0
|
|
45
|
+
best, best_len = None, None
|
|
46
|
+
for start in range(n):
|
|
47
|
+
order = [start]
|
|
48
|
+
left = set(range(n)) - {start}
|
|
49
|
+
while left:
|
|
50
|
+
last = order[-1]
|
|
51
|
+
nxt = min(left, key=lambda k: sign * d[last, k])
|
|
52
|
+
order.append(nxt)
|
|
53
|
+
left.remove(nxt)
|
|
54
|
+
order = _two_opt(d, order, sign)
|
|
55
|
+
length = sign * _path_length(d, order)
|
|
56
|
+
if best is None or length < best_len - 1e-12:
|
|
57
|
+
best, best_len = order, length
|
|
58
|
+
return best
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def cycle_order(d, kind="similar"):
|
|
62
|
+
"""Closed cycle (for the rings of the test figure)."""
|
|
63
|
+
order = path_order(d, kind)
|
|
64
|
+
return order
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def groups(d, size):
|
|
68
|
+
"""Partition colours into groups of at most `size`, maximising the least
|
|
69
|
+
distance within any group. Returns a list of index lists, best first."""
|
|
70
|
+
n = len(d)
|
|
71
|
+
k = int(np.ceil(n / size))
|
|
72
|
+
# Round-robin over the similar ordering puts alike colours in different groups.
|
|
73
|
+
order = path_order(d, "similar")
|
|
74
|
+
assign = np.empty(n, int)
|
|
75
|
+
for pos, i in enumerate(order):
|
|
76
|
+
assign[i] = pos % k
|
|
77
|
+
|
|
78
|
+
def group_min(a):
|
|
79
|
+
mins = []
|
|
80
|
+
for g in range(k):
|
|
81
|
+
m = np.flatnonzero(a == g)
|
|
82
|
+
if len(m) < 2:
|
|
83
|
+
mins.append(np.inf)
|
|
84
|
+
else:
|
|
85
|
+
sub = d[np.ix_(m, m)]
|
|
86
|
+
mins.append(sub[np.triu_indices(len(m), 1)].min())
|
|
87
|
+
return np.array(mins)
|
|
88
|
+
|
|
89
|
+
def key(a):
|
|
90
|
+
m = np.sort(group_min(a))
|
|
91
|
+
return tuple(m)
|
|
92
|
+
|
|
93
|
+
cur = key(assign)
|
|
94
|
+
improved = True
|
|
95
|
+
while improved:
|
|
96
|
+
improved = False
|
|
97
|
+
for i in range(n):
|
|
98
|
+
for j in range(i + 1, n):
|
|
99
|
+
if assign[i] == assign[j]:
|
|
100
|
+
continue
|
|
101
|
+
assign[i], assign[j] = assign[j], assign[i]
|
|
102
|
+
new = key(assign)
|
|
103
|
+
if new > cur:
|
|
104
|
+
cur = new
|
|
105
|
+
improved = True
|
|
106
|
+
else:
|
|
107
|
+
assign[i], assign[j] = assign[j], assign[i]
|
|
108
|
+
mins = group_min(assign)
|
|
109
|
+
out = []
|
|
110
|
+
for g in np.argsort(-mins):
|
|
111
|
+
members = list(np.flatnonzero(assign == g))
|
|
112
|
+
sub = d[np.ix_(members, members)]
|
|
113
|
+
inner = path_order(sub, "contrasting")
|
|
114
|
+
out.append([members[i] for i in inner])
|
|
115
|
+
return out
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def order_indices(rgb, space, kind):
|
|
119
|
+
"""Indices that reorder a palette. kind is 'similar', 'contrasting', or
|
|
120
|
+
an integer group size."""
|
|
121
|
+
d = distance_matrix(rgb, space)
|
|
122
|
+
if isinstance(kind, int):
|
|
123
|
+
return [i for g in groups(d, kind) for i in g]
|
|
124
|
+
return path_order(d, kind)
|
cmapkit/mpl.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Matplotlib helpers.
|
|
2
|
+
|
|
3
|
+
matplotlib is imported only when these functions are called, so the rest of
|
|
4
|
+
the package does not depend on it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .mccp.optimise import palette
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _opaque_hex(colour):
|
|
11
|
+
"""'#rrggbb' of a colour, or None if it is fully transparent."""
|
|
12
|
+
import matplotlib.colors as mcolors
|
|
13
|
+
if isinstance(colour, str) and colour.lower() == "none":
|
|
14
|
+
return None
|
|
15
|
+
rgba = mcolors.to_rgba(colour)
|
|
16
|
+
return None if rgba[3] == 0 else mcolors.to_hex(rgba, keep_alpha=False)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _background(ax=None):
|
|
20
|
+
"""The colour behind the data of ax: its own face colour, or, if that is
|
|
21
|
+
transparent or hidden (as for twin axes), that of an axes in the same
|
|
22
|
+
place, then the figure's. Without ax, the current style's defaults."""
|
|
23
|
+
import matplotlib as mpl
|
|
24
|
+
if ax is None:
|
|
25
|
+
return (_opaque_hex(mpl.rcParams["axes.facecolor"])
|
|
26
|
+
or _opaque_hex(mpl.rcParams["figure.facecolor"]) or "#ffffff")
|
|
27
|
+
candidates = [ax]
|
|
28
|
+
if not ax.patch.get_visible() or _opaque_hex(ax.get_facecolor()) is None:
|
|
29
|
+
box = ax.get_position().bounds
|
|
30
|
+
candidates += [o for o in ax.figure.axes
|
|
31
|
+
if o is not ax and o.get_position().bounds == box]
|
|
32
|
+
for a in candidates:
|
|
33
|
+
if a.patch.get_visible():
|
|
34
|
+
c = _opaque_hex(a.get_facecolor())
|
|
35
|
+
if c:
|
|
36
|
+
return c
|
|
37
|
+
return _opaque_hex(ax.figure.get_facecolor()) or "#ffffff"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def cycler(n, **kwargs):
|
|
41
|
+
"""A matplotlib cycler of n MCCP colours. Keyword arguments go to
|
|
42
|
+
cmapkit.palette; the background defaults to the current style's axes
|
|
43
|
+
colour."""
|
|
44
|
+
from cycler import cycler as _cycler
|
|
45
|
+
kwargs.setdefault("background", _background())
|
|
46
|
+
return _cycler(color=palette(n, **kwargs).hex)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def use(n, ax=None, **kwargs):
|
|
50
|
+
"""Set the colour cycle to n MCCP colours: for one set of axes if ax is
|
|
51
|
+
given, otherwise for all later figures. The background is taken from ax,
|
|
52
|
+
or from the current style, unless given. Returns the palette."""
|
|
53
|
+
import matplotlib as mpl
|
|
54
|
+
kwargs.setdefault("background", _background(ax))
|
|
55
|
+
pal = palette(n, **kwargs)
|
|
56
|
+
if ax is None:
|
|
57
|
+
mpl.rcParams["axes.prop_cycle"] = mpl.cycler(color=pal.hex)
|
|
58
|
+
else:
|
|
59
|
+
ax.set_prop_cycle(color=pal.hex)
|
|
60
|
+
return pal
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
SUPPORTED = "lines drawn in data coordinates (plot, step, semilogy, ...) and single-colour scatter plots"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def series(ax):
|
|
67
|
+
"""The artists recolor() would recolour on ax, in the order they were
|
|
68
|
+
added, and a list of the kinds of artist it cannot handle."""
|
|
69
|
+
from matplotlib.collections import Collection, PathCollection
|
|
70
|
+
from matplotlib.lines import Line2D
|
|
71
|
+
out, unsupported = [], []
|
|
72
|
+
for c in ax.containers:
|
|
73
|
+
unsupported.append(type(c).__name__)
|
|
74
|
+
for p in ax.patches:
|
|
75
|
+
unsupported.append(type(p).__name__)
|
|
76
|
+
for a in ax.get_children():
|
|
77
|
+
if isinstance(a, Line2D) and a in ax.lines:
|
|
78
|
+
if a.get_transform() != ax.transData:
|
|
79
|
+
continue # axhline, axvline and other reference lines
|
|
80
|
+
if a.get_label() == "_nolegend_":
|
|
81
|
+
unsupported.append("box plot or other composite plot")
|
|
82
|
+
continue
|
|
83
|
+
out.append(a)
|
|
84
|
+
elif isinstance(a, PathCollection):
|
|
85
|
+
if a.get_array() is not None:
|
|
86
|
+
unsupported.append("scatter with c= (colour-mapped)")
|
|
87
|
+
else:
|
|
88
|
+
out.append(a)
|
|
89
|
+
elif isinstance(a, Collection) and a in ax.collections:
|
|
90
|
+
unsupported.append(type(a).__name__)
|
|
91
|
+
return out, unsupported
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _axes_of(target):
|
|
95
|
+
import matplotlib.pyplot as plt
|
|
96
|
+
from matplotlib.figure import Figure
|
|
97
|
+
if target is None:
|
|
98
|
+
return [plt.gca()]
|
|
99
|
+
if isinstance(target, Figure):
|
|
100
|
+
return list(target.axes)
|
|
101
|
+
if isinstance(target, (list, tuple)):
|
|
102
|
+
return list(target)
|
|
103
|
+
return [target]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _set_colour(artist, colour):
|
|
107
|
+
from matplotlib.collections import Collection
|
|
108
|
+
from matplotlib.patches import Patch
|
|
109
|
+
if isinstance(artist, Collection):
|
|
110
|
+
fc = artist.get_facecolor()
|
|
111
|
+
if len(fc) and fc[0][3] > 0:
|
|
112
|
+
artist.set_facecolor(colour)
|
|
113
|
+
artist.set_edgecolor(colour)
|
|
114
|
+
elif isinstance(artist, Patch):
|
|
115
|
+
artist.set_facecolor(colour)
|
|
116
|
+
artist.set_edgecolor(colour)
|
|
117
|
+
else:
|
|
118
|
+
artist.set_color(colour)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def recolor(target=None, artists=None, legend=True, strict=True, by_label=False, **kwargs):
|
|
122
|
+
"""Recolour the series already drawn with MCCP colours.
|
|
123
|
+
|
|
124
|
+
target is a set of axes (default: the current one), a list of axes, or a
|
|
125
|
+
figure; series on all of them are coloured together, so that no two share
|
|
126
|
+
a colour. Series are lines drawn in data coordinates and single-colour
|
|
127
|
+
scatter plots, in the order they were added. Reference lines (axhline,
|
|
128
|
+
axvline) are left alone. The series may instead be named with artists=.
|
|
129
|
+
|
|
130
|
+
Error bars, bars, histograms, filled areas, box plots and colour-mapped
|
|
131
|
+
scatter plots cannot be matched to one colour per series. With strict=True
|
|
132
|
+
(the default) they raise ValueError; otherwise they are left alone.
|
|
133
|
+
|
|
134
|
+
With by_label=True, series with the same label (for example the same
|
|
135
|
+
quantity in several panels) share a colour, and the palette has one
|
|
136
|
+
colour per distinct label.
|
|
137
|
+
|
|
138
|
+
Legends on the axes and the figure are updated in place. The background
|
|
139
|
+
is taken from the first axes unless given. Returns the palette."""
|
|
140
|
+
axes = _axes_of(target)
|
|
141
|
+
if artists is None:
|
|
142
|
+
artists, unsupported = [], []
|
|
143
|
+
for ax in axes:
|
|
144
|
+
a, u = series(ax)
|
|
145
|
+
artists += a
|
|
146
|
+
unsupported += u
|
|
147
|
+
if unsupported and strict:
|
|
148
|
+
raise ValueError("recolor() supports " + SUPPORTED + "; found "
|
|
149
|
+
+ ", ".join(sorted(set(unsupported)))
|
|
150
|
+
+ ". Pass artists=[...] or strict=False.")
|
|
151
|
+
if not artists:
|
|
152
|
+
raise ValueError("No series to recolour.")
|
|
153
|
+
kwargs.setdefault("background", _background(axes[0]))
|
|
154
|
+
keys = []
|
|
155
|
+
for a in artists:
|
|
156
|
+
label = a.get_label()
|
|
157
|
+
keys.append(label if by_label and label and not label.startswith("_") else id(a))
|
|
158
|
+
distinct = list(dict.fromkeys(keys))
|
|
159
|
+
pal = palette(len(distinct), **kwargs)
|
|
160
|
+
colour_of = dict(zip(distinct, pal.hex))
|
|
161
|
+
by_text = {}
|
|
162
|
+
for a, k in zip(artists, keys):
|
|
163
|
+
_set_colour(a, colour_of[k])
|
|
164
|
+
label = a.get_label()
|
|
165
|
+
if label and not label.startswith("_"):
|
|
166
|
+
by_text.setdefault(label, colour_of[k])
|
|
167
|
+
if legend:
|
|
168
|
+
legends = [ax.get_legend() for ax in axes]
|
|
169
|
+
legends += list(axes[0].figure.legends)
|
|
170
|
+
for leg in legends:
|
|
171
|
+
if leg is None:
|
|
172
|
+
continue
|
|
173
|
+
for text, handle in zip(leg.get_texts(), leg.legend_handles):
|
|
174
|
+
c = by_text.get(text.get_text())
|
|
175
|
+
if c is not None and handle is not None:
|
|
176
|
+
_set_colour(handle, c)
|
|
177
|
+
return pal
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
__all__ = ["cycler", "use", "recolor", "series"]
|
cmapkit/space.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Conversion from sRGB to CAM16-UCS, with flare and simulated colour vision.
|
|
2
|
+
|
|
3
|
+
The CAM16 equations follow Li et al. (2017); see docs/cam16-reference.md.
|
|
4
|
+
All functions are vectorised over a leading axis of colours.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from ._machado import MACHADO_2009
|
|
12
|
+
|
|
13
|
+
# Linear sRGB to CIE XYZ (IEC 61966-2-1), D65 white.
|
|
14
|
+
M_SRGB = np.array([[0.4124564, 0.3575761, 0.1804375],
|
|
15
|
+
[0.2126729, 0.7151522, 0.0721750],
|
|
16
|
+
[0.0193339, 0.1191920, 0.9503041]])
|
|
17
|
+
# White of the display, scaled so that Y = 100.
|
|
18
|
+
XYZ_WHITE = 100.0 * M_SRGB.sum(axis=1)
|
|
19
|
+
|
|
20
|
+
M16 = np.array([[0.401288, 0.650173, -0.051461],
|
|
21
|
+
[-0.250268, 1.204414, 0.045854],
|
|
22
|
+
[-0.002079, 0.048952, 0.953127]])
|
|
23
|
+
|
|
24
|
+
SURROUNDS = { # F, c, N_c (Li et al. 2017, Table A1)
|
|
25
|
+
"average": (1.0, 0.69, 1.0),
|
|
26
|
+
"dim": (0.9, 0.59, 0.9),
|
|
27
|
+
"dark": (0.8, 0.525, 0.8),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
UCS_CONSTANTS = { # K_L, c1, c2 (Luo et al. 2006)
|
|
31
|
+
"UCS": (1.00, 0.007, 0.0228),
|
|
32
|
+
"LCD": (0.77, 0.007, 0.0053),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def srgb_to_linear(rgb):
|
|
37
|
+
rgb = np.asarray(rgb, dtype=float)
|
|
38
|
+
return np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def linear_to_srgb(lin):
|
|
42
|
+
lin = np.clip(np.asarray(lin, dtype=float), 0.0, 1.0)
|
|
43
|
+
return np.where(lin <= 0.0031308, 12.92 * lin, 1.055 * lin ** (1 / 2.4) - 0.055)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def hex_to_rgb(colours):
|
|
47
|
+
"""Convert '#rrggbb' strings to an (n, 3) array of sRGB values in [0, 1]."""
|
|
48
|
+
if isinstance(colours, str):
|
|
49
|
+
colours = [colours]
|
|
50
|
+
out = []
|
|
51
|
+
for c in colours:
|
|
52
|
+
c = c.lstrip("#")
|
|
53
|
+
out.append([int(c[i:i + 2], 16) / 255 for i in (0, 2, 4)])
|
|
54
|
+
return np.array(out)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def to_hex(colour):
|
|
58
|
+
"""Normalise a colour ('#rgb', '#rrggbb', a matplotlib name, or an RGB
|
|
59
|
+
triple in [0, 1]) to '#rrggbb'."""
|
|
60
|
+
if isinstance(colour, str):
|
|
61
|
+
c = colour.strip().lower()
|
|
62
|
+
if c.startswith("#") and len(c) == 4:
|
|
63
|
+
return "#" + "".join(ch * 2 for ch in c[1:])
|
|
64
|
+
if c.startswith("#") and len(c) == 7:
|
|
65
|
+
return c
|
|
66
|
+
try:
|
|
67
|
+
from matplotlib.colors import to_hex as _mpl_to_hex
|
|
68
|
+
except ImportError as exc:
|
|
69
|
+
raise ValueError(f"Cannot parse colour {colour!r}") from exc
|
|
70
|
+
return _mpl_to_hex(colour)
|
|
71
|
+
return rgb_to_hex(np.asarray(colour, dtype=float))[0]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def rgb_to_hex(rgb):
|
|
75
|
+
rgb = np.clip(np.round(np.atleast_2d(rgb) * 255), 0, 255).astype(int)
|
|
76
|
+
return ["#{:02x}{:02x}{:02x}".format(*row) for row in rgb]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def relative_luminance(rgb):
|
|
80
|
+
"""Relative luminance on a 0-1 scale, as used by WCAG."""
|
|
81
|
+
return srgb_to_linear(rgb) @ M_SRGB[1]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def contrast_ratio(rgb1, rgb2):
|
|
85
|
+
"""WCAG 2.1 contrast ratio between colours."""
|
|
86
|
+
y1, y2 = relative_luminance(rgb1), relative_luminance(rgb2)
|
|
87
|
+
hi, lo = np.maximum(y1, y2), np.minimum(y1, y2)
|
|
88
|
+
return (hi + 0.05) / (lo + 0.05)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class Viewing:
|
|
93
|
+
"""Viewing conditions.
|
|
94
|
+
|
|
95
|
+
white_luminance: luminance of the display white, cd/m^2.
|
|
96
|
+
background_y: relative luminance of the background, white = 100.
|
|
97
|
+
surround: 'average', 'dim' or 'dark'.
|
|
98
|
+
flare: fraction of the white added to every colour.
|
|
99
|
+
ucs: 'UCS' or 'LCD' constant set.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
white_luminance: float = 80.0
|
|
103
|
+
background_y: float = 100.0
|
|
104
|
+
surround: str = "dim"
|
|
105
|
+
flare: float = 0.01
|
|
106
|
+
ucs: str = "UCS"
|
|
107
|
+
min_background_y: float = 2.0
|
|
108
|
+
# Override of K_L: weight of lightness against the chromatic axes.
|
|
109
|
+
# K_L < 1 makes lightness differences count for more (an ellipsoidal
|
|
110
|
+
# metric); None takes K_L from the constant set.
|
|
111
|
+
lightness_weight: float | None = None
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def adapting_luminance(self):
|
|
115
|
+
return self.white_luminance * self.y_b / 100.0
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def y_b(self):
|
|
119
|
+
return max(self.background_y, self.min_background_y)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
PRESETS = {
|
|
123
|
+
# sRGB reference viewing environment: 80 cd/m^2 white, 64 lux ambient
|
|
124
|
+
# (dim surround), 1 % viewing flare.
|
|
125
|
+
"screen": dict(white_luminance=80.0, surround="dim", flare=0.01),
|
|
126
|
+
# Provisional values, to be derived properly.
|
|
127
|
+
"screen-dark-room": dict(white_luminance=80.0, surround="dark", flare=0.002),
|
|
128
|
+
"projector": dict(white_luminance=50.0, surround="dark", flare=0.03),
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def viewing(preset="screen", background="#ffffff", **overrides):
|
|
133
|
+
"""Viewing conditions for a named preset and background colour."""
|
|
134
|
+
if preset != "screen":
|
|
135
|
+
import warnings
|
|
136
|
+
warnings.warn(f"The '{preset}' viewing preset has provisional values and is "
|
|
137
|
+
"experimental; only 'screen' has been calibrated.", stacklevel=2)
|
|
138
|
+
params = dict(PRESETS[preset])
|
|
139
|
+
y = float(relative_luminance(hex_to_rgb(to_hex(background)))[0]) * 100.0
|
|
140
|
+
params["background_y"] = y
|
|
141
|
+
params.update(overrides)
|
|
142
|
+
return Viewing(**params)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class CAM16UCS:
|
|
146
|
+
"""Forward transform from sRGB to CAM16-UCS under fixed viewing conditions."""
|
|
147
|
+
|
|
148
|
+
def __init__(self, view=None):
|
|
149
|
+
self.view = view or Viewing()
|
|
150
|
+
v = self.view
|
|
151
|
+
F, c, Nc = SURROUNDS[v.surround]
|
|
152
|
+
L_A = v.adapting_luminance
|
|
153
|
+
Yb = v.y_b
|
|
154
|
+
xyz_w = XYZ_WHITE
|
|
155
|
+
Yw = xyz_w[1]
|
|
156
|
+
rgb_w = M16 @ xyz_w
|
|
157
|
+
D = np.clip(F * (1 - (1 / 3.6) * np.exp((-L_A - 42) / 92)), 0, 1)
|
|
158
|
+
self.D_rgb = D * Yw / rgb_w + 1 - D
|
|
159
|
+
k = 1 / (5 * L_A + 1)
|
|
160
|
+
self.F_L = 0.2 * k ** 4 * (5 * L_A) + 0.1 * (1 - k ** 4) ** 2 * (5 * L_A) ** (1 / 3)
|
|
161
|
+
self.n = Yb / Yw
|
|
162
|
+
self.z = 1.48 + np.sqrt(self.n)
|
|
163
|
+
self.N_bb = 0.725 * (1 / self.n) ** 0.2
|
|
164
|
+
self.c, self.N_c = c, Nc
|
|
165
|
+
rgb_aw = self._compress(self.D_rgb * rgb_w)
|
|
166
|
+
self.A_w = (2 * rgb_aw[0] + rgb_aw[1] + rgb_aw[2] / 20 - 0.305) * self.N_bb
|
|
167
|
+
self.K_L, self.c1, self.c2 = UCS_CONSTANTS[v.ucs]
|
|
168
|
+
if v.lightness_weight is not None:
|
|
169
|
+
self.K_L = v.lightness_weight
|
|
170
|
+
|
|
171
|
+
def _compress(self, x):
|
|
172
|
+
t = (self.F_L * np.abs(x) / 100) ** 0.42
|
|
173
|
+
return np.sign(x) * 400 * t / (t + 27.13) + 0.1
|
|
174
|
+
|
|
175
|
+
def cam16_from_xyz(self, xyz):
|
|
176
|
+
"""Return J, M, h (degrees) for XYZ with white Y = 100."""
|
|
177
|
+
rgb = np.asarray(xyz, dtype=float) @ M16.T
|
|
178
|
+
ra = self._compress(rgb * self.D_rgb)
|
|
179
|
+
R, G, B = ra[..., 0], ra[..., 1], ra[..., 2]
|
|
180
|
+
a = R - 12 * G / 11 + B / 11
|
|
181
|
+
b = (R + G - 2 * B) / 9
|
|
182
|
+
h = np.degrees(np.arctan2(b, a)) % 360
|
|
183
|
+
e_t = 0.25 * (np.cos(np.radians(h) + 2) + 3.8)
|
|
184
|
+
A = (2 * R + G + B / 20 - 0.305) * self.N_bb
|
|
185
|
+
J = 100 * np.clip(A / self.A_w, 0, None) ** (self.c * self.z)
|
|
186
|
+
t = (50000 / 13 * self.N_c * self.N_bb * e_t * np.hypot(a, b)
|
|
187
|
+
/ (R + G + 21 * B / 20))
|
|
188
|
+
C = t ** 0.9 * np.sqrt(J / 100) * (1.64 - 0.29 ** self.n) ** 0.73
|
|
189
|
+
M = C * self.F_L ** 0.25
|
|
190
|
+
return J, M, h
|
|
191
|
+
|
|
192
|
+
def from_linear(self, lin):
|
|
193
|
+
"""Linear sRGB (n, 3) to CAM16-UCS (n, 3): J', a', b'."""
|
|
194
|
+
xyz = 100.0 * np.asarray(lin, dtype=float) @ M_SRGB.T
|
|
195
|
+
f = self.view.flare
|
|
196
|
+
xyz = (xyz + f * XYZ_WHITE) / (1 + f)
|
|
197
|
+
J, M, h = self.cam16_from_xyz(xyz)
|
|
198
|
+
Jp = (1 + 100 * self.c1) * J / (1 + self.c1 * J) / self.K_L
|
|
199
|
+
Mp = np.log1p(self.c2 * M) / self.c2
|
|
200
|
+
hr = np.radians(h)
|
|
201
|
+
return np.stack([Jp, Mp * np.cos(hr), Mp * np.sin(hr)], axis=-1)
|
|
202
|
+
|
|
203
|
+
def __call__(self, rgb):
|
|
204
|
+
"""sRGB (n, 3) in [0, 1] to CAM16-UCS (n, 3)."""
|
|
205
|
+
return self.from_linear(srgb_to_linear(rgb))
|
|
206
|
+
|
|
207
|
+
def xyz_from_cam16(self, J, M, h):
|
|
208
|
+
"""Inverse of cam16_from_xyz: XYZ (white Y = 100) from J, M and h in
|
|
209
|
+
degrees. The a and b of the opponent signals follow the inverse of
|
|
210
|
+
CIECAM02 (CIE 159:2004), which CAM16 shares."""
|
|
211
|
+
J, M, h = np.broadcast_arrays(*(np.asarray(x, dtype=float) for x in (J, M, h)))
|
|
212
|
+
hr = np.radians(h)
|
|
213
|
+
C = M / self.F_L ** 0.25
|
|
214
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
215
|
+
t = (C / (np.sqrt(J / 100) * (1.64 - 0.29 ** self.n) ** 0.73)) ** (1 / 0.9)
|
|
216
|
+
t = np.nan_to_num(t, nan=0.0, posinf=0.0)
|
|
217
|
+
e_t = 0.25 * (np.cos(hr + 2) + 3.8)
|
|
218
|
+
A = self.A_w * (J / 100) ** (1 / (self.c * self.z))
|
|
219
|
+
p2 = A / self.N_bb + 0.305
|
|
220
|
+
p3 = 21 / 20
|
|
221
|
+
s, c = np.sin(hr), np.cos(hr)
|
|
222
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
223
|
+
p1 = 50000 / 13 * self.N_c * self.N_bb * e_t / t
|
|
224
|
+
use_sin = np.abs(s) >= np.abs(c)
|
|
225
|
+
b_s = (p2 * (2 + p3) * 460 / 1403
|
|
226
|
+
/ (p1 / s + (2 + p3) * 220 / 1403 * c / s - 27 / 1403 + p3 * 6300 / 1403))
|
|
227
|
+
a_c = (p2 * (2 + p3) * 460 / 1403
|
|
228
|
+
/ (p1 / c + (2 + p3) * 220 / 1403 - (27 / 1403 - p3 * 6300 / 1403) * s / c))
|
|
229
|
+
a = np.where(use_sin, b_s * c / s, a_c)
|
|
230
|
+
b = np.where(use_sin, b_s, a_c * s / c)
|
|
231
|
+
a = np.where(t == 0, 0.0, a)
|
|
232
|
+
b = np.where(t == 0, 0.0, b)
|
|
233
|
+
ra = np.stack([(460 * p2 + 451 * a + 288 * b) / 1403,
|
|
234
|
+
(460 * p2 - 891 * a - 261 * b) / 1403,
|
|
235
|
+
(460 * p2 - 220 * a - 6300 * b) / 1403], axis=-1)
|
|
236
|
+
x = ra - 0.1
|
|
237
|
+
rc = np.sign(x) * 100 / self.F_L * (27.13 * np.abs(x) / (400 - np.abs(x))) ** (1 / 0.42)
|
|
238
|
+
return (rc / self.D_rgb) @ np.linalg.inv(M16).T
|
|
239
|
+
|
|
240
|
+
def to_linear(self, u):
|
|
241
|
+
"""CAM16-UCS (n, 3) to linear sRGB (n, 3), not clipped: values outside
|
|
242
|
+
[0, 1] mean the colour lies outside the sRGB gamut."""
|
|
243
|
+
u = np.asarray(u, dtype=float)
|
|
244
|
+
Jp = u[..., 0] * self.K_L
|
|
245
|
+
J = Jp / (1 + 100 * self.c1 - self.c1 * Jp)
|
|
246
|
+
Mp = np.hypot(u[..., 1], u[..., 2])
|
|
247
|
+
M = np.expm1(self.c2 * Mp) / self.c2
|
|
248
|
+
h = np.degrees(np.arctan2(u[..., 2], u[..., 1])) % 360
|
|
249
|
+
xyz = self.xyz_from_cam16(J, M, h)
|
|
250
|
+
f = self.view.flare
|
|
251
|
+
xyz = xyz * (1 + f) - f * XYZ_WHITE
|
|
252
|
+
return xyz @ np.linalg.inv(M_SRGB).T / 100.0
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
@dataclass(frozen=True)
|
|
256
|
+
class Observer:
|
|
257
|
+
"""An observer: normal vision, or a simulated deficiency at a severity."""
|
|
258
|
+
|
|
259
|
+
kind: str = "normal" # 'normal', 'protan', 'deutan' or 'tritan'
|
|
260
|
+
severity: float = 1.0
|
|
261
|
+
# Fraction of the common spacing this observer is guaranteed (max-min) or
|
|
262
|
+
# aimed at (power mean). 1 treats the observer like normal vision.
|
|
263
|
+
priority: float = 1.0
|
|
264
|
+
|
|
265
|
+
def matrix(self):
|
|
266
|
+
if self.kind == "normal":
|
|
267
|
+
return np.eye(3)
|
|
268
|
+
table = MACHADO_2009[self.kind]
|
|
269
|
+
x = np.clip(self.severity, 0, 1) * 10
|
|
270
|
+
i = int(min(np.floor(x), 9))
|
|
271
|
+
return table[i] + (x - i) * (table[i + 1] - table[i])
|
|
272
|
+
|
|
273
|
+
def __str__(self):
|
|
274
|
+
s = "normal" if self.kind == "normal" else f"{self.kind} {self.severity:g}"
|
|
275
|
+
return s if self.priority == 1.0 else f"{s} (priority {self.priority:g})"
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class Space:
|
|
279
|
+
"""CAM16-UCS coordinates of sRGB colours for one or more observers."""
|
|
280
|
+
|
|
281
|
+
def __init__(self, view=None, observers=(Observer(),)):
|
|
282
|
+
self.ucs = CAM16UCS(view)
|
|
283
|
+
self.observers = tuple(observers)
|
|
284
|
+
self._mats = [o.matrix() for o in self.observers]
|
|
285
|
+
|
|
286
|
+
def coords(self, rgb):
|
|
287
|
+
"""Return an array (n_observers, n, 3)."""
|
|
288
|
+
lin = srgb_to_linear(np.atleast_2d(rgb))
|
|
289
|
+
out = []
|
|
290
|
+
for m in self._mats:
|
|
291
|
+
# Simulated colours may fall outside the sRGB cube. They are not
|
|
292
|
+
# clipped: the cone signals of CAM16 stay positive for every
|
|
293
|
+
# observer over the whole cube, so the transform remains smooth.
|
|
294
|
+
out.append(self.ucs.from_linear(lin @ m.T))
|
|
295
|
+
return np.stack(out)
|
|
296
|
+
|
|
297
|
+
def jacobian(self, rgb, h=1e-6):
|
|
298
|
+
"""Coordinates and their derivatives with respect to sRGB.
|
|
299
|
+
|
|
300
|
+
Returns (coords, jac) with shapes (k, n, 3) and (k, n, 3, 3), where
|
|
301
|
+
jac[o, i, p, q] = d coord_p / d rgb_q, by central differences
|
|
302
|
+
(one-sided at the bounds of the cube).
|
|
303
|
+
"""
|
|
304
|
+
rgb = np.atleast_2d(np.asarray(rgb, dtype=float))
|
|
305
|
+
base = self.coords(rgb)
|
|
306
|
+
jac = np.empty(base.shape + (3,))
|
|
307
|
+
for q in range(3):
|
|
308
|
+
up = rgb.copy()
|
|
309
|
+
dn = rgb.copy()
|
|
310
|
+
up[:, q] = np.minimum(rgb[:, q] + h, 1.0)
|
|
311
|
+
dn[:, q] = np.maximum(rgb[:, q] - h, 0.0)
|
|
312
|
+
step = (up[:, q] - dn[:, q])[None, :, None]
|
|
313
|
+
jac[..., q] = (self.coords(up) - self.coords(dn)) / step
|
|
314
|
+
return base, jac
|