First par_iter implementation (good but no feedback :( )
This commit is contained in:
parent
a8ac428a52
commit
2ff656edb8
|
|
@ -7,8 +7,10 @@ edition = "2021"
|
|||
[dependencies]
|
||||
clap = { version = "4.5.16", features = ["derive"] }
|
||||
image = "0.25.2"
|
||||
indicatif = { version = "0.17.8", features = ["rayon"] }
|
||||
kmeans_colors = "0.6.0"
|
||||
palette = "0.7.6"
|
||||
rayon = "1.10.0"
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
|
|
|
|||
202
src/main.rs
202
src/main.rs
|
|
@ -1,5 +1,7 @@
|
|||
use clap::{Parser, ValueEnum};
|
||||
use image::{GenericImageView, Pixel};
|
||||
use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
|
||||
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
|
||||
// use image::ImageEncoder;
|
||||
use kmeans_colors::{get_kmeans_hamerly, Kmeans, Sort};
|
||||
use palette::cast::ComponentsAs;
|
||||
|
|
@ -95,39 +97,33 @@ fn main() {
|
|||
println!("[INFO] Export Path: {:?}", &export_path);
|
||||
// println!("[INFO] Export Format: {:?}", &cli.format);
|
||||
|
||||
let mut colorblobs = Vec::with_capacity(cli.image.len());
|
||||
match mode {
|
||||
ExtractMode::Full => {
|
||||
for image in cli.image {
|
||||
colorblobs.push(extract_colors(&image));
|
||||
}
|
||||
}
|
||||
ExtractMode::Cluster => {
|
||||
for image in cli.image {
|
||||
colorblobs.push(extract_kcluster(&image, cli.nb_colors));
|
||||
}
|
||||
}
|
||||
}
|
||||
export(export_path, colorblobs);
|
||||
let function = match mode {
|
||||
ExtractMode::Full => extract_colors,
|
||||
ExtractMode::Cluster => extract_kcluster,
|
||||
};
|
||||
|
||||
let style = ProgressStyle::default_bar();
|
||||
let colorblobs = cli
|
||||
.image
|
||||
.par_iter()
|
||||
.progress_with_style(style)
|
||||
.map(|image| function(image, cli.nb_colors))
|
||||
.collect::<Vec<ColorIndex>>();
|
||||
export_html(export_path, colorblobs);
|
||||
}
|
||||
|
||||
fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
|
||||
let name = format!(
|
||||
"{}",
|
||||
image
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(".")
|
||||
.nth(0)
|
||||
.unwrap()
|
||||
);
|
||||
let name = image
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(".")
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let runs = 8;
|
||||
let nb_colors = match nb_colors {
|
||||
Some(c) => c,
|
||||
None => 8,
|
||||
};
|
||||
let nb_colors = nb_colors.unwrap_or(8);
|
||||
let max_iter = 20;
|
||||
let converge = 0.0025;
|
||||
let verbose = false;
|
||||
|
|
@ -150,11 +146,13 @@ 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 as usize,
|
||||
nb_colors,
|
||||
max_iter,
|
||||
converge,
|
||||
verbose,
|
||||
|
|
@ -165,6 +163,7 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
|
|||
result = run_result;
|
||||
}
|
||||
}
|
||||
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);
|
||||
|
|
@ -185,40 +184,23 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
|
|||
)
|
||||
})
|
||||
.collect::<Vec<RichColor>>();
|
||||
// Pre-convert centroids into output format
|
||||
// let centroids = &result
|
||||
// .centroids
|
||||
// .iter()
|
||||
// .map(|x| x.into_format())
|
||||
// .collect::<Vec<Srgb<u8>>>();
|
||||
// let rgb: Vec<Srgb<u8>> = Srgb::map_indices_to_centroids(centroids, &result.indices);
|
||||
|
||||
// save_image(
|
||||
// rgb.as_components(),
|
||||
// imgx,
|
||||
// imgy,
|
||||
// Path::new("testout.png"),
|
||||
// false,
|
||||
// )
|
||||
// .unwrap();
|
||||
|
||||
ColorIndex::new(name, colors)
|
||||
}
|
||||
|
||||
fn extract_colors(image_path: &PathBuf) -> ColorIndex {
|
||||
let name = format!(
|
||||
"{}",
|
||||
image_path
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(".")
|
||||
.nth(0)
|
||||
.unwrap()
|
||||
);
|
||||
fn extract_colors(image_path: &PathBuf, nb_colors: Option<usize>) -> 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");
|
||||
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();
|
||||
|
|
@ -264,47 +246,9 @@ fn extract_colors(image_path: &PathBuf) -> ColorIndex {
|
|||
.collect(),
|
||||
)
|
||||
}
|
||||
// /// Saves image buffer to file.
|
||||
// pub fn save_image(
|
||||
// imgbuf: &[u8],
|
||||
// imgx: u32,
|
||||
// imgy: u32,
|
||||
// title: &Path,
|
||||
// palette: bool,
|
||||
// ) -> Result<(), Box<dyn Error>> {
|
||||
// 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(())
|
||||
// }
|
||||
fn export(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
|
||||
/// Export the colors a a html file
|
||||
fn export_html(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"));
|
||||
|
||||
|
|
@ -321,7 +265,7 @@ fn export(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
|
|||
.to_str()
|
||||
.unwrap()
|
||||
.split(".")
|
||||
.nth(0)
|
||||
.next()
|
||||
.unwrap()
|
||||
)
|
||||
.unwrap();
|
||||
|
|
@ -363,3 +307,61 @@ fn export(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
|
|||
}
|
||||
write!(out, "</body></html>").unwrap();
|
||||
}
|
||||
|
||||
// Save the kcluster picture
|
||||
// Pre-convert centroids into output format
|
||||
// let centroids = &result
|
||||
// .centroids
|
||||
// .iter()
|
||||
// .map(|x| x.into_format())
|
||||
// .collect::<Vec<Srgb<u8>>>();
|
||||
// let rgb: Vec<Srgb<u8>> = 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<dyn Error>> {
|
||||
// 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(())
|
||||
// }
|
||||
|
|
|
|||
Reference in New Issue