Debian Codegraph @

src/lab.rs

raw symbols SCIP
1 #[cfg(not(feature = "std"))]
2 use num_traits::float::Float;
3
4 // Constants for D65 white point (normalized to Y=1.0)
5 const D65_X: f32 = 0.95047;
6 const D65_Y: f32 = 1.0;
7 const D65_Z: f32 = 1.08883;
8
9 const DELTA: f32 = 6.0 / 29.0;
10 const DELTA2: f32 = DELTA * DELTA;
11 const DELTA3: f32 = DELTA2 * DELTA;
12
13 // Helper function for LAB to XYZ conversion
14 const fn lab_to_xyz(l: f32, a: f32, b: f32) -> [f32; 3] {
15 let fy = (l + 16.0) / 116.0;
16 let fx = fy + a / 500.0;
17 let fz = fy - b / 200.0;
18
19 const fn lab_f(t: f32) -> f32 {
20 if t > DELTA {
21 t * t * t
22 } else {
23 (t - 16.0 / 116.0) * 3.0 * DELTA2
24 }
25 }
26
27 let x = D65_X * lab_f(fx);
28 let y = D65_Y * lab_f(fy);
29 let z = D65_Z * lab_f(fz);
30 [x, y, z]
31 }
32
33 #[allow(clippy::excessive_precision)]
34 // Helper function for XYZ to linear RGB conversion
35 const fn xyz_to_linear_rgb(x: f32, y: f32, z: f32) -> [f32; 3] {
36 // sRGB matrix (D65)
37 let r = 3.2404542 * x - 1.5371385 * y - 0.4985314 * z;
38 let g = -0.9692660 * x + 1.8760108 * y + 0.0415560 * z;
39 let b = 0.0556434 * x - 0.2040259 * y + 1.0572252 * z;
40 [r, g, b]
41 }
42
43 #[allow(clippy::excessive_precision)]
44 // Helper function for linear RGB to XYZ conversion
45 const fn linear_rgb_to_xyz(r: f32, g: f32, b: f32) -> [f32; 3] {
46 // Inverse sRGB matrix (D65)
47 let x = 0.4124564 * r + 0.3575761 * g + 0.1804375 * b;
48 let y = 0.2126729 * r + 0.7151522 * g + 0.0721750 * b;
49 let z = 0.0193339 * r + 0.1191920 * g + 0.9503041 * b;
50 [x, y, z]
51 }
52
53 // Helper function for XYZ to LAB conversion
54 fn xyz_to_lab(x: f32, y: f32, z: f32) -> [f32; 3] {
55 let lab_f = |t: f32| -> f32 {
56 if t > DELTA3 {
57 t.cbrt()
58 } else {
59 (t / (3.0 * DELTA2)) + (4.0 / 29.0)
60 }
61 };
62
63 let fx = lab_f(x / D65_X);
64 let fy = lab_f(y / D65_Y);
65 let fz = lab_f(z / D65_Z);
66
67 let l = 116.0 * fy - 16.0;
68 let a = 500.0 * (fx - fy);
69 let b = 200.0 * (fy - fz);
70
71 [l, a, b]
72 }
73
74 // Convert CIELAB (L*a*b*) to linear RGB
75 // L: [0, 100], a: [-128, 127], b: [-128, 127]
76 // Returns RGB in [0, 1] range
77 pub(crate) const fn lab_to_linear_rgb(l: f32, a: f32, b: f32) -> [f32; 3] {
78 let [x, y, z] = lab_to_xyz(l, a, b);
79 xyz_to_linear_rgb(x, y, z)
80 }
81
82 // Convert linear RGB to CIELAB (L*a*b*)
83 // RGB components in [0, 1] range
84 // Returns [L, a, b] with L: [0, 100], a: [-128, 127], b: [-128, 127]
85 pub(crate) fn linear_rgb_to_lab(r: f32, g: f32, b: f32) -> [f32; 3] {
86 let [x, y, z] = linear_rgb_to_xyz(r, g, b);
87 xyz_to_lab(x, y, z)
88 }