summaryrefslogtreecommitdiffstats
path: root/src/color.rs
blob: 5d50aa14ec6268365ab2ebacd86f43565183159e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//! Colors and color spaces.

pub mod order;
pub mod source;

use crate::metric::kd::{Cartesian, CartesianMetric};
use crate::metric::{Metric, SquaredDistance};

use image::Rgb;

use std::ops::Index;

/// An 8-bit RGB color.
pub type Rgb8 = Rgb<u8>;

/// A [color space](https://en.wikipedia.org/wiki/Color_space).
pub trait ColorSpace: Copy + From<Rgb8> + CartesianMetric {
    /// Compute the average of the given colors.
    fn average<I: IntoIterator<Item = Self>>(colors: I) -> Self;
}

/// [sRGB](https://en.wikipedia.org/wiki/SRGB) space.
#[derive(Clone, Copy, Debug)]
pub struct RgbSpace([f64; 3]);

impl Index<usize> for RgbSpace {
    type Output = f64;

    fn index(&self, i: usize) -> &f64 {
        &self.0[i]
    }
}

impl From<Rgb8> for RgbSpace {
    fn from(rgb8: Rgb8) -> Self {
        Self([
            (rgb8[0] as f64) / 255.0,
            (rgb8[1] as f64) / 255.0,
            (rgb8[2] as f64) / 255.0,
        ])
    }
}

impl Metric<[f64]> for RgbSpace {
    type Distance = SquaredDistance;

    fn distance(&self, other: &[f64]) -> Self::Distance {
        self.0.distance(other)
    }
}

impl Metric for RgbSpace {
    type Distance = SquaredDistance;

    fn distance(&self, other: &Self) -> Self::Distance {
        self.0.distance(&other.0)
    }
}

impl Cartesian for RgbSpace {
    fn dimensions(&self) -> usize {
        self.0.dimensions()
    }

    fn coordinate(&self, i: usize) -> f64 {
        self.0.coordinate(i)
    }
}

impl ColorSpace for RgbSpace {
    fn average<I: IntoIterator<Item = Self>>(colors: I) -> Self {
        let mut sum = [0.0, 0.0, 0.0];
        let mut len: usize = 0;
        for color in colors.into_iter() {
            for i in 0..3 {
                sum[i] += color[i];
            }
            len += 1;
        }
        for s in &mut sum {
            *s /= len as f64;
        }
        Self(sum)
    }
}

/// [CIE XYZ](https://en.wikipedia.org/wiki/CIE_1931_color_space) space.
#[derive(Clone, Copy, Debug)]
struct XyzSpace([f64; 3]);

impl Index<usize> for XyzSpace {
    type Output = f64;

    fn index(&self, i: usize) -> &f64 {
        &self.0[i]
    }
}

/// The inverse of the sRGB gamma function.
fn srgb_inv_gamma(t: f64) -> f64 {
    if t <= 0.040449936 {
        t / 12.92
    } else {
        ((t + 0.055) / 1.055).powf(2.4)
    }
}

impl From<Rgb8> for XyzSpace {
    fn from(rgb8: Rgb8) -> Self {
        let rgb = RgbSpace::from(rgb8);

        let r = srgb_inv_gamma(rgb[0]);
        let g = srgb_inv_gamma(rgb[1]);
        let b = srgb_inv_gamma(rgb[2]);

        Self([
            0.4123808838268995 * r + 0.3575728355732478 * g + 0.1804522977447919 * b,
            0.2126198631048975 * r + 0.7151387878413206 * g + 0.0721499433963131 * b,
            0.0193434956789248 * r + 0.1192121694056356 * g + 0.9505065664127130 * b,
        ])
    }
}

/// CIE D50 [white point](https://en.wikipedia.org/wiki/Standard_illuminant).
const WHITE: XyzSpace = XyzSpace([0.9504060171449392, 0.9999085943425312, 1.089062231497274]);

/// CIE L\*a\*b\* (and L\*u\*v\*) gamma
fn lab_gamma(t: f64) -> f64 {
    if t > 216.0 / 24389.0 {
        t.cbrt()
    } else {
        841.0 * t / 108.0 + 4.0 / 29.0
    }
}

