use crate::image::{D50_WHITE, Gamma, RgbWorkingSpace};
const EPSILON: f64 = 216.0 / 24389.0;
const KAPPA: f64 = 24389.0 / 27.0;
fn clip(x: f64) -> f64 {
if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }
}
pub fn srgb_linearize(x: f64) -> f64 {
if x <= 0.04045 { x / 12.92 } else { ((x + 0.055) / 1.055).powf(2.4) }
}
pub fn srgb_delinearize(x: f64) -> f64 {
if x <= 0.0031308 { 12.92 * x } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 }
}
fn f(t: f64) -> f64 {
if t > EPSILON { t.cbrt() } else { (KAPPA * t + 16.0) / 116.0 }
}
fn g(t: f64) -> f64 {
let cube = t * t * t;
if cube > EPSILON { cube } else { (116.0 * t - 16.0) / KAPPA }
}
#[derive(Clone, PartialEq, Debug)]
pub struct ColorTransform {
gamma: Gamma,
to_xyz: [[f64; 3]; 3],
from_xyz: [[f64; 3]; 3],
}
impl ColorTransform {
pub fn new(space: &RgbWorkingSpace) -> Option<Self> {
let [x, y, luminance] = [space.x, space.y, space.luminance];
let mut to_xyz = [[0.0f64; 3]; 3];
for i in 0..3 {
if y[i] == 0.0 {
return None;
}
to_xyz[0][i] = luminance[i] * x[i] / y[i];
to_xyz[1][i] = luminance[i];
to_xyz[2][i] = luminance[i] * (1.0 - x[i] - y[i]) / y[i];
}
let from_xyz = invert(&to_xyz)?;
Some(ColorTransform { gamma: space.gamma, to_xyz, from_xyz })
}
pub fn srgb() -> Self {
Self::new(&RgbWorkingSpace::srgb()).expect("sRGB is a valid working space")
}
pub fn linearize(&self, value: f64) -> f64 {
match self.gamma {
Gamma::Srgb => srgb_linearize(value),
Gamma::Exponent(exponent) => value.max(0.0).powf(exponent),
}
}
pub fn delinearize(&self, value: f64) -> f64 {
match self.gamma {
Gamma::Srgb => srgb_delinearize(value),
Gamma::Exponent(exponent) => value.max(0.0).powf(1.0 / exponent),
}
}
pub fn rgb_to_xyz_linear(&self, linear: [f64; 3]) -> [f64; 3] {
apply(&self.to_xyz, linear)
}
pub fn rgb_to_xyz(&self, rgb: [f64; 3]) -> [f64; 3] {
let linear = [self.linearize(rgb[0]), self.linearize(rgb[1]), self.linearize(rgb[2])];
apply(&self.to_xyz, linear)
}
pub fn xyz_to_rgb(&self, xyz: [f64; 3]) -> [f64; 3] {
let linear = apply(&self.from_xyz, xyz);
[
clip(self.delinearize(linear[0].max(0.0))),
clip(self.delinearize(linear[1].max(0.0))),
clip(self.delinearize(linear[2].max(0.0))),
]
}
pub fn rgb_to_lab(&self, rgb: [f64; 3]) -> [f64; 3] {
xyz_to_lab(self.rgb_to_xyz(rgb))
}
pub fn lab_to_rgb(&self, lab: [f64; 3]) -> [f64; 3] {
self.xyz_to_rgb(lab_to_xyz(lab))
}
pub fn rgb_to_gray(&self, rgb: [f64; 3]) -> f64 {
let linear = [self.linearize(rgb[0]), self.linearize(rgb[1]), self.linearize(rgb[2])];
let y = self.to_xyz[1][0] * linear[0]
+ self.to_xyz[1][1] * linear[1]
+ self.to_xyz[1][2] * linear[2];
clip(1.16 * f(y) - 0.16)
}
}
pub fn xyz_to_lab(xyz: [f64; 3]) -> [f64; 3] {
let fx = f(xyz[0] / D50_WHITE[0]);
let fy = f(xyz[1]);
let fz = f(xyz[2] / D50_WHITE[2]);
[
clip(1.16 * fy - 0.16),
clip(0.5 + (29.0 / 50.0) * (fx - fy)),
clip(0.5 + (29.0 / 50.0) * (fy - fz)),
]
}
pub fn lab_to_xyz(lab: [f64; 3]) -> [f64; 3] {
let fy = (lab[0] + 0.16) / 1.16;
let fx = fy + (50.0 / 29.0) * (lab[1] - 0.5);
let fz = fy - (50.0 / 29.0) * (lab[2] - 0.5);
[g(fx) * D50_WHITE[0], g(fy), g(fz) * D50_WHITE[2]]
}
fn apply(matrix: &[[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] {
let mut out = [0.0; 3];
for (row, slot) in matrix.iter().zip(out.iter_mut()) {
*slot = row[0] * v[0] + row[1] * v[1] + row[2] * v[2];
}
out
}
fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
let det = m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
if !det.is_finite() || det.abs() < 1e-15 {
return None;
}
let mut out = [[0.0f64; 3]; 3];
for (i, row) in out.iter_mut().enumerate() {
for (j, slot) in row.iter_mut().enumerate() {
let (a, b) = ((j + 1) % 3, (j + 2) % 3);
let (c, d) = ((i + 1) % 3, (i + 2) % 3);
*slot = (m[a][c] * m[b][d] - m[a][d] * m[b][c]) / det;
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_matrix_carries_white_to_the_reference_white() {
let transform = ColorTransform::srgb();
let white = apply(&transform.to_xyz, [1.0, 1.0, 1.0]);
for (got, want) in white.iter().zip(D50_WHITE) {
assert!((got - want).abs() < 1e-9, "white came out {white:?}, wanted {D50_WHITE:?}");
}
}
#[test]
fn the_matrix_agrees_with_an_independent_published_one() {
let transform = ColorTransform::srgb();
let reference = [
[0.4360747, 0.3850649, 0.1430804],
[0.2225045, 0.7168786, 0.0606169],
[0.0139322, 0.0971045, 0.7141733],
];
let columns = [
transform.rgb_to_xyz_linear([1.0, 0.0, 0.0]),
transform.rgb_to_xyz_linear([0.0, 1.0, 0.0]),
transform.rgb_to_xyz_linear([0.0, 0.0, 1.0]),
];
let mut worst = 0.0f64;
for i in 0..3 {
for j in 0..3 {
worst = worst.max((columns[j][i] - reference[i][j]).abs());
}
}
assert!(worst < 1e-4, "the matrix differs from the published one by {worst}");
}
#[test]
fn chromatic_colours_agree_with_an_independent_implementation() {
let transform = ColorTransform::srgb();
let reference = [
("red", [1.0, 0.0, 0.0], [0.542_902_841, 0.593_741_425, 0.702_671_220]),
("green", [0.0, 1.0, 0.0], [0.878_185_825, 0.408_031_212, 0.734_881_397]),
("blue", [0.0, 0.0, 1.0], [0.295_686_645, 0.579_225_348, 0.175_117_300]),
("mid", [0.2, 0.6, 0.35], [0.562_694_762, 0.451_611_727, 0.571_345_428]),
("yellow", [1.0, 1.0, 0.0], [0.976_069_495, 0.481_726_180, 0.770_835_430]),
];
for (name, rgb, want) in reference {
let got = transform.rgb_to_lab(rgb);
for i in 0..3 {
assert!(
(got[i] - want[i]).abs() < 1e-8,
"{name}: got {got:?}, an independent implementation gives {want:?}"
);
}
}
}
#[test]
fn the_chromatic_axes_point_the_way_they_should() {
let t = ColorTransform::srgb();
assert!(t.rgb_to_lab([1.0, 0.0, 0.0])[1] > 0.5, "red must be on the +a side");
assert!(t.rgb_to_lab([0.0, 1.0, 0.0])[1] < 0.5, "green must be on the -a side");
assert!(t.rgb_to_lab([0.0, 0.0, 1.0])[2] < 0.5, "blue must be on the -b side");
assert!(t.rgb_to_lab([1.0, 1.0, 0.0])[2] > 0.5, "yellow must be on the +b side");
}
#[test]
fn the_matrix_inverse_is_an_inverse() {
let transform = ColorTransform::srgb();
let mut product = [[0.0f64; 3]; 3];
for (i, row) in product.iter_mut().enumerate() {
for (j, slot) in row.iter_mut().enumerate() {
for k in 0..3 {
*slot += transform.to_xyz[i][k] * transform.from_xyz[k][j];
}
}
}
for (i, row) in product.iter().enumerate() {
for (j, got) in row.iter().enumerate() {
let want = if i == j { 1.0 } else { 0.0 };
assert!((got - want).abs() < 1e-12, "row {i} column {j}");
}
}
}
#[test]
fn white_and_black_land_where_they_should() {
let transform = ColorTransform::srgb();
let [l, a, b] = transform.rgb_to_lab([1.0, 1.0, 1.0]);
assert!((l - 1.0).abs() < 1e-9, "white L = {l}");
assert!((a - 0.5).abs() < 1e-9, "white a = {a}, the achromatic axis is at one half");
assert!((b - 0.5).abs() < 1e-9, "white b = {b}");
let [l, a, b] = transform.rgb_to_lab([0.0, 0.0, 0.0]);
assert!(l.abs() < 1e-9, "black L = {l}");
assert!((a - 0.5).abs() < 1e-9, "black a = {a}");
assert!((b - 0.5).abs() < 1e-9, "black b = {b}");
}
#[test]
fn rgb_round_trips_through_lab() {
let transform = ColorTransform::srgb();
let colors = [
[0.0, 0.0, 0.0],
[1.0, 1.0, 1.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[0.5, 0.5, 0.5],
[0.2, 0.7, 0.35],
[0.94, 0.11, 0.68],
[0.01, 0.02, 0.03],
];
for rgb in colors {
let lab = transform.rgb_to_lab(rgb);
let back = transform.lab_to_rgb(lab);
for i in 0..3 {
assert!(
(rgb[i] - back[i]).abs() < 1e-9,
"{rgb:?} came back {back:?} through {lab:?}"
);
}
}
}
#[test]
fn rgb_round_trips_through_xyz() {
for space in [RgbWorkingSpace::srgb(), adobe_rgb()] {
let transform = ColorTransform::new(&space).expect("valid space");
for rgb in [[0.3, 0.6, 0.9], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.77, 0.25, 0.4]] {
let back = transform.xyz_to_rgb(transform.rgb_to_xyz(rgb));
for i in 0..3 {
assert!((rgb[i] - back[i]).abs() < 1e-9, "{rgb:?} came back {back:?}");
}
}
}
}
#[test]
fn the_srgb_transfer_functions_invert_each_other() {
for i in 0..=1000 {
let x = f64::from(i) / 1000.0;
let back = srgb_delinearize(srgb_linearize(x));
assert!((x - back).abs() < 1e-12, "{x} came back {back}");
}
assert!((srgb_linearize(0.04045) - 0.0031308).abs() < 1e-7);
}
#[test]
fn the_companding_functions_invert_each_other() {
for i in 0..=1000 {
let t = f64::from(i) / 1000.0;
assert!((g(f(t)) - t).abs() < 1e-12, "t = {t}");
}
for t in [EPSILON * 0.5, EPSILON, EPSILON * 1.5] {
assert!((g(f(t)) - t).abs() < 1e-12, "t = {t}");
}
}
#[test]
fn grayscale_is_the_lightness_component() {
let transform = ColorTransform::srgb();
for rgb in
[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [0.25, 0.5, 0.75], [0.9, 0.1, 0.4]]
{
let gray = transform.rgb_to_gray(rgb);
let [l, _, _] = transform.rgb_to_lab(rgb);
assert!((gray - l).abs() < 1e-12, "{rgb:?}: gray {gray}, L {l}");
}
}
#[test]
fn an_exponent_gamma_is_not_the_srgb_function() {
let srgb = ColorTransform::srgb();
let exponent = ColorTransform::new(&adobe_rgb()).expect("valid");
let difference = (srgb.linearize(0.5) - exponent.linearize(0.5)).abs();
assert!(difference > 1e-3, "the two transfer functions differ by only {difference}");
}
#[test]
fn degenerate_primaries_have_no_transform() {
let mut space = RgbWorkingSpace::srgb();
space.x = [0.3, 0.3, 0.3];
space.y = [0.3, 0.3, 0.3];
assert!(ColorTransform::new(&space).is_none());
}
fn adobe_rgb() -> RgbWorkingSpace {
RgbWorkingSpace::new(
Gamma::Exponent(2.2),
[0.648431, 0.230154, 0.155886],
[0.330856, 0.701572, 0.066044],
Some("Adobe RGB (1998)".into()),
)
.expect("valid primaries")
}
}