lut-match 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lut-match contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: lut-match
3
+ Version: 0.1.0
4
+ Summary: Fit smooth, zero-inversion .cube 3D LUTs and HaldCLUT PNGs from reference stills
5
+ License: MIT
6
+ Project-URL: Homepage, https://lumonopolis.github.io/lut-match/
7
+ Project-URL: Repository, https://github.com/Lumonopolis/lut-match
8
+ Keywords: color-grading,3d-lut,cube,haldclut,oklab,davinci-resolve,ffmpeg
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Multimedia :: Graphics
14
+ Classifier: Topic :: Multimedia :: Video
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.24
19
+ Requires-Dist: scipy>=1.10
20
+ Requires-Dist: pillow>=10.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.4; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # lut-match
26
+
27
+ Fit smooth, zero-inversion Adobe `.cube` 3D LUTs (`17³` / `33³` / `65³`) and Level-8 HaldCLUT PNGs from one or more reference stills in Python.
28
+
29
+ ![lut-match comparison](https://raw.githubusercontent.com/Lumonopolis/lut-match/main/docs/assets/hero-compare.png)
30
+
31
+ - **Browser Studio (zero install):** https://lumonopolis.github.io/lut-match/
32
+ - **Source & Benchmarks:** https://github.com/Lumonopolis/lut-match
33
+
34
+ ## Quickstart
35
+
36
+ ```bash
37
+ pip install lut-match
38
+
39
+ # Fit a 33^3 .cube LUT from one or more reference stills
40
+ lut-match fit --src shot.png --ref look1.jpg --ref look2.jpg -o grade.cube --hald grade_hald8.png
41
+
42
+ # Expressive single-still transfer with skin protection
43
+ lut-match fit --src shot.png --ref film_still.jpg -o creative.cube --mode creative --skin-protect 0.55
44
+
45
+ # Apply or inspect a .cube LUT
46
+ lut-match apply --lut grade.cube --in shot.png --out graded.png
47
+ lut-match inspect --lut grade.cube
48
+ ```
49
+
50
+ ```python
51
+ from lut_match import apply_lut, load_image, save_cube, solve_lut
52
+
53
+ src = load_image("shot.png")
54
+ ref = load_image("film_still.jpg")
55
+ lut = solve_lut(src, ref, size=33, mode="creative", skin_protect=0.5, idt="srgb")
56
+ save_cube(lut, "grade.cube", title="my-grade")
57
+ graded = apply_lut(src, lut)
58
+ ```
59
+
60
+ Supports 6 Input Device Transforms (`srgb`, `rec709`, `apple-log`, `slog3`, `vlog`, `clog3`), `Balanced` vs `Creative` transfer modes, and guarantees `0.00%` monotonicity inversions in sRGB/Rec.709 working space.
@@ -0,0 +1,36 @@
1
+ # lut-match
2
+
3
+ Fit smooth, zero-inversion Adobe `.cube` 3D LUTs (`17³` / `33³` / `65³`) and Level-8 HaldCLUT PNGs from one or more reference stills in Python.
4
+
5
+ ![lut-match comparison](https://raw.githubusercontent.com/Lumonopolis/lut-match/main/docs/assets/hero-compare.png)
6
+
7
+ - **Browser Studio (zero install):** https://lumonopolis.github.io/lut-match/
8
+ - **Source & Benchmarks:** https://github.com/Lumonopolis/lut-match
9
+
10
+ ## Quickstart
11
+
12
+ ```bash
13
+ pip install lut-match
14
+
15
+ # Fit a 33^3 .cube LUT from one or more reference stills
16
+ lut-match fit --src shot.png --ref look1.jpg --ref look2.jpg -o grade.cube --hald grade_hald8.png
17
+
18
+ # Expressive single-still transfer with skin protection
19
+ lut-match fit --src shot.png --ref film_still.jpg -o creative.cube --mode creative --skin-protect 0.55
20
+
21
+ # Apply or inspect a .cube LUT
22
+ lut-match apply --lut grade.cube --in shot.png --out graded.png
23
+ lut-match inspect --lut grade.cube
24
+ ```
25
+
26
+ ```python
27
+ from lut_match import apply_lut, load_image, save_cube, solve_lut
28
+
29
+ src = load_image("shot.png")
30
+ ref = load_image("film_still.jpg")
31
+ lut = solve_lut(src, ref, size=33, mode="creative", skin_protect=0.5, idt="srgb")
32
+ save_cube(lut, "grade.cube", title="my-grade")
33
+ graded = apply_lut(src, lut)
34
+ ```
35
+
36
+ Supports 6 Input Device Transforms (`srgb`, `rec709`, `apple-log`, `slog3`, `vlog`, `clog3`), `Balanced` vs `Creative` transfer modes, and guarantees `0.00%` monotonicity inversions in sRGB/Rec.709 working space.
@@ -0,0 +1,49 @@
1
+ from lut_match.color import (
2
+ SUPPORTED_IDTS,
3
+ apply_idt,
4
+ ciede2000,
5
+ linear_to_oklab,
6
+ linear_to_srgb,
7
+ oklab_to_linear,
8
+ rgb_to_lab,
9
+ srgb_to_linear,
10
+ srgb_to_oklab,
11
+ oklab_to_srgb,
12
+ )
13
+ from lut_match.io import (
14
+ apply_lut,
15
+ generate_hald_clut,
16
+ identity_lut,
17
+ inspect_lut,
18
+ load_cube,
19
+ load_hald_clut,
20
+ load_image,
21
+ save_cube,
22
+ save_hald_clut,
23
+ save_image,
24
+ )
25
+ from lut_match.solver import solve_lut
26
+
27
+ __all__ = [
28
+ "SUPPORTED_IDTS",
29
+ "apply_idt",
30
+ "apply_lut",
31
+ "ciede2000",
32
+ "generate_hald_clut",
33
+ "identity_lut",
34
+ "inspect_lut",
35
+ "linear_to_oklab",
36
+ "linear_to_srgb",
37
+ "load_cube",
38
+ "load_hald_clut",
39
+ "load_image",
40
+ "oklab_to_linear",
41
+ "oklab_to_srgb",
42
+ "rgb_to_lab",
43
+ "save_cube",
44
+ "save_hald_clut",
45
+ "save_image",
46
+ "solve_lut",
47
+ "srgb_to_linear",
48
+ "srgb_to_oklab",
49
+ ]
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+
7
+ from lut_match.color import SUPPORTED_IDTS
8
+ from lut_match.io import (
9
+ apply_lut,
10
+ inspect_lut,
11
+ load_cube,
12
+ load_image,
13
+ save_cube,
14
+ save_hald_clut,
15
+ save_image,
16
+ )
17
+ from lut_match.solver import solve_lut
18
+
19
+
20
+ def _build_parser() -> argparse.ArgumentParser:
21
+ parser = argparse.ArgumentParser(
22
+ prog="lut-match",
23
+ description="Fit, apply, and inspect smooth monotone .cube 3D color-grade LUTs.",
24
+ )
25
+ sub = parser.add_subparsers(dest="command", required=True)
26
+
27
+ p_fit = sub.add_parser("fit", help="Fit a .cube 3D LUT from source and reference still(s).")
28
+ p_fit.add_argument("--ref", action="append", required=True, help="Reference graded still path (repeatable).")
29
+ p_fit.add_argument("--src", action="append", required=True, help="Source still path (repeatable).")
30
+ p_fit.add_argument("-o", "--out", required=True, help="Output .cube file path.")
31
+ p_fit.add_argument("--size", type=int, default=33, choices=(17, 33, 65), help="3D LUT grid size.")
32
+ p_fit.add_argument("--strength", type=float, default=1.0, help="LUT strength in [0, 1].")
33
+ p_fit.add_argument("--skin-protect", type=float, default=0.5, help="Skin-tone protection in [0, 1].")
34
+ p_fit.add_argument("--shadow-lift", type=float, default=0.0, help="Shadow lift adjustment.")
35
+ p_fit.add_argument("--highlight-rolloff", type=float, default=0.0, help="Highlight rolloff adjustment.")
36
+ p_fit.add_argument("--smoothness", type=float, default=0.35, help="3D lattice smoothing factor.")
37
+ p_fit.add_argument(
38
+ "--mode",
39
+ default="balanced",
40
+ choices=("balanced", "creative"),
41
+ help="Transfer mode: 'balanced' (Empirical-Bayes) or 'creative' (expressive single-still).",
42
+ )
43
+ p_fit.add_argument("--idt", default="srgb", choices=SUPPORTED_IDTS, help="Source input device transform.")
44
+ p_fit.add_argument("--hald", default=None, help="Optional Level-8 HaldCLUT PNG output path.")
45
+ p_fit.add_argument("--title", default="lut-match", help="TITLE metadata written to .cube.")
46
+
47
+ p_apply = sub.add_parser("apply", help="Apply a .cube 3D LUT to an image via tetrahedral interpolation.")
48
+ p_apply.add_argument("--lut", required=True, help="Input .cube LUT path.")
49
+ p_apply.add_argument("--in", dest="inp", required=True, help="Input image path.")
50
+ p_apply.add_argument("--out", required=True, help="Output graded image path.")
51
+
52
+ p_inspect = sub.add_parser("inspect", help="Inspect structural quality metrics of a .cube LUT.")
53
+ p_inspect.add_argument("--lut", required=True, help="Input .cube LUT path.")
54
+ p_inspect.add_argument("--json", action="store_true", help="Emit JSON output.")
55
+
56
+ return parser
57
+
58
+
59
+ def main(argv: list[str] | None = None) -> int:
60
+ parser = _build_parser()
61
+ args = parser.parse_args(argv)
62
+
63
+ try:
64
+ if args.command == "fit":
65
+ src_imgs = [load_image(p) for p in args.src]
66
+ src_arg = src_imgs[0] if len(src_imgs) == 1 else src_imgs
67
+ ref_imgs = [load_image(p) for p in args.ref]
68
+ lut = solve_lut(
69
+ src_rgb=src_arg,
70
+ ref_rgbs=ref_imgs,
71
+ size=args.size,
72
+ strength=args.strength,
73
+ skin_protect=args.skin_protect,
74
+ shadow_lift=args.shadow_lift,
75
+ highlight_rolloff=args.highlight_rolloff,
76
+ smoothness=args.smoothness,
77
+ idt=args.idt,
78
+ mode=args.mode,
79
+ )
80
+ save_cube(lut, args.out, title=args.title)
81
+ if args.hald:
82
+ save_hald_clut(lut, args.hald)
83
+ return 0
84
+
85
+ if args.command == "apply":
86
+ lut, _ = load_cube(args.lut)
87
+ img = load_image(args.inp)
88
+ graded = apply_lut(img, lut)
89
+ save_image(graded, args.out)
90
+ return 0
91
+
92
+ if args.command == "inspect":
93
+ lut, meta = load_cube(args.lut)
94
+ metrics = inspect_lut(lut)
95
+ payload = {"size": meta["size"], "title": meta["title"], **metrics}
96
+ if args.json:
97
+ print(json.dumps(payload, indent=2))
98
+ else:
99
+ print(f"Title: {payload['title']} (size {payload['size']}^3)")
100
+ print(f"Inversions: {payload['inversion_count']} ({payload['inversion_rate'] * 100.0:.4f}%)")
101
+ print(f"Laplacian roughness: {payload['laplacian_roughness']:.6f}")
102
+ print(f"Max step: {payload['max_step']:.6f}")
103
+ print(f"Clipping fraction: {payload['clipping_fraction'] * 100.0:.2f}%")
104
+ print(f"Skin hue shift: {payload['skin_hue_shift_deg']:.3f} deg")
105
+ return 0
106
+ except (FileNotFoundError, ValueError) as exc:
107
+ print(f"error: {exc}", file=sys.stderr)
108
+ return 2
109
+
110
+ return 1
111
+
112
+
113
+ if __name__ == "__main__":
114
+ raise SystemExit(main())
@@ -0,0 +1,303 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ SUPPORTED_IDTS = ("srgb", "rec709", "apple-log", "slog3", "vlog", "clog3")
6
+
7
+ _M_SRGB_TO_LMS = np.array(
8
+ [
9
+ [0.4122214708, 0.5363325363, 0.0514459929],
10
+ [0.2119034982, 0.6806995451, 0.1073969566],
11
+ [0.0883024619, 0.2817188376, 0.6299787005],
12
+ ],
13
+ dtype=np.float64,
14
+ )
15
+ _M_LMS_TO_SRGB = np.linalg.inv(_M_SRGB_TO_LMS)
16
+
17
+ _M_LMS_TO_OKLAB = np.array(
18
+ [
19
+ [0.2104542553, 0.7936177850, -0.0040720468],
20
+ [1.9779984951, -2.4285922050, 0.4505937099],
21
+ [0.0259040371, 0.7827717662, -0.8086757660],
22
+ ],
23
+ dtype=np.float64,
24
+ )
25
+ _M_OKLAB_TO_LMS = np.linalg.inv(_M_LMS_TO_OKLAB)
26
+
27
+ _M_SRGB_TO_XYZ = np.array(
28
+ [
29
+ [0.4124564, 0.3575761, 0.1804375],
30
+ [0.2126729, 0.7151522, 0.0721750],
31
+ [0.0193339, 0.1191920, 0.9503041],
32
+ ],
33
+ dtype=np.float64,
34
+ )
35
+ _D65_XYZ = np.array([0.95047, 1.00000, 1.08883], dtype=np.float64)
36
+
37
+
38
+ def _npm_from_xy(
39
+ rx: float,
40
+ ry: float,
41
+ gx: float,
42
+ gy: float,
43
+ bx: float,
44
+ by: float,
45
+ wx: float = 0.3127,
46
+ wy: float = 0.3290,
47
+ ) -> np.ndarray:
48
+ """Compute Normalized Primary Matrix mapping linear RGB to CIE XYZ."""
49
+ primaries = np.array(
50
+ [
51
+ [rx / ry, gx / gy, bx / by],
52
+ [1.0, 1.0, 1.0],
53
+ [(1.0 - rx - ry) / ry, (1.0 - gx - gy) / gy, (1.0 - bx - by) / by],
54
+ ],
55
+ dtype=np.float64,
56
+ )
57
+ white_xyz = np.array([wx / wy, 1.0, (1.0 - wx - wy) / wy], dtype=np.float64)
58
+ scales = np.linalg.solve(primaries, white_xyz)
59
+ return primaries * scales[None, :]
60
+
61
+
62
+ _NPM_REC709 = _npm_from_xy(0.64, 0.33, 0.30, 0.60, 0.15, 0.06)
63
+ _INV_NPM_REC709 = np.linalg.inv(_NPM_REC709)
64
+
65
+ _M_REC2020_TO_REC709 = _INV_NPM_REC709 @ _npm_from_xy(0.708, 0.292, 0.170, 0.797, 0.131, 0.046)
66
+ _M_SGAMUT3CINE_TO_REC709 = _INV_NPM_REC709 @ _npm_from_xy(0.766, 0.275, 0.225, 0.800, 0.089, -0.087)
67
+ _M_VGAMUT_TO_REC709 = np.array(
68
+ [
69
+ [1.806576, -0.695697, -0.110879],
70
+ [-0.170090, 1.305955, -0.135865],
71
+ [-0.025206, -0.154468, 1.179674],
72
+ ],
73
+ dtype=np.float64,
74
+ )
75
+ _M_CGAMUT_TO_REC709 = _INV_NPM_REC709 @ _npm_from_xy(0.740, 0.270, 0.170, 1.140, 0.080, -0.100)
76
+
77
+
78
+ def srgb_to_linear(rgb: np.ndarray) -> np.ndarray:
79
+ x = np.asarray(rgb, dtype=np.float64)
80
+ return np.where(
81
+ x <= 0.04045,
82
+ x / 12.92,
83
+ np.power((np.maximum(x, 0.04045) + 0.055) / 1.055, 2.4),
84
+ )
85
+
86
+
87
+ def linear_to_srgb(rgb: np.ndarray) -> np.ndarray:
88
+ x = np.asarray(rgb, dtype=np.float64)
89
+ return np.where(
90
+ x <= 0.0031308,
91
+ x * 12.92,
92
+ 1.055 * np.power(np.maximum(x, 0.0031308), 1.0 / 2.4) - 0.055,
93
+ )
94
+
95
+
96
+ def linear_to_oklab(rgb: np.ndarray) -> np.ndarray:
97
+ x = np.asarray(rgb, dtype=np.float64)
98
+ lms = x @ _M_SRGB_TO_LMS.T
99
+ lms_cbrt = np.cbrt(lms)
100
+ return lms_cbrt @ _M_LMS_TO_OKLAB.T
101
+
102
+
103
+ def oklab_to_linear(lab: np.ndarray) -> np.ndarray:
104
+ x = np.asarray(lab, dtype=np.float64)
105
+ lms_cbrt = x @ _M_OKLAB_TO_LMS.T
106
+ lms = lms_cbrt * lms_cbrt * lms_cbrt
107
+ return lms @ _M_LMS_TO_SRGB.T
108
+
109
+
110
+ def srgb_to_oklab(rgb: np.ndarray) -> np.ndarray:
111
+ return linear_to_oklab(srgb_to_linear(rgb))
112
+
113
+
114
+ def oklab_to_srgb(lab: np.ndarray) -> np.ndarray:
115
+ return linear_to_srgb(oklab_to_linear(lab))
116
+
117
+
118
+ def _rec709_to_linear(rgb: np.ndarray) -> np.ndarray:
119
+ x = np.asarray(rgb, dtype=np.float64)
120
+ alpha = 1.09929682680944
121
+ cut = 0.0812428582986315
122
+ return np.where(
123
+ x < cut,
124
+ x / 4.5,
125
+ np.power((np.maximum(x, cut) + (alpha - 1.0)) / alpha, 1.0 / 0.45),
126
+ )
127
+
128
+
129
+ def _apple_log_to_linear(rgb: np.ndarray) -> np.ndarray:
130
+ p = np.asarray(rgb, dtype=np.float64)
131
+ r_0 = -0.05641088
132
+ r_t = 0.01
133
+ c = 47.28711236
134
+ beta = 0.00964052
135
+ gamma = 0.08550479
136
+ delta = 0.69336945
137
+ p_t = c * (r_t - r_0) ** 2
138
+ lin = np.where(
139
+ p >= p_t,
140
+ np.power(2.0, (p - delta) / gamma) - beta,
141
+ np.where(p > 0.0, np.sqrt(np.maximum(p, 0.0) / c) + r_0, r_0),
142
+ )
143
+ return lin @ _M_REC2020_TO_REC709.T
144
+
145
+
146
+ def _slog3_to_linear(rgb: np.ndarray) -> np.ndarray:
147
+ x = np.asarray(rgb, dtype=np.float64)
148
+ t = x * 1023.0
149
+ cut = 171.2102946929
150
+ lin = np.where(
151
+ t >= cut,
152
+ np.power(10.0, (t - 420.0) / 261.5) * 0.19 - 0.01,
153
+ (t - 95.0) * 0.01125 / (cut - 95.0),
154
+ )
155
+ return lin @ _M_SGAMUT3CINE_TO_REC709.T
156
+
157
+
158
+ def _vlog_to_linear(rgb: np.ndarray) -> np.ndarray:
159
+ x = np.asarray(rgb, dtype=np.float64)
160
+ lin = np.where(
161
+ x >= 0.181,
162
+ np.power(10.0, (x - 0.598206) / 0.241514) - 0.00873,
163
+ (x - 0.125) / 5.6,
164
+ )
165
+ return lin @ _M_VGAMUT_TO_REC709.T
166
+
167
+
168
+ def _clog3_to_linear(rgb: np.ndarray) -> np.ndarray:
169
+ y = np.asarray(rgb, dtype=np.float64)
170
+ lin = np.where(
171
+ y >= 0.15277891,
172
+ (np.power(10.0, (y - 0.12240537) / 0.36726845) - 1.0) / 14.98325,
173
+ np.where(
174
+ y <= 0.09746547,
175
+ -(np.power(10.0, (0.12783901 - y) / 0.36726845) - 1.0) / 14.98325,
176
+ (y - 0.12512219) / 1.9754798,
177
+ ),
178
+ )
179
+ return lin @ _M_CGAMUT_TO_REC709.T
180
+
181
+
182
+ def _tone_map_scene_to_display(lin_rgb: np.ndarray) -> np.ndarray:
183
+ """Smooth photographic highlight rolloff preserving 18% mid-gray."""
184
+ x = np.maximum(lin_rgb, 0.0)
185
+ # Rational filmic rolloff calibrated so scene 0.18 -> ~0.18 display linear and inf -> 1.0
186
+ a = 1.0
187
+ b = 0.85
188
+ mapped = (x * (a + 0.12 * x)) / (x * (b + 0.12 * x) + 0.95)
189
+ return np.clip(mapped, 0.0, 1.0)
190
+
191
+
192
+ def apply_idt(rgb: np.ndarray, idt: str = "srgb") -> np.ndarray:
193
+ """Convert encoded image RGB from the specified IDT into working sRGB [0, 1]."""
194
+ key = idt.lower().strip()
195
+ if key not in SUPPORTED_IDTS:
196
+ raise ValueError(f"Unsupported IDT '{idt}'. Expected one of: {', '.join(SUPPORTED_IDTS)}")
197
+ x = np.asarray(rgb, dtype=np.float64)
198
+ if key == "srgb":
199
+ return np.clip(x, 0.0, 1.0)
200
+ if key == "rec709":
201
+ return np.clip(linear_to_srgb(np.clip(_rec709_to_linear(x), 0.0, 1.0)), 0.0, 1.0)
202
+ if key == "apple-log":
203
+ lin = _apple_log_to_linear(x)
204
+ elif key == "slog3":
205
+ lin = _slog3_to_linear(x)
206
+ elif key == "vlog":
207
+ lin = _vlog_to_linear(x)
208
+ else:
209
+ lin = _clog3_to_linear(x)
210
+ return np.clip(linear_to_srgb(_tone_map_scene_to_display(lin)), 0.0, 1.0)
211
+
212
+
213
+ def rgb_to_lab(rgb: np.ndarray) -> np.ndarray:
214
+ """Convert sRGB [0, 1] to CIE L*a*b* (D65)."""
215
+ lin = srgb_to_linear(np.clip(rgb, 0.0, 1.0))
216
+ xyz = lin @ _M_SRGB_TO_XYZ.T
217
+ scaled = xyz / _D65_XYZ
218
+ eps = (6.0 / 29.0) ** 3
219
+ kappa_div = 1.0 / (3.0 * (6.0 / 29.0) ** 2)
220
+ f = np.where(scaled > eps, np.cbrt(np.maximum(scaled, eps)), kappa_div * scaled + 4.0 / 29.0)
221
+ L = 116.0 * f[..., 1] - 16.0
222
+ a = 500.0 * (f[..., 0] - f[..., 1])
223
+ b = 200.0 * (f[..., 1] - f[..., 2])
224
+ return np.stack([L, a, b], axis=-1)
225
+
226
+
227
+ def ciede2000(
228
+ lab1: np.ndarray,
229
+ lab2: np.ndarray,
230
+ k_L: float = 1.0,
231
+ k_C: float = 1.0,
232
+ k_H: float = 1.0,
233
+ ) -> np.ndarray:
234
+ """Exact Sharma, Wu & Dalal (2005) CIEDE2000 color difference."""
235
+ l1, a1, b1 = [np.asarray(lab1[..., i], dtype=np.float64) for i in range(3)]
236
+ l2, a2, b2 = [np.asarray(lab2[..., i], dtype=np.float64) for i in range(3)]
237
+
238
+ c1 = np.hypot(a1, b1)
239
+ c2 = np.hypot(a2, b2)
240
+ c_bar = 0.5 * (c1 + c2)
241
+ c_bar7 = c_bar ** 7
242
+ pow25_7 = 25.0 ** 7
243
+ g = 0.5 * (1.0 - np.sqrt(c_bar7 / (c_bar7 + pow25_7)))
244
+
245
+ a1p = (1.0 + g) * a1
246
+ a2p = (1.0 + g) * a2
247
+ c1p = np.hypot(a1p, b1)
248
+ c2p = np.hypot(a2p, b2)
249
+
250
+ h1p = np.where((b1 == 0.0) & (a1p == 0.0), 0.0, np.degrees(np.arctan2(b1, a1p)) % 360.0)
251
+ h2p = np.where((b2 == 0.0) & (a2p == 0.0), 0.0, np.degrees(np.arctan2(b2, a2p)) % 360.0)
252
+
253
+ dlp = l2 - l1
254
+ dcp = c2p - c1p
255
+
256
+ prod_cp = c1p * c2p
257
+ h_diff = h2p - h1p
258
+ dhp = np.where(
259
+ prod_cp == 0.0,
260
+ 0.0,
261
+ np.where(
262
+ np.abs(h_diff) <= 180.0,
263
+ h_diff,
264
+ np.where(h_diff > 180.0, h_diff - 360.0, h_diff + 360.0),
265
+ ),
266
+ )
267
+ dHp = 2.0 * np.sqrt(prod_cp) * np.sin(np.radians(0.5 * dhp))
268
+
269
+ l_bar_p = 0.5 * (l1 + l2)
270
+ c_bar_p = 0.5 * (c1p + c2p)
271
+
272
+ h_sum = h1p + h2p
273
+ h_bar_p = np.where(
274
+ prod_cp == 0.0,
275
+ h_sum,
276
+ np.where(
277
+ np.abs(h1p - h2p) <= 180.0,
278
+ 0.5 * h_sum,
279
+ np.where(h_sum < 360.0, 0.5 * (h_sum + 360.0), 0.5 * (h_sum - 360.0)),
280
+ ),
281
+ )
282
+
283
+ t = (
284
+ 1.0
285
+ - 0.17 * np.cos(np.radians(h_bar_p - 30.0))
286
+ + 0.24 * np.cos(np.radians(2.0 * h_bar_p))
287
+ + 0.32 * np.cos(np.radians(3.0 * h_bar_p + 6.0))
288
+ - 0.20 * np.cos(np.radians(4.0 * h_bar_p - 63.0))
289
+ )
290
+ d_theta = 30.0 * np.exp(-(((h_bar_p - 275.0) / 25.0) ** 2))
291
+ c_bar_p7 = c_bar_p ** 7
292
+ r_c = 2.0 * np.sqrt(c_bar_p7 / (c_bar_p7 + pow25_7))
293
+
294
+ l_delta_sq = (l_bar_p - 50.0) ** 2
295
+ s_l = 1.0 + (0.015 * l_delta_sq) / np.sqrt(20.0 + l_delta_sq)
296
+ s_c = 1.0 + 0.045 * c_bar_p
297
+ s_h = 1.0 + 0.015 * c_bar_p * t
298
+ r_t = -np.sin(np.radians(2.0 * d_theta)) * r_c
299
+
300
+ term_l = dlp / (k_L * s_l)
301
+ term_c = dcp / (k_C * s_c)
302
+ term_h = dHp / (k_H * s_h)
303
+ return np.sqrt(term_l ** 2 + term_c ** 2 + term_h ** 2 + r_t * term_c * term_h)