Debian Codegraph @

node/colorjs.io/src/spaces/lab.js

raw
1 import ColorSpace from "../ColorSpace.js";
2 import { WHITES } from "../adapt.js";
3 import xyz_d50 from "./xyz-d50.js";
4
5 // κ * ε = 2^3 = 8
6 const ε = 216 / 24389; // 6^3/29^3 == (24/116)^3
7 const ε3 = 24 / 116;
8 const κ = 24389 / 27; // 29^3/3^3
9
10 let white = WHITES.D50;
11
12 export default new ColorSpace({
13 id: "lab",
14 name: "Lab",
15 coords: {
16 l: {
17 refRange: [0, 100],
18 name: "Lightness",
19 },
20 a: {
21 refRange: [-125, 125],
22 },
23 b: {
24 refRange: [-125, 125],
25 },
26 },
27
28 // Assuming XYZ is relative to D50, convert to CIE Lab
29 // from CIE standard, which now defines these as a rational fraction
30 white,
31
32 base: xyz_d50,
33 // Convert D50-adapted XYX to Lab
34 // CIE 15.3:2004 section 8.2.1.1
35 fromBase (XYZ) {
36 // XYZ scaled relative to reference white
37 let xyz = XYZ.map((value, i) => value / white[i]);
38 let f = xyz.map(value => (value > ε ? Math.cbrt(value) : (κ * value + 16) / 116));
39
40 let L = 116 * f[1] - 16;
41 let a = 500 * (f[0] - f[1]);
42 let b = 200 * (f[1] - f[2]);
43
44 return [L, a, b];
45 },
46 // Convert Lab to D50-adapted XYZ
47 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
48 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
49 toBase (Lab) {
50 // compute f, starting with the luminance-related term
51 let [L, a, b] = Lab;
52 let f = [];
53 f[1] = (L + 16) / 116;
54 f[0] = a / 500 + f[1];
55 f[2] = f[1] - b / 200;
56
57 // compute xyz
58 // prettier-ignore
59 let xyz = [
60 f[0] > ε3 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ,
61 Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ,
62 f[2] > ε3 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ,
63 ];
64
65 // Compute XYZ by scaling xyz by reference white
66 return xyz.map((value, i) => value * white[i]);
67 },
68
69 formats: {
70 lab: {
71 coords: [
72 "<percentage> | <number>",
73 "<number> | <percentage>",
74 "<number> | <percentage>",
75 ],
76 },
77 },
78 });