Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/src/icc/matrix.rs

5.9 KiB, 1 run

created by r1870400018:68829, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! The matrix path: RGB to XYZ (D50) through a profile's colorants and curves, and RGB to grey
2//! through the grey curve's inverse.
3//!
4//! A matrix profile is three curves, one for each of red, green and blue, that take a device value
5//! to a linear intensity, and three XYZ colorants, the columns of the matrix that takes the
6//! intensities to XYZ in the connection space. A grey profile is one curve, `kTRC`, from the grey
7//! level to Y. Nothing here interpolates a table; a profile whose colour is held in a lattice is
8//! the lookup-table path, and is read, not evaluated, by [`crate::icc::read`].
9//!
10//! # RGB to grey
11//!
12//! The Y of the RGB colour, found through the source's matrix, is the luminance the destination
13//! grey must reproduce, so the grey level is the destination curve's inverse at that Y. This is the
14//! conversion LittleCMS makes for an RGB source and a grey profile with an XYZ connection space.
15//!
16//! # What is refused
17//!
18//! A grey profile with a Lab connection space is refused by name, since its `kTRC` takes a level to
19//! L* rather than to Y and this path makes no conversion between the two; so is an RGB profile with
20//! a Lab one, a profile lacking a colorant or a curve, and a curve that falls from its start to its
21//! end.
22//!
23//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
24//! Anthropic Claude
25
26use crate::icc::read::{
27 Curve,
28 Profile,
29 Space,
30};
31
32use oxedyne_fe2o3_core::prelude::*;
33
34pub type M3 = [[f64; 3]; 3];
35
36/// The product `a * b`.
37pub fn mul(a: &M3, b: &M3) -> M3 {
38 let mut m = [[0.0; 3]; 3];
39 for i in 0..3 {
40 for j in 0..3 {
41 m[i][j] = (0..3).map(|k| a[i][k] * b[k][j]).sum();
42 }
43 }
44 m
45}
46
47/// The product `a * v`.
48pub fn mul_v(a: &M3, v: [f64; 3]) -> [f64; 3] {
49 let mut r = [0.0; 3];
50 for i in 0..3 {
51 r[i] = a[i][0] * v[0] + a[i][1] * v[1] + a[i][2] * v[2];
52 }
53 r
54}
55
56/// The inverse of `a`, by its adjugate; a matrix of determinant near zero is refused.
57pub fn inv(a: &M3) -> Outcome<M3> {
58 let c = [
59 [
60 a[1][1] * a[2][2] - a[1][2] * a[2][1],
61 a[0][2] * a[2][1] - a[0][1] * a[2][2],
62 a[0][1] * a[1][2] - a[0][2] * a[1][1],
63 ],
64 [
65 a[1][2] * a[2][0] - a[1][0] * a[2][2],
66 a[0][0] * a[2][2] - a[0][2] * a[2][0],
67 a[0][2] * a[1][0] - a[0][0] * a[1][2],
68 ],
69 [
70 a[1][0] * a[2][1] - a[1][1] * a[2][0],
71 a[0][1] * a[2][0] - a[0][0] * a[2][1],
72 a[0][0] * a[1][1] - a[0][1] * a[1][0],
73 ],
74 ];
75 let det = a[0][0] * c[0][0] + a[0][1] * c[1][0] + a[0][2] * c[2][0];
76 if det.abs() < 1e-12 {
77 return Err(err!("A colour matrix of determinant {} has no inverse.", det;
78 Invalid, Input, Numeric));
79 }
80 let mut m = c;
81 for row in m.iter_mut() {
82 for v in row.iter_mut() {
83 *v /= det;
84 }
85 }
86 Ok(m)
87}
88
89// An RGB space: the matrix from linear RGB to XYZ (D50), and the curve of each channel.
90#[derive(Clone, Debug)]
91pub struct RgbMatrix {
92 pub m: M3, // row major, the colorants as columns
93 pub trc: [Curve; 3],
94}
95
96impl RgbMatrix {
97 /// The matrix path of an RGB profile with an XYZ connection space.
98 pub fn read(p: &Profile) -> Outcome<Self> {
99 if p.head.space != Space::Rgb || p.head.pcs != Space::Xyz {
100 return Err(err!(
101 "Profile '{}' is a {:?} profile with a {:?} connection space, and the matrix path \
102 is of an RGB profile with an XYZ one.", p.name, p.head.space, p.head.pcs;
103 Invalid, Input, Mismatch));
104 }
105 let mut m = [[0.0; 3]; 3];
106 let mut trc = [Curve::Identity, Curve::Identity, Curve::Identity];
107 for i in 0..3 {
108 let (xyz, sig) = (p.cols[i], ["rXYZ", "gXYZ", "bXYZ"][i]);
109 let col = res!(xyz.ok_or_else(|| err!(
110 "Profile '{}' has no '{}' tag, so it has no matrix path.", p.name, sig;
111 Invalid, Input, Missing)));
112 for j in 0..3 {
113 m[j][i] = col[j];
114 }
115 let (curve, sig) = (&p.trcs[i], ["rTRC", "gTRC", "bTRC"][i]);
116 let curve = res!(curve.as_ref().ok_or_else(|| err!(
117 "Profile '{}' has no '{}' tag, so it has no matrix path.", p.name, sig;
118 Invalid, Input, Missing)));
119 if !curve.rises() {
120 return Err(err!(
121 "Tag '{}' of profile '{}' falls from its start to its end, and a curve that \
122 falls cannot be inverted.", sig, p.name; Invalid, Input, Invalid));
123 }
124 trc[i] = curve.clone();
125 }
126 Ok(Self { m, trc })
127 }
128
129 /// The linear intensities of a device colour.
130 pub fn linear(&self, rgb: [f64; 3]) -> [f64; 3] {
131 [self.trc[0].eval(rgb[0]), self.trc[1].eval(rgb[1]), self.trc[2].eval(rgb[2])]
132 }
133
134 /// The XYZ (D50) of a device colour.
135 pub fn xyz(&self, rgb: [f64; 3]) -> [f64; 3] {
136 mul_v(&self.m, self.linear(rgb))
137 }
138
139 /// The Y of a device colour, the luminance a grey must match.
140 pub fn y(&self, rgb: [f64; 3]) -> f64 {
141 let lin = self.linear(rgb);
142 self.m[1][0] * lin[0] + self.m[1][1] * lin[1] + self.m[1][2] * lin[2]
143 }
144}
145
146// A grey space: the curve from the grey level to Y.
147#[derive(Clone, Debug)]
148pub struct Grey {
149 pub trc: Curve,
150}
151
152impl Grey {
153 /// The grey curve of a grey profile with an XYZ connection space.
154 pub fn read(p: &Profile) -> Outcome<Self> {
155 if p.head.space != Space::Gray || p.head.pcs != Space::Xyz {
156 return Err(err!(
157 "Profile '{}' is a {:?} profile with a {:?} connection space, and the grey path is \
158 of a grey profile with an XYZ one.", p.name, p.head.space, p.head.pcs;
159 Invalid, Input, Mismatch));
160 }
161 let trc = res!(p.ktrc.as_ref().ok_or_else(|| err!(
162 "Profile '{}' has no 'kTRC' tag, so it has no grey curve.", p.name;
163 Invalid, Input, Missing)));
164 if !trc.rises() {
165 return Err(err!(
166 "Tag 'kTRC' of profile '{}' falls from its start to its end, and a curve that \
167 falls cannot be inverted.", p.name; Invalid, Input, Invalid));
168 }
169 Ok(Self { trc: trc.clone() })
170 }
171
172 /// The Y of a grey level.
173 pub fn y(&self, g: f64) -> f64 {
174 self.trc.eval(g)
175 }
176
177 /// The grey level whose Y is `y`.
178 pub fn level(&self, y: f64) -> f64 {
179 self.trc.inverse(y)
180 }
181}
182
183/// The grey level a destination grey space gives the colour `rgb` of a source RGB space.
184pub fn rgb_to_grey(src: &RgbMatrix, dst: &Grey, rgb: [f64; 3]) -> f64 {
185 dst.level(src.y(rgb))
186}