/// [CIE L\*a\*b\*](https://en.wikipedia.org/wiki/CIELAB_color_space) space.
#[derive(Clone, Copy, Debug)]
pub struct LabSpace([f64; 3]);

impl Index<usize> for LabSpace {
    type Output = f64;

    fn index(&self, i: usize) -> &f64 {
        &self.0[i]
    }
}

impl From<Rgb8> for LabSpace {
    fn from(rgb8: Rgb8) -> Self {
        let xyz = XyzSpace::from(rgb8);

        let x = lab_gamma(xyz[0] / WHITE[0]);
        let y = lab_gamma(xyz[1] / WHITE[1]);
        let z = lab_gamma(xyz[2] / WHITE[2]);

        let l = 116.0 * y - 16.0;
        let a = 500.0 * (x - y);
        let b = 200.0 * (y - z);

        Self([l, a, b])
    }
}

impl Metric<[f64]> for LabSpace {
    type Distance = SquaredDistance;

    fn distance(&self, other: &[f64]) -> Self::Distance {
        self.0.distance(other)
    }
}

impl Metric for LabSpace {
    type Distance = SquaredDistance;

    fn distance(&self, other: &Self) -> Self::Distance {
        self.0.distance(&other.0)
    }
}

impl Cartesian for LabSpace {
    fn dimensions(&self) -> usize {
        self.0.dimensions()
    }

    fn coordinate(&self, i: usize) -> f64 {
        self.0.coordinate(i)
    }
}

impl ColorSpace for LabSpace {
    fn average<I: IntoIterator<Item = Self>>(colors: I) -> Self {
        let mut sum = [0.0, 0.0, 0.0];
        let mut len: usize = 0;
        for color in colors.into_iter() {
            for i in 0..3 {
                sum[i] += color[i];
            }
            len += 1;
        }
        for s in &mut sum {
            *s /= len as f64;
        }
        Self(sum)
    }
}

/// [CIE L\*u\*v\*](https://en.wikipedia.org/wiki/CIELUV) space.
#[derive(Clone, Copy, Debug)]
pub struct LuvSpace([f64; 3]);

impl Index<usize> for LuvSpace {
    type Output = f64;

    fn index(&self, i: usize) -> &f64 {
        &self.0[i]
    }
}

/// Computes the u' and v' values for L\*u\*v\*.
fn uv_prime(xyz: &XyzSpace) -> (f64, f64) {
    let denom = xyz[0] + 15.0 * xyz[1] + 3.0 * xyz[2];
    if denom == 0.0 {
        (0.0, 0.0)
    } else {
        (4.0 * xyz[0] / denom, 9.0 * xyz[1] / denom)
    }
}

impl From<Rgb8> for LuvSpace {
    fn from(rgb8: Rgb8) -> Self {
        let xyz = XyzSpace::from(rgb8);

        let (uprime, vprime) = uv_prime(&xyz);
        let (unprime, vnprime) = uv_prime(&WHITE);

        let l = 116.0 * lab_gamma(xyz[1] / WHITE[1]) - 16.0;
        let u = 13.0 * l * (uprime - unprime);
        let v = 13.0 * l * (vprime - vnprime);

        Self([l, u, v])
    }
}

impl Metric<[f64]> for LuvSpace {
    type Distance = SquaredDistance;

    fn distance(&self, other: &[f64]) -> Self::Distance {
        self.0.distance(other)
    }
}

impl Metric for LuvSpace {
    type Distance = SquaredDistance;

    fn distance(&self, other: &Self) -> Self::Distance {
        self.0.distance(&other.0)
    }
}

impl Cartesian for LuvSpace {
    fn dimensions(&self) -> usize {
        self.0.dimensions()
    }

    fn coordinate(&self, i: usize) -> f64 {
        self.0.coordinate(i)
    }
}

impl ColorSpace for LuvSpace {
    fn average<I: IntoIterator<Item = Self>>(colors: I) -> Self {
        let mut sum = [0.0, 0.0, 0.0];
        let mut len: usize = 0;
        for color in colors.into_iter() {
            for i in 0..3 {
                sum[i] += color[i];
            }
            len += 1;
        }
        for s in &mut sum {
            *s /= len as f64;
        }
        Self(sum)
    }
}