From f58997b47928dc3c49ef9a1b317fad30d8b94473 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 6 Sep 2024 16:52:46 +0200 Subject: [PATCH] Splitting into files --- src/image_functions.rs | 142 ++++++++++++++++ src/main.rs | 356 ++++------------------------------------- src/structs.rs | 40 +++++ src/utilities.rs | 145 +++++++++++++++++ 4 files changed, 361 insertions(+), 322 deletions(-) create mode 100644 src/image_functions.rs create mode 100644 src/structs.rs create mode 100644 src/utilities.rs diff --git a/src/image_functions.rs b/src/image_functions.rs new file mode 100644 index 0000000..f60b83e --- /dev/null +++ b/src/image_functions.rs @@ -0,0 +1,142 @@ +use image::{GenericImageView, Pixel}; +use indicatif::ProgressBar; +use kmeans_colors::{get_kmeans_hamerly, Kmeans, Sort}; +use palette::{ + cast::ComponentsAs, color_difference::Wcag21RelativeContrast, FromColor, Hsl, Srgb, Srgba, +}; +use std::{ + collections::HashSet, + path::{Path, PathBuf}, +}; + +use crate::{ + structs::{ColorIndex, RichColor}, + utilities::extract_name, + Cli, +}; + +/// Extract a subset of most representative colors +pub(crate) fn extract_kcluster(image: &PathBuf, cli: &Cli, pb: &ProgressBar) -> ColorIndex { + let name = extract_name(image); + let runs = cli.runs.unwrap_or(8); + let nb_colors = cli.nb_colors.unwrap_or(8); + let max_iter = 20; + let converge = 0.0025; + let verbose = false; + let seed = 424242; + // Replace with your image path + let image_path = image; + let mut rgb_pixels: Vec> = Vec::new(); + // Open the image + let img = image::open(image_path) + .expect("Couldn't open image") + .into_rgba8(); + let img_vec: &[Srgba] = img.as_raw().components_as(); + + rgb_pixels.clear(); + + // Read image buffer into Srgb format + rgb_pixels.extend( + img_vec + .iter() + .filter(|x| x.alpha == 255) + .map(|x| Srgb::::from_color(x.into_format::<_, f32>())), + ); + // Iterate over amount of runs keeping best results + let mut result = Kmeans::new(); + for i in 0..runs { + let run_result = get_kmeans_hamerly( + nb_colors, + max_iter, + converge, + verbose, + &rgb_pixels, + seed + i as u64, + ); + if run_result.score < result.score { + result = run_result; + } + pb.inc(1); + } + // Print and/or sort results, output to palette + let mut res: Vec> = + Srgb::sort_indexed_colors(&result.centroids, &result.indices); + res.sort_unstable_by(|a, b| (b.percentage).total_cmp(&a.percentage)); + let colors = res + .iter() + .map(|c| { + RichColor::new( + 0, + (c.centroid.relative_luminance().luma * 255.) as u32, + ( + (c.centroid.red * 255.) as u8, + (c.centroid.green * 255.) as u8, + (c.centroid.blue * 255.) as u8, + ), + ) + }) + .collect::>(); + + ColorIndex::new(name, colors) +} + +/// Extract the first nb unique colors +pub(crate) fn extract_colors(image_path: &PathBuf, cli: &Cli, pb: &ProgressBar) -> ColorIndex { + let _ = cli; + let name = image_path + .file_name() + .unwrap() + .to_str() + .unwrap() + .split(".") + .next() + .unwrap() + .to_string(); + // Open the image + let img = image::open(Path::new(&image_path)).expect("Failed to open image"); + + // Create a HashSet to store unique colors + let mut colors = HashSet::new(); + + // Iterate over the pixels + for pixel in img.pixels() { + // Get the color as a tuple (R, G, B, A) + let rgb = pixel.2.to_rgb(); + let srgb = Srgb::new( + rgb[0] as f64 / 255., + rgb[1] as f64 / 255., + rgb[2] as f64 / 255., + ); + let hsl = Hsl::from_color(srgb); + // Insert the color into the HashSet + colors.insert(( + rgb[0], + rgb[1], + rgb[2], + (hsl.hue.into_positive_degrees() * 100.) as u32, + (hsl.lightness * 100.) as u32, + )); + } + + let mut vec = Vec::with_capacity(colors.len() + 1); + // Print the unique colors + for color in &colors { + println!("[{}] {:?}", name, color); + + vec.push(( + color.3, // format!("#{:02X}{:02X}{:02X}", color.0, color.1, color.2), + (color.0, color.1, color.2), + color.4, + )); + } + + vec.sort_by_key(|&(k, _, _)| k); + pb.inc(8); // TODO: Have a real pb + println!("[{}] Found {} unique colors", name, colors.len()); + ColorIndex::new( + name, + vec.iter() + .map(|(hue, rgb, luma)| RichColor::new(*hue, *luma, rgb.to_owned())) + .collect(), + ) +} diff --git a/src/main.rs b/src/main.rs index 53fc6d9..978cf5f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,27 +1,17 @@ -use clap::{Parser, ValueEnum}; -// use console::style; -use image::{GenericImageView, Pixel}; -use indicatif::ParallelProgressIterator; +mod image_functions; +mod structs; +mod utilities; + +use clap::Parser; +use image_functions::{extract_colors, extract_kcluster}; use indicatif::{HumanDuration, MultiProgress, ProgressBar, ProgressStyle}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; -// use image::ImageEncoder; -use kmeans_colors::{get_kmeans_hamerly, Kmeans, Sort}; -use palette::cast::ComponentsAs; -use palette::color_difference::Wcag21RelativeContrast; -use palette::FromColor; -use palette::{Srgb, Srgba}; - -use palette::Hsl; -// use std::error::Error; -use std::fs::File; -use std::io::{BufWriter, Write}; -use std::path::PathBuf; - -use std::collections::HashSet; -use std::path::Path; -// use std::rc::Rc; -// use std::thread; -use std::time::{Duration, Instant}; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; +use structs::{ColorIndex, ExtractMode}; +use utilities::{export_html, small_name}; /// CLI for extracting a color palette from an image and exporting it. #[derive(Parser, Debug)] @@ -42,45 +32,14 @@ struct Cli { /// Max number of colors to extract #[arg(short, long, value_enum, value_name = "NB_COLORS")] nb_colors: Option, -} -/// Supported export formats for the color palette -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] -enum ExtractMode { - Full, - Cluster, -} + /// Number of passes to process + #[arg(short, long, value_name = "NB_RUNS")] + runs: Option, -/// A color index -struct ColorIndex { - name: String, - colors: Vec, -} - -impl ColorIndex { - fn new(name: String, colors: Vec) -> Self { - Self { name, colors } - } -} - -/// A single color, with many infos -struct RichColor { - #[allow(dead_code)] - hue: u32, - luma: u32, - rgb: (u8, u8, u8), -} - -impl RichColor { - fn rgb_string(&self) -> String { - format!("#{:02X}{:02X}{:02X}", self.rgb.0, self.rgb.1, self.rgb.2) - } -} - -impl RichColor { - fn new(hue: u32, luma: u32, rgb: (u8, u8, u8)) -> Self { - Self { hue, luma, rgb } - } + /// Extra Verbosity + #[arg(short, default_value_t = false)] + verbosity: bool, } fn main() { @@ -92,7 +51,7 @@ fn main() { .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ "); let cli = Cli::parse(); - let export_path = match cli.export { + let export_path = match cli.export.clone() { Some(e) => e, None => cli.image[0] .parent() @@ -106,9 +65,11 @@ fn main() { }; // Display parsed arguments - println!("[INFO] Image Path: {:?}", &cli.image); - println!("[INFO] Export Path: {:?}", &export_path); - // println!("[INFO] Export Format: {:?}", &cli.format); + if cli.verbosity { + println!("[INFO] Image Path: {:?}", &cli.image); + println!("[INFO] Export Path: {:?}", &export_path); + // println!("[INFO] Export Format: {:?}", &cli.format); + } let function = match mode { ExtractMode::Full => extract_colors, @@ -117,277 +78,28 @@ fn main() { let m = MultiProgress::new(); let pb_general = ProgressBar::new(cli.image.len() as u64) - // let pb_general = ProgressBar:: .with_style(spinner_style.clone()) - // pb_general.set_style(spinner_style.clone()); - .with_prefix("Images being processed"); + .with_prefix("Images processed"); m.add(pb_general.clone()); pb_general.enable_steady_tick(Duration::from_millis(100)); let colorblobs: Vec<_> = cli .image .par_iter() - .progress_with(pb_general.clone()) + // .progress_with(pb_general.clone()) .map(|image| { let pb = m.add(ProgressBar::new(8)); // TODO: Not use 8 for passes and have it as parameter pb.enable_steady_tick(Duration::from_millis(100)); pb.set_style(spinner_style.clone()); - pb.set_prefix(format!("[{:?}]", image)); // Make shorter by def - // pb_general.inc(1); - function(image, cli.nb_colors, &pb) + pb.set_prefix(format!("[{:?}]", small_name(image))); + let r = function(image, &cli, &pb); + pb_general.inc(1); + r }) .collect::>(); - println!("Done in {}", HumanDuration(started.elapsed())); - export(export_path, colorblobs); -} - -fn extract_kcluster(image: &PathBuf, nb_colors: Option, pb: &ProgressBar) -> ColorIndex { - let name = image - .file_name() - .unwrap() - .to_str() - .unwrap() - .split(".") - .next() - .unwrap() - .to_string(); - let runs = 8; - let nb_colors = nb_colors.unwrap_or(8); - let max_iter = 20; - let converge = 0.0025; - let verbose = false; - let seed = 424242; - // Replace with your image path - let image_path = image; - let mut rgb_pixels: Vec> = Vec::new(); - // Open the image - let img = image::open(image_path) - .expect("Couldn't open image") - .into_rgba8(); - let img_vec: &[Srgba] = img.as_raw().components_as(); - - rgb_pixels.clear(); - - // Read image buffer into Srgb format - rgb_pixels.extend( - img_vec - .iter() - .filter(|x| x.alpha == 255) - .map(|x| Srgb::::from_color(x.into_format::<_, f32>())), - ); - // Iterate over amount of runs keeping best results - let mut result = Kmeans::new(); - for i in 0..runs { - let run_result = get_kmeans_hamerly( - nb_colors, - max_iter, - converge, - verbose, - &rgb_pixels, - seed + i as u64, - ); - if run_result.score < result.score { - result = run_result; - } - pb.inc(1); + pb_general.finish_and_clear(); + if cli.verbosity { + println!("Done in {}", HumanDuration(started.elapsed())); } - // Print and/or sort results, output to palette - let mut res: Vec> = - Srgb::sort_indexed_colors(&result.centroids, &result.indices); - res.sort_unstable_by(|a, b| (b.percentage).total_cmp(&a.percentage)); - // res.truncate(8); - // println!("{:?}", res.iter().map(|c| )); - let colors = res - .iter() - .map(|c| { - RichColor::new( - 0, - (c.centroid.relative_luminance().luma * 255.) as u32, - ( - (c.centroid.red * 255.) as u8, - (c.centroid.green * 255.) as u8, - (c.centroid.blue * 255.) as u8, - ), - ) - }) - .collect::>(); - - ColorIndex::new(name, colors) + export_html(export_path, colorblobs); } - -fn extract_colors(image_path: &PathBuf, nb_colors: Option, pb: &ProgressBar) -> ColorIndex { - let _ = nb_colors; - let name = image_path - .file_name() - .unwrap() - .to_str() - .unwrap() - .split(".") - .next() - .unwrap() - .to_string(); - // Open the image - let img = image::open(Path::new(&image_path)).expect("Failed to open image"); - - // Create a HashSet to store unique colors - let mut colors = HashSet::new(); - - // Iterate over the pixels - for pixel in img.pixels() { - // Get the color as a tuple (R, G, B, A) - let rgb = pixel.2.to_rgb(); - let srgb = Srgb::new( - rgb[0] as f64 / 255., - rgb[1] as f64 / 255., - rgb[2] as f64 / 255., - ); - let hsl = Hsl::from_color(srgb); - // Insert the color into the HashSet - colors.insert(( - rgb[0], - rgb[1], - rgb[2], - (hsl.hue.into_positive_degrees() * 100.) as u32, - (hsl.lightness * 100.) as u32, - )); - } - - let mut vec = Vec::with_capacity(colors.len() + 1); - // Print the unique colors - for color in &colors { - println!("[{}] {:?}", name, color); - - vec.push(( - color.3, // format!("#{:02X}{:02X}{:02X}", color.0, color.1, color.2), - (color.0, color.1, color.2), - color.4, - )); - } - - vec.sort_by_key(|&(k, _, _)| k); - pb.inc(8); // TODO: Have a real pb - println!("[{}] Found {} unique colors", name, colors.len()); - ColorIndex::new( - name, - vec.iter() - .map(|(hue, rgb, luma)| RichColor::new(*hue, *luma, rgb.to_owned())) - .collect(), - ) -} -fn export(export_path: PathBuf, color_vec: Vec) { - // let mut out = File::create(&export_path).expect("Can't open output file"); - let mut out = BufWriter::new(File::create(&export_path).expect("Can't open output file")); - - write!( - out, - r#""# - ).unwrap(); - write!( - out, - "Palette: {}", - &export_path - .file_name() - .unwrap() - .to_str() - .unwrap() - .split(".") - .next() - .unwrap() - ) - .unwrap(); - write!( - out, - r#" - "# - ) - .unwrap(); - for blob in color_vec { - write!(out, "

{}

", blob.name).unwrap(); - write!(out, "
").unwrap(); - for v in blob.colors { - let c = if v.luma < 60 { "FFFFFF" } else { "000000" }; - write!(out,"
\n {} \n
",v.rgb_string(),c,v.rgb_string()).expect("Can't write color in the output"); - } - write!(out, "
").unwrap(); - } - write!(out, "").unwrap(); -} - -// Save the kcluster picture -// Pre-convert centroids into output format -// let centroids = &result -// .centroids -// .iter() -// .map(|x| x.into_format()) -// .collect::>>(); -// let rgb: Vec> = Srgb::map_indices_to_centroids(centroids, &result.indices); - -// save_image( -// rgb.as_components(), -// imgx, -// imgy, -// Path::new("testout.png"), -// false, -// ) -// .unwrap(); -// /// Saves image buffer to file. -// pub fn save_image( -// imgbuf: &[u8], -// imgx: u32, -// imgy: u32, -// title: &Path, -// palette: bool, -// ) -> Result<(), Box> { -// let mut w = BufWriter::new(File::create(title)?); -// if title.extension().unwrap() == "png" { -// // If file is a palette, use Adaptive filtering to save more space -// use image::codecs::png::FilterType::{Adaptive, NoFilter}; -// let encoder = image::codecs::png::PngEncoder::new_with_quality( -// w, -// image::codecs::png::CompressionType::Best, -// if palette { Adaptive } else { NoFilter }, -// ); - -// // Clean up if file is created but there's a problem writing to it -// match encoder.write_image(imgbuf, imgx, imgy, image::ColorType::Rgb8.into()) { -// Ok(_) => {} -// Err(err) => { -// eprintln!("Error: {}.", err); -// std::fs::remove_file(title)?; -// } -// } -// } else { -// let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut w, 90); - -// match encoder.encode(imgbuf, imgx, imgy, image::ColorType::Rgb8.into()) { -// Ok(_) => {} -// Err(err) => { -// eprintln!("Error: {}.", err); -// std::fs::remove_file(title)?; -// } -// } -// }; - -// Ok(()) -// } diff --git a/src/structs.rs b/src/structs.rs new file mode 100644 index 0000000..4a0c919 --- /dev/null +++ b/src/structs.rs @@ -0,0 +1,40 @@ +use clap::ValueEnum; + +/// Supported export formats for the color palette +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] +pub(crate) enum ExtractMode { + Full, + Cluster, +} + +/// A color index +pub(crate) struct ColorIndex { + pub name: String, + pub colors: Vec, +} + +impl ColorIndex { + pub(crate) fn new(name: String, colors: Vec) -> Self { + Self { name, colors } + } +} + +/// A single color, with many infos +pub(crate) struct RichColor { + #[allow(dead_code)] + pub hue: u32, + pub luma: u32, + pub rgb: (u8, u8, u8), +} + +impl RichColor { + pub(crate) fn rgb_string(&self) -> String { + format!("#{:02X}{:02X}{:02X}", self.rgb.0, self.rgb.1, self.rgb.2) + } +} + +impl RichColor { + pub(crate) fn new(hue: u32, luma: u32, rgb: (u8, u8, u8)) -> Self { + Self { hue, luma, rgb } + } +} diff --git a/src/utilities.rs b/src/utilities.rs new file mode 100644 index 0000000..488e741 --- /dev/null +++ b/src/utilities.rs @@ -0,0 +1,145 @@ +use std::{ + fs::File, + io::{BufWriter, Write}, + path::{Path, PathBuf}, +}; + +use crate::structs::ColorIndex; + +/// Make a smaller name +pub(crate) fn small_name(name: &Path) -> String { + let os = format!("{:?}", name.to_string_lossy()); + os +} + +/// Extract the image name +pub(crate) fn extract_name(image: &Path) -> String { + image + .file_name() + .unwrap() + .to_str() + .unwrap() + .split(".") + .next() + .unwrap() + .to_string() +} + +/// Export the file as html +pub(crate) fn export_html(export_path: PathBuf, color_vec: Vec) { + // let mut out = File::create(&export_path).expect("Can't open output file"); + let mut out = BufWriter::new(File::create(&export_path).expect("Can't open output file")); + + write!( + out, + r#""# + ).unwrap(); + write!( + out, + "Palette: {}", + &export_path + .file_name() + .unwrap() + .to_str() + .unwrap() + .split(".") + .next() + .unwrap() + ) + .unwrap(); + write!( + out, + r#" + "# + ) + .unwrap(); + for blob in color_vec { + write!(out, "

{}

", blob.name).unwrap(); + write!(out, "
").unwrap(); + for v in blob.colors { + let c = if v.luma < 60 { "FFFFFF" } else { "000000" }; + write!(out,"
\n {} \n
",v.rgb_string(),c,v.rgb_string()).expect("Can't write color in the output"); + } + write!(out, "
").unwrap(); + } + write!(out, "").unwrap(); +} + +// Save the kcluster picture +// Pre-convert centroids into output format +// let centroids = &result +// .centroids +// .iter() +// .map(|x| x.into_format()) +// .collect::>>(); +// let rgb: Vec> = Srgb::map_indices_to_centroids(centroids, &result.indices); + +// save_image( +// rgb.as_components(), +// imgx, +// imgy, +// Path::new("testout.png"), +// false, +// ) +// .unwrap(); +// /// Saves image buffer to file. +// pub fn save_image( +// imgbuf: &[u8], +// imgx: u32, +// imgy: u32, +// title: &Path, +// palette: bool, +// ) -> Result<(), Box> { +// let mut w = BufWriter::new(File::create(title)?); +// if title.extension().unwrap() == "png" { +// // If file is a palette, use Adaptive filtering to save more space +// use image::codecs::png::FilterType::{Adaptive, NoFilter}; +// let encoder = image::codecs::png::PngEncoder::new_with_quality( +// w, +// image::codecs::png::CompressionType::Best, +// if palette { Adaptive } else { NoFilter }, +// ); + +// // Clean up if file is created but there's a problem writing to it +// match encoder.write_image(imgbuf, imgx, imgy, image::ColorType::Rgb8.into()) { +// Ok(_) => {} +// Err(err) => { +// eprintln!("Error: {}.", err); +// std::fs::remove_file(title)?; +// } +// } +// } else { +// let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut w, 90); + +// match encoder.encode(imgbuf, imgx, imgy, image::ColorType::Rgb8.into()) { +// Ok(_) => {} +// Err(err) => { +// eprintln!("Error: {}.", err); +// std::fs::remove_file(title)?; +// } +// } +// }; + +// Ok(()) +// }