Now with a palletor

This commit is contained in:
dandaedre 2024-08-29 01:48:32 +02:00
parent e3fb4884b9
commit a8ac428a52
2 changed files with 224 additions and 63 deletions

View File

@ -7,6 +7,7 @@ edition = "2021"
[dependencies]
clap = { version = "4.5.16", features = ["derive"] }
image = "0.25.2"
kmeans_colors = "0.6.0"
palette = "0.7.6"
[profile.dev]

View File

@ -1,10 +1,18 @@
use clap::Parser;
use palette::{FromColor, Hsl, Srgb};
use clap::{Parser, ValueEnum};
use image::{GenericImageView, Pixel};
// 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::Write;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use image::{GenericImageView, Pixel};
use std::collections::HashSet;
use std::path::Path;
@ -19,17 +27,22 @@ struct Cli {
/// Path to export the palette to
#[arg(short, long, value_name = "EXPORT_PATH")]
export: Option<PathBuf>,
// /// Format in which to export the palette (e.g., JSON, XML)
// #[arg(short, long, value_enum, value_name = "FORMAT")]
// format: Option<PaletteFormat>,
/// Type of extraction, full or k-mean-cluster
#[arg(short, long, value_enum, value_name = "MODE")]
mode: Option<ExtractMode>,
/// Max number of colors to extract
#[arg(short, long, value_enum, value_name = "NB_COLORS")]
nb_colors: Option<usize>,
}
// /// Supported export formats for the color palette
// #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
// enum PaletteFormat {
// HTML,
// Md,
// }
/// Supported export formats for the color palette
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum ExtractMode {
Full,
Cluster,
}
/// A color index
struct ColorIndex {
@ -72,6 +85,10 @@ fn main() {
.expect("Couldn't find a place to save the output")
.to_path_buf(),
};
let mode = match cli.mode {
Some(f) => f,
None => ExtractMode::Full,
};
// Display parsed arguments
println!("[INFO] Image Path: {:?}", &cli.image);
@ -79,23 +96,25 @@ fn main() {
// println!("[INFO] Export Format: {:?}", &cli.format);
let mut colorblobs = Vec::with_capacity(cli.image.len());
for image in cli.image {
colorblobs.push(extract_colors(&image));
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);
}
fn export(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
let mut out = File::create(&export_path).expect("Can't open output file");
write!(
out,
r#"<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>"#
).unwrap();
write!(
out,
"Palette: {}",
&export_path
fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>) -> ColorIndex {
let name = format!(
"{}",
image
.file_name()
.unwrap()
.to_str()
@ -103,45 +122,87 @@ fn export(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
.split(".")
.nth(0)
.unwrap()
)
.unwrap();
write!(
out,
r#"</title> <style> body{{background-color: #332f35;
margin: 0;
font-family: "Open Sans","Segoe UI",Tahoma,sans-serif;
padding: 0;
display: grid;
justify-content: center;
align-items: center;
height: 100vh;
}}
.custom-div {{ display: flex;
flex-wrap: wrap;
flex-grow: 0;
padding: 5px;
background: #27232a;
text-align: center;
margin: 10px 0 20px;
}}
h1 {{
text-transform: uppercase;
color: #eaeaea;
}}
</style></head><body>
"#
)
.unwrap();
for blob in color_vec {
write!(out, "<h1>{}</h1>", blob.name).unwrap();
write!(out, "<div class='custom-div'>").unwrap();
for v in blob.colors {
let c = if v.luma < 60 { "FFFFFF" } else { "000000" };
write!(out," <div class='color' style='background:{}; color: #{}; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'> \n {} \n</div>",v.rgb_string(),c,v.rgb_string()).expect("Can't write color in the output");
);
let runs = 8;
let nb_colors = match nb_colors {
Some(c) => c,
None => 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<Srgb<f32>> = Vec::new();
// Open the image
let img = image::open(image_path)
.expect("Couldn't open image")
.into_rgba8();
let img_vec: &[Srgba<u8>] = 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::<f32>::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 as usize,
max_iter,
converge,
verbose,
&rgb_pixels,
seed + i as u64,
);
if run_result.score < result.score {
result = run_result;
}
write!(out, "</div>").unwrap();
}
write!(out, "</body></html>").unwrap();
// 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);
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::<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 {
@ -203,3 +264,102 @@ 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>) {
// 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#"<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>"#
).unwrap();
write!(
out,
"Palette: {}",
&export_path
.file_name()
.unwrap()
.to_str()
.unwrap()
.split(".")
.nth(0)
.unwrap()
)
.unwrap();
write!(
out,
r#"</title> <style> body{{background-color: #332f35;
margin: 0;
font-family: "Open Sans","Segoe UI",Tahoma,sans-serif;
padding: 0;
display: grid;
justify-content: center;
align-items: center;
height: 100vh;
}}
.custom-div {{ display: flex;
flex-wrap: wrap;
flex-grow: 0;
padding: 5px;
background: #27232a;
text-align: center;
margin: 10px 0 20px;
}}
h1 {{
text-transform: uppercase;
color: #eaeaea;
}}
</style></head><body>
"#
)
.unwrap();
for blob in color_vec {
write!(out, "<h1>{}</h1>", blob.name).unwrap();
write!(out, "<div class='custom-div'>").unwrap();
for v in blob.colors {
let c = if v.luma < 60 { "FFFFFF" } else { "000000" };
write!(out," <div class='color' style='background:{}; color: #{}; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'> \n {} \n</div>",v.rgb_string(),c,v.rgb_string()).expect("Can't write color in the output");
}
write!(out, "</div>").unwrap();
}
write!(out, "</body></html>").unwrap();
}