diff options
Diffstat (limited to 'src/lib.rs')
-rw-r--r-- | src/lib.rs | 246 |
1 files changed, 109 insertions, 137 deletions
diff --git a/src/lib.rs b/src/lib.rs index ed3d4e2..9ab6b5c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,83 +1,91 @@ -use nih_kmeans::KMeans; -use rgb::RGB8; -use std::collections::HashMap; +use std::collections::HashSet; + +use rgb::{ComponentBytes, FromSlice, RGB8}; pub mod difference; mod nih_kmeans; +pub mod selection; -type DiffFn = dyn Fn(&RGB8, &RGB8) -> f32; +use difference::DiffFn; +use selection::Selector; -pub struct SquasherBuilder<T> { +pub struct SquasherBuilder<T: Count> { max_colours: T, difference_fn: Box<DiffFn>, - tolerance: f32, + selector: Option<Box<dyn Selector + 'static>>, } impl<T: Count> SquasherBuilder<T> { + // I don't want a default here because, to me anyway, Default implies a + // working struct and this would panic build() + #[allow(clippy::new_without_default)] pub fn new() -> Self { - Self::default() + Self { + max_colours: T::zero(), + difference_fn: Box::new(difference::rgb), + selector: None, + } } /// The max number of colors selected for the palette, minus one. /// /// `max_colors(255)` will attempt to make a 256 color palette - pub fn max_colors(mut self, max_minus_one: T) -> SquasherBuilder<T> { + pub fn max_colors(mut self, max_minus_one: T) -> Self { self.max_colours = max_minus_one; self } - /// The function to use to compare colours. + /// The function to use to compare colours while mapping the image. /// - /// see the [difference] module for functions included with the crate. - pub fn difference(mut self, difference: &'static DiffFn) -> SquasherBuilder<T> { + /// see the [difference] module for functions included with the crate and + /// information on implementing your own. + pub fn mapper_difference(mut self, difference: &'static DiffFn) -> Self { self.difference_fn = Box::new(difference); self } - /// Percent colours have to differ by to be included into the palette. - /// between and including 0.0 to 100.0 - pub fn tolerance(mut self, percent: f32) -> SquasherBuilder<T> { - self.tolerance = percent; + pub fn selector(mut self, selector: impl Selector + 'static) -> Self { + self.selector = Some(Box::new(selector)); self } - pub fn build(self, image: &[u8]) -> Squasher<T> { + pub fn build<'a, Img>(self, image: Img) -> Squasher<T> + where + Img: Into<ImageData<'a>>, + { let mut squasher = - Squasher::from_parts(self.max_colours, self.difference_fn, self.tolerance); + Squasher::from_parts(self.max_colours, self.difference_fn, self.selector.unwrap()); squasher.recolor(image); squasher } } -impl<T: Count> Default for SquasherBuilder<T> { - fn default() -> Self { - Self { - max_colours: T::from_usize(255), - difference_fn: Box::new(difference::rgb_difference), - tolerance: 1.0, - } - } -} - pub struct Squasher<T> { // one less than the max colours as you can't have a zero colour image. max_colours_min1: T, palette: Vec<RGB8>, map: Vec<T>, + selector: Box<dyn Selector + 'static>, difference_fn: Box<DiffFn>, - tolerance_percent: f32, } impl<T: Count> Squasher<T> { /// Creates a new squasher and allocates a new color map. A color map /// contains every 24-bit color and ends up with an amount of memory /// equal to `16MB * std::mem::size_of(T)`. - pub fn new(max_colors_minus_one: T, buffer: &[u8]) -> Self { + pub fn new<'a, Img>( + max_colors_minus_one: T, + selector: impl Selector + 'static, + buffer: Img, + ) -> Self + where + Img: Into<ImageData<'a>>, + { let mut this = Self::from_parts( max_colors_minus_one, - Box::new(difference::rgb_difference), - 1.0, + Box::new(difference::rgb), + Box::new(selector), ); this.recolor(buffer); @@ -88,79 +96,75 @@ impl<T: Count> Squasher<T> { SquasherBuilder::new() } - pub fn set_tolerance(&mut self, percent: f32) { - self.tolerance_percent = percent; - } - /// Create a new palette from the colours in the given image. - pub fn recolor(&mut self, image: &[u8]) { - let sorted = Self::unique_and_sort(image); - let selected = self.select_colors(sorted); - self.palette = selected; - } - - /// Create a new palette from the colours in the given image, using the iterative kmeans algorithm with simplified seeding - pub fn recolor_kmeans(&mut self, image: &[u8], max_iter: usize) { - let kmean = KMeans::new( - image - .chunks_exact(3) - .map(|bytes| RGB8::new(bytes[0], bytes[1], bytes[2])) - .collect(), - ); - self.palette = kmean.get_k_colors(self.max_colours_min1.as_usize() + 1, max_iter); + pub fn recolor<'a, Img>(&mut self, image: Img) + where + Img: Into<ImageData<'a>>, + { + self.palette = self + .selector + .select(self.max_colours_min1.as_usize() + 1, image.into()); } /// Create a Squasher from parts. Noteably, this leave your palette empty - fn from_parts(max_colours_min1: T, difference_fn: Box<DiffFn>, tolerance: f32) -> Self { + fn from_parts( + max_colours_min1: T, + difference_fn: Box<DiffFn>, + selector: Box<dyn Selector>, + ) -> Self { Self { max_colours_min1, palette: vec![], map: vec![T::zero(); 256 * 256 * 256], difference_fn, - tolerance_percent: tolerance, + selector, } } /// Take an RGB image buffer and an output buffer. The function will fill /// the output buffer with indexes into the Palette. The output buffer should /// be a third of the size of the image buffer. - pub fn map(&mut self, image: &[u8], buffer: &mut [T]) { - if buffer.len() * 3 < image.len() { - panic!("outout buffer too small to fit indexed image"); + pub fn map<'a, Img>(&mut self, image: Img, buffer: &mut [T]) + where + Img: Into<ImageData<'a>>, + { + let ImageData(rgb) = image.into(); + + if buffer.len() * 3 < rgb.len() { + panic!("output buffer too small to fit indexed image"); } // We have to map the colours of this image now because it might contain // colours not present in the first image. - let sorted = Self::unique_and_sort(image); - self.map_selected(&sorted); - - for (idx, color) in image.chunks(3).enumerate() { - let index = self.map[color_index(&RGB8::new(color[0], color[1], color[2]))]; + let unique = Self::unique_colors(rgb); + self.map_selected(&unique); - buffer[idx] = index; + for (idx, color) in rgb.iter().enumerate() { + buffer[idx] = self.map[color_index(color)]; } } /// Like [Squasher::map] but it doesn't recount the input image. This will /// cause colors the Squasher hasn't seen before to come out as index 0 which - /// may be incorrect. + /// may be incorrect! //TODO: gen- Better name? - pub fn map_unsafe(&self, image: &[u8], buffer: &mut [T]) { - if buffer.len() * 3 < image.len() { - panic!("outout buffer too small to fit indexed image"); + pub fn map_no_recolor<'a, Img>(&self, image: Img, buffer: &mut [T]) + where + Img: Into<ImageData<'a>>, + { + let ImageData(rgb) = image.into(); + + if buffer.len() * 3 < rgb.len() { + panic!("output buffer too small to fit indexed image"); } - for (idx, color) in image.chunks(3).enumerate() { - let index = self.map[color_index(&RGB8::new(color[0], color[1], color[2]))]; - - buffer[idx] = index; + for (idx, color) in rgb.iter().enumerate() { + buffer[idx] = self.map[color_index(color)]; } } #[cfg(feature = "gifed")] pub fn palette_gifed(&self) -> gifed::block::Palette { - use rgb::ComponentBytes; - self.palette.as_slice().as_bytes().try_into().unwrap() } @@ -171,73 +175,12 @@ impl<T: Count> Squasher<T> { /// Retrieve the palette as bytes pub fn palette_bytes(&self) -> Vec<u8> { - self.palette - .clone() - .into_iter() - .flat_map(|rgb| [rgb.r, rgb.g, rgb.b].into_iter()) - .collect() - } - - /// Takes an image buffer of RGB data and fill the color map - fn unique_and_sort(buffer: &[u8]) -> Vec<RGB8> { - let mut colors: HashMap<RGB8, usize> = HashMap::default(); - - //count pixels - for pixel in buffer.chunks(3) { - let rgb = RGB8::new(pixel[0], pixel[1], pixel[2]); - - match colors.get_mut(&rgb) { - None => { - colors.insert(rgb, 1); - } - Some(n) => *n += 1, - } - } - - Self::sort(colors) - } - - fn sort(map: HashMap<RGB8, usize>) -> Vec<RGB8> { - let mut sorted: Vec<(RGB8, usize)> = map.into_iter().collect(); - sorted.sort_by(|(colour1, freq1), (colour2, freq2)| { - freq2 - .cmp(freq1) - .then(colour2.r.cmp(&colour1.r)) - .then(colour2.g.cmp(&colour1.g)) - .then(colour2.b.cmp(&colour1.b)) - }); - - sorted.into_iter().map(|(color, _count)| color).collect() - } - - /// Pick the colors in the palette from a Vec of colors sorted by number - /// of times they occur, high to low. - fn select_colors(&self, sorted: Vec<RGB8>) -> Vec<RGB8> { - // I made these numbers up - #[allow(non_snake_case)] - //let RGB_TOLERANCE: f32 = 0.01 * 765.0; - //let RGB_TOLERANCE: f32 = 36.0; - let tolerance = (self.tolerance_percent / 100.0) * 765.0; - let max_colours = self.max_colours_min1.as_usize() + 1; - let mut selected_colors: Vec<RGB8> = Vec::with_capacity(max_colours); - - for sorted_color in sorted { - if max_colours <= selected_colors.len() { - break; - } else if selected_colors - .iter() - .all(|color| (self.difference_fn)(&sorted_color, color) > tolerance) - { - selected_colors.push(sorted_color); - } - } - - selected_colors + self.palette.as_bytes().to_owned() } /// Pick the closest colour in the palette for each unique color in the image - fn map_selected(&mut self, sorted: &[RGB8]) { - for colour in sorted { + fn map_selected(&mut self, unique: &[RGB8]) { + for colour in unique { let mut min_diff = f32::MAX; let mut min_index = usize::MAX; @@ -253,6 +196,14 @@ impl<T: Count> Squasher<T> { self.map[color_index(colour)] = T::from_usize(min_index); } } + + fn unique_colors(image: &[RGB8]) -> Vec<RGB8> { + let mut unique: HashSet<RGB8> = HashSet::new(); + for px in image { + unique.insert(*px); + } + unique.into_iter().collect() + } } impl Squasher<u8> { @@ -264,8 +215,8 @@ impl Squasher<u8> { pub fn map_over(&mut self, image: &mut [u8]) -> usize { // We have to map the colours of this image now because it might contain // colours not present in the first image. - let sorted = Self::unique_and_sort(image); - self.map_selected(&sorted); + let unique = Self::unique_colors(image.as_rgb()); + self.map_selected(&unique); for idx in 0..(image.len() / 3) { let rgb_idx = idx * 3; @@ -316,6 +267,27 @@ count_impl!(u32); count_impl!(u64); count_impl!(usize); +pub struct ImageData<'a>(&'a [RGB8]); + +impl<'a> From<&'a Vec<u8>> for ImageData<'a> { + fn from(plain: &'a Vec<u8>) -> Self { + ImageData(plain.as_rgb()) + } +} + +impl<'a> From<&'a [u8]> for ImageData<'a> { + fn from(plain: &'a [u8]) -> Self { + ImageData(plain.as_rgb()) + } +} + +impl<'a> From<&'a [RGB8]> for ImageData<'a> { + fn from(rgb: &'a [RGB8]) -> Self { + ImageData(rgb) + } +} + +/// Compute the color index into the big-map-of-all-colours. #[inline(always)] fn color_index(c: &RGB8) -> usize { c.r as usize * (256 * 256) + c.g as usize * 256 + c.b as usize |