With threads, some prettying up to do

This commit is contained in:
Dandaedre 2024-09-05 21:15:49 +02:00
parent 2ff656edb8
commit 6a8bee0b4a
2 changed files with 37 additions and 15 deletions

View File

@ -6,6 +6,7 @@ edition = "2021"
[dependencies]
clap = { version = "4.5.16", features = ["derive"] }
console = "0.15.8"
image = "0.25.2"
indicatif = { version = "0.17.8", features = ["rayon"] }
kmeans_colors = "0.6.0"

View File

@ -1,6 +1,8 @@
use clap::{Parser, ValueEnum};
use console::style;
use image::{GenericImageView, Pixel};
use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use indicatif::{HumanDuration, MultiProgress, ProgressBar, ProgressStyle};
// use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
// use image::ImageEncoder;
use kmeans_colors::{get_kmeans_hamerly, Kmeans, Sort};
@ -17,6 +19,8 @@ use std::path::PathBuf;
use std::collections::HashSet;
use std::path::Path;
use std::thread;
use std::time::{Duration, Instant};
/// CLI for extracting a color palette from an image and exporting it.
#[derive(Parser, Debug)]
@ -79,11 +83,17 @@ impl RichColor {
}
fn main() {
let started = Instant::now();
let spinner_style = ProgressStyle::with_template("{prefix:.bold.dim} {spinner} {wide_msg}")
.unwrap()
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ");
let cli = Cli::parse();
let export_path = match cli.export {
Some(e) => e,
None => cli.image[0]
.parent()
// Check output here, not later
.expect("Couldn't find a place to save the output")
.to_path_buf(),
};
@ -102,17 +112,31 @@ fn main() {
ExtractMode::Cluster => extract_kcluster,
};
let style = ProgressStyle::default_bar();
let colorblobs = cli
let m = MultiProgress::new();
// let style = ProgressStyle::default_bar();
let handles: Vec<_> = cli
.image
.par_iter()
.progress_with_style(style)
.map(|image| function(image, cli.nb_colors))
.collect::<Vec<ColorIndex>>();
export_html(export_path, colorblobs);
.map(|image| {
let pb = m.add(ProgressBar::new(8)); // TODO: Not use 8 for passes and have it as parameter
// pb.set_style(spinner_style.clone());
pb.set_prefix(format!("[{:?}]", image)); // Make shorter by def
let image = image.clone();
thread::spawn(move || function(&image, cli.nb_colors, &pb))
})
.collect();
// .collect::<Vec<ColorIndex>>();
for h in handles {
let _ = h.join();
}
m.clear().unwrap();
// export(export_path, colorblobs);
println!("Done in {}", HumanDuration(started.elapsed()));
}
fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>, pb: &ProgressBar) -> ColorIndex {
let name = image
.file_name()
.unwrap()
@ -146,11 +170,9 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
.filter(|x| x.alpha == 255)
.map(|x| Srgb::<f32>::from_color(x.into_format::<_, f32>())),
);
println!("Started");
// Iterate over amount of runs keeping best results
let mut result = Kmeans::new();
for i in 0..runs {
println!("{}", runs);
let run_result = get_kmeans_hamerly(
nb_colors,
max_iter,
@ -162,8 +184,8 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
if run_result.score < result.score {
result = run_result;
}
pb.inc(1);
}
println!("Done");
// Print and/or sort results, output to palette
let mut res: Vec<kmeans_colors::CentroidData<palette::rgb::Rgb>> =
Srgb::sort_indexed_colors(&result.centroids, &result.indices);
@ -188,7 +210,7 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
ColorIndex::new(name, colors)
}
fn extract_colors(image_path: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
fn extract_colors(image_path: &PathBuf, nb_colors: Option<usize>, pb: &ProgressBar) -> ColorIndex {
let _ = nb_colors;
let name = image_path
.file_name()
@ -238,6 +260,7 @@ fn extract_colors(image_path: &PathBuf, nb_colors: Option<usize>) -> ColorIndex
}
vec.sort_by_key(|&(k, _, _)| k);
pb.inc(8); // TODO: Have a real pb
println!("[{}] Found {} unique colors", name, colors.len());
ColorIndex::new(
name,
@ -246,9 +269,7 @@ fn extract_colors(image_path: &PathBuf, nb_colors: Option<usize>) -> ColorIndex
.collect(),
)
}
/// Export the colors a a html file
fn export_html(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
fn export(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
// 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"));