iris-lib 0.1.0

A library that creates color palettes from images using the median cut algorithm.
Documentation
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::utils::mean;
use crate::color::{Color, ColorChannel};

#[cfg(feature = "image")]
extern crate image;
#[cfg(feature = "image")]
use image::GenericImageView;

/// Struct holding an `Vec<Color>`.
/// Implements helpful functions for the median cut algorithm.
///
#[derive(Debug, PartialEq)]
pub struct ColorBucket {
    colors: Vec<Color>,
}

impl ColorBucket {
    /// Creates a `ColorBucket` based on the colors passed. Returns `None` if passed an empty vector.
    ///
    /// # Arguments
    ///
    /// * `colors` - Color vector from which the mean color is created.
    ///
    /// # Examples
    ///
    /// ```
    /// use iris_lib::color::Color;
    /// use iris_lib::color_bucket::ColorBucket;
    ///
    /// let data = vec![Color { r: 15, g: 131, b: 0, a: 255 }, Color { r: 221, g: 11, b: 22, a: 130 }, Color { r: 81, g: 11, b: 16, a: 0 }];
    /// let result = ColorBucket::from_pixels(data.clone()).expect("Passed empty color vector to test.");
    /// ```
    ///
    pub fn from_pixels(pixels: Vec<Color>) -> Option<Self> {
        if pixels.is_empty() {
            None
        } else {
            Some(Self { colors: pixels })
        }
    }

    #[cfg(feature = "image")]
    /// Creates a `ColorBucket` based from image files. Returns `None` if unable to load the image.
    /// 
    /// # Arguments
    ///
    /// * `image_path` - Path to the target image.
    ///
    /// # Examples
    ///
    /// ```
    /// use iris_lib::color_bucket::ColorBucket;
    ///
    /// if let Some(mut result) = ColorBucket::from_image("peppers.png") {
    ///     // ...
    /// }
    /// ```
    ///
    pub fn from_image(image_path: &str) -> Option<Self> {
        if let Ok(img) = image::open(image_path) {
            let mut colors = Vec::new();

            for p in img.pixels() {
                let color = Color {
                    r: p.2.0[0],
                    g: p.2.0[1],
                    b: p.2.0[2],
                    a: p.2.0[3]
                };

                colors.push(color);
            }

            Some (Self { colors })
        } else {
            println!("Unable to load image at: {}", image_path);
            None
        }
    }

    /// Recursively performs the median cut algorithm on self if iteration has not reached 0 yet.
    /// Creates two new buckets based on own colors. One bucket with values above and one bucket with value below the median, then performs the algorithm on them again.
    ///
    /// If iteration has reached 0 the color mean for self is pushed to the result vector.
    ///
    /// # Arguments
    ///
    /// * `iter_count` - Iteration index is used as termination criteria. Recursion stop when 0 is reached.
    /// * `result` - Vector holding color means for each bucket in the iteration.
    ///
    fn recurse(&mut self, iter_count: u8, result: &mut Vec<Color>) {
        if iter_count == 0 {
            result.push(self.color_mean())
        } else {
            let new_buckets = self.median_cut();
            if let Some(mut bucket) = new_buckets.0 {
                bucket.recurse(iter_count - 1, result);
            }
            if let Some(mut bucket) = new_buckets.1 {
                bucket.recurse(iter_count - 1, result);
            }
        }
    }

    /// Creates a color palette from own pixels.
    ///
    /// # Arguments
    ///
    /// * `iter_count` - number of iterations to be performed on the bucket.
    ///
    /// # Example
    ///
    /// ```
    /// use iris_lib::color_bucket::ColorBucket;
    /// use iris_lib::color::Color;
    ///
    /// let data = vec![Color { r: 15, g: 131, b: 0, a: 255 }, Color { r: 221, g: 11, b: 22, a: 130 }, Color { r: 81, g: 11, b: 16, a: 0 }];
    /// let mut bucket = ColorBucket::from_pixels(data.clone()).expect("Passed empty color vector to test.");
    /// let result = bucket.make_palette(3);
    /// ```
    ///
    pub fn make_palette(&mut self, iter_count: u8) -> Vec<Color> {
        let mut result = vec![];
        self.recurse(iter_count, &mut result);
        result
    }

    /// Performs the median cut on a own vector (bucket) of `Color`.
    /// Returns two `Color` vectors representing the colors above and colors below median value.
    ///
    fn median_cut(&mut self) -> (Option<ColorBucket>, Option<ColorBucket>) {
        let highest_range_channel = self.highest_range_channel();
        let median = self.color_median(highest_range_channel);
        let mut above_median = vec![];
        let mut below_median = vec![];
        for color in &self.colors {
            if color[highest_range_channel] > median {
                above_median.push(*color);
            } else {
                below_median.push(*color);
            }
        }

        (ColorBucket::from_pixels(above_median), ColorBucket::from_pixels(below_median))
    }

    /// Returns the color channel with the highest range.
    /// IMPORTANT: Ignores alpha channel!
    ///
    fn highest_range_channel(&self) -> ColorChannel {
        let ranges = self.color_ranges();
        let mut highest_range_channel = ColorChannel::R;
        let mut highest_value = ranges.r;

        if ranges.g > highest_value {
            highest_range_channel = ColorChannel::G;
            highest_value = ranges.g;
        }

        if ranges.b > highest_value {
            highest_range_channel = ColorChannel::B;
        }

        highest_range_channel
    }

    /// Returns the ranges for each color channel.
    ///
    fn color_ranges(&self) -> Color {
        // Unwrap is ok here, because `max_by_key` only returns `None` for empty vectors
        Color {
            r: self.colors.iter().max_by_key(|c| c.r).unwrap().r - self.colors.iter().min_by_key(|c| c.r).unwrap().r,
            g: self.colors.iter().max_by_key(|c| c.g).unwrap().g - self.colors.iter().min_by_key(|c| c.g).unwrap().g,
            b: self.colors.iter().max_by_key(|c| c.b).unwrap().b - self.colors.iter().min_by_key(|c| c.b).unwrap().b,
            a: self.colors.iter().max_by_key(|c| c.a).unwrap().a - self.colors.iter().min_by_key(|c| c.a).unwrap().a,
        }
    }

    /// Sort a colors for a specific channel.
    ///
    /// # Arguments
    ///
    /// * `channel` - Target channel. The sorting is performed based on this value.
    ///
    fn sort_colors(&mut self, channel: ColorChannel) {
        self.colors.sort_by_key(|x| x[channel])
    }

    /// Returns median value for a specific `ColorChannel`.
    ///
    /// # Arguments
    ///
    /// * `channel` - Target channel for which the median is calculated.
    ///
    fn color_median(&mut self, channel: ColorChannel) -> u8 {
        self.sort_colors(channel);

        let mid = self.colors.len() / 2;
        if self.colors.len() % 2 == 0 {
            let bucket = ColorBucket::from_pixels(vec![self.colors[mid - 1], self.colors[mid]]).unwrap();
            bucket.channel_mean(channel)
        } else {
            self.channel_value_by_index(mid, channel)
        }
    }

    /// Returns a color value based on the provided channel and index parameters.
    ///
    /// # Arguments
    ///
    /// * `index` - Index of the target color in the vector.
    /// * `channel` - Color channel of the searched value.
    ///
    fn channel_value_by_index(&self, index: usize, channel: ColorChannel) -> u8 {
        self.colors[index][channel]
    }

    /// Calculate the mean value for a specific color channel on own vector of `Color`.
    ///
    /// # Arguments
    ///
    /// * `channel` - Target channel for which the mean is calculated.
    ///
    ///
    fn channel_mean(&self, channel: ColorChannel) -> u8 {
        mean(self.colors.iter().map(|x| x[channel]))
    }

    /// Returns the mean color value based on own colors.
    ///
    fn color_mean(&self) -> Color {
        let r = mean(self.colors.iter().map(|c| c.r));
        let g = mean(self.colors.iter().map(|c| c.g));
        let b = mean(self.colors.iter().map(|c| c.b));
        let a = mean(self.colors.iter().map(|c| c.a));

        Color { r, g, b, a }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn from_pixels_ut() {
        let bucket = ColorBucket::from_pixels(vec![]);
        assert_eq!(bucket, None);

        let data = vec![Color { r: 15, g: 131, b: 0, a: 255 }, Color { r: 221, g: 11, b: 22, a: 130 }, Color { r: 81, g: 11, b: 16, a: 0 }];
        let bucket = ColorBucket::from_pixels(data.clone()).expect("Passed empty color vector to test.");
        assert_eq!(bucket.colors, data);
    }

    #[test]
    fn recurse_ut() {
        let pixels = vec![Color { r: 255, g: 0, b: 0, a: 255 }, Color { r: 0, g: 255, b: 0, a: 255 }];
        let mut bucket = ColorBucket::from_pixels(pixels.clone()).expect("Passed empty color vector to test.");
        let mut result = vec![];
        bucket.recurse(1, &mut result);
        assert_eq!(result, pixels);
    }

    #[test]
    fn make_palette_ut() {
        let pixels = vec![Color { r: 100, g: 120, b: 120, a: 0 }, Color { r: 150, g: 150, b: 150, a: 0 }, Color { r: 255, g: 255, b: 255, a: 0 }];
        let mut bucket = ColorBucket::from_pixels(pixels.clone()).expect("Passed empty color vector to test.");

        let colors = bucket.make_palette(3);
        let expected = vec![Color { r: 255, g: 255, b: 255, a: 0 }, Color { r: 150, g: 150, b: 150, a: 0 }, Color { r: 100, g: 120, b: 120, a: 0 }];
        assert_eq!(colors, expected);
    }

    #[test]
    pub fn sort_colors_ut() {
        let colors = generate_unsorted_colors();
        let mut bucket = ColorBucket::from_pixels(colors.clone()).expect("Passed empty color vector to test");
        bucket.sort_colors(ColorChannel::R);

        assert_eq!(bucket.colors[0], Color { r: 0, g: 2, b: 1, a: 20 });
        assert_eq!(bucket.colors[1], Color { r: 1, g: 23, b: 16, a: 20 });
        assert_eq!(bucket.colors[2], Color { r: 3, g: 4, b: 15, a: 2 });
        assert_eq!(bucket.colors[3], Color { r: 55, g: 17, b: 0, a: 118 });
    }

    #[test]
    pub fn color_median_ut() {
        let colors = generate_unsorted_colors();
        let mut bucket = ColorBucket::from_pixels(colors.clone()).expect("Passed empty color vector to test");
        let result = bucket.color_median(ColorChannel::R);
        assert_eq!(result, 2);
    }

    #[test]
    fn channel_value_by_index_ut() {
        let colors = vec![
            Color { r: 100, g: 22, b: 12, a: 0 },
            Color { r: 126, g: 175, b: 137, a: 1 },
            Color { r: 221, g: 225, b: 0, a: 113 },
            Color { r: 13, g: 226, b: 0, a: 17 },
        ];

        let bucket = ColorBucket::from_pixels(colors).expect("Passing empty color vector to test");

        assert_eq!(100, bucket.channel_value_by_index(0, ColorChannel::R));
        assert_eq!(22, bucket.channel_value_by_index(0, ColorChannel::G));
        assert_eq!(12, bucket.channel_value_by_index(0, ColorChannel::B));
        assert_eq!(0, bucket.channel_value_by_index(0, ColorChannel::A));

        assert_eq!(126, bucket.channel_value_by_index(1, ColorChannel::R));
        assert_eq!(175, bucket.channel_value_by_index(1, ColorChannel::G));
        assert_eq!(137, bucket.channel_value_by_index(1, ColorChannel::B));
        assert_eq!(1, bucket.channel_value_by_index(1, ColorChannel::A));

        assert_eq!(221, bucket.channel_value_by_index(2, ColorChannel::R));
        assert_eq!(225, bucket.channel_value_by_index(2, ColorChannel::G));
        assert_eq!(0, bucket.channel_value_by_index(2, ColorChannel::B));
        assert_eq!(113, bucket.channel_value_by_index(2, ColorChannel::A));

        assert_eq!(13, bucket.channel_value_by_index(3, ColorChannel::R));
        assert_eq!(226, bucket.channel_value_by_index(3, ColorChannel::G));
        assert_eq!(0, bucket.channel_value_by_index(3, ColorChannel::B));
        assert_eq!(17, bucket.channel_value_by_index(3, ColorChannel::A));
    }

    #[test]
    fn channel_mean_ut() {
        let colors = vec![
            Color { r: 100, g: 50, b: 12, a: 255 },
            Color { r: 100, g: 50, b: 12, a: 255 },
            Color { r: 100, g: 50, b: 12, a: 255 },
            Color { r: 100, g: 50, b: 12, a: 255 },
        ];

        let bucket = ColorBucket::from_pixels(colors).expect("Passed empty color vector to test.");
        let mut result = bucket.channel_mean(ColorChannel::R);
        assert_eq!(100, result);
        result = bucket.channel_mean(ColorChannel::G);
        assert_eq!(50, result);
        result = bucket.channel_mean(ColorChannel::B);
        assert_eq!(12, result);
        result = bucket.channel_mean(ColorChannel::A);
        assert_eq!(255, result);

        // More precise check
        let colors = vec![
            Color { r: 100, g: 22, b: 12, a: 0 },
            Color { r: 126, g: 175, b: 137, a: 1 },
            Color { r: 221, g: 225, b: 0, a: 113 },
            Color { r: 13, g: 226, b: 0, a: 17 },
        ];

        let bucket = ColorBucket::from_pixels(colors).expect("Passed empty color vector to test.");

        result = bucket.channel_mean(ColorChannel::R);
        assert_eq!(115, result);
        result = bucket.channel_mean(ColorChannel::G);
        assert_eq!(162, result);
        result = bucket.channel_mean(ColorChannel::B);
        assert_eq!(37, result);
        result = bucket.channel_mean(ColorChannel::A);
        assert_eq!(32, result);
    }

    #[test]
    pub fn ut_color_mean() {
        let colors = generate_unsorted_colors();
        let bucket = ColorBucket::from_pixels(colors).expect("Passed empty color vector to test.");

        let result = bucket.color_mean();
        let expected = Color { r: 14, g: 11, b: 8, a: 40 };
        assert_eq!(expected, result);
    }

    #[test]
    fn median_cut_ut() {
        let mut bucket = ColorBucket::from_pixels(generate_unsorted_colors()).expect("Passed empty color vector to test.");
        let result = bucket.median_cut();
        assert_eq!(
            result.0,
            Some(ColorBucket::from_pixels(vec![Color { r: 3, g: 4, b: 15, a: 2 }, Color { r: 55, g: 17, b: 0, a: 118 }]).unwrap())
        );
        assert_eq!(
            result.1,
            Some(ColorBucket::from_pixels(vec![Color { r: 0, g: 2, b: 1, a: 20 }, Color { r: 1, g: 23, b: 16, a: 20 }]).unwrap())
        );

        let mut bucket = ColorBucket::from_pixels(vec![Color { r: 0, g: 0, b: 0, a: 0 }]).expect("Passed empty color vector to test.");
        let result = bucket.median_cut();
        assert_eq!(result.0, None);
        assert_eq!(result.1, Some(ColorBucket::from_pixels(vec![Color { r: 0, g: 0, b: 0, a: 0 }])).unwrap());
    }

    #[test]
    fn highest_range_channel_ut() {
        let bucket = ColorBucket::from_pixels(generate_unsorted_colors()).expect("Passed empty color vector to test");
        assert_eq!(ColorChannel::R, bucket.highest_range_channel());
        assert_ne!(ColorChannel::G, bucket.highest_range_channel());
        assert_ne!(ColorChannel::B, bucket.highest_range_channel());
        assert_ne!(ColorChannel::A, bucket.highest_range_channel());
    }

    #[test]
    fn color_ranges_ut() {
        let bucket = ColorBucket::from_pixels(generate_unsorted_colors()).expect("Passed empty color vector to test");
        let expected = Color { r: 55, g: 21, b: 16, a: 116 };
        assert_eq!(expected, bucket.color_ranges());
    }

    fn generate_unsorted_colors() -> Vec<Color> {
        vec![
            Color { r: 55, g: 17, b: 0, a: 118 },
            Color { r: 0, g: 2, b: 1, a: 20 },
            Color { r: 3, g: 4, b: 15, a: 2 },
            Color { r: 1, g: 23, b: 16, a: 20 },
        ]
    }
}