Splitting into files

This commit is contained in:
Dandaedre 2024-09-06 16:52:46 +02:00
parent c816ab9566
commit f58997b479
4 changed files with 361 additions and 322 deletions

142
src/image_functions.rs Normal file
View File

@ -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<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,
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<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));
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>>();
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(),
)
}

View File

@ -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<usize>,
}
/// 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<usize>,
/// A color index
struct ColorIndex {
name: String,
colors: Vec<RichColor>,
}
impl ColorIndex {
fn new(name: String, colors: Vec<RichColor>) -> 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::<Vec<ColorIndex>>();
println!("Done in {}", HumanDuration(started.elapsed()));
export(export_path, colorblobs);
}
fn extract_kcluster(image: &PathBuf, nb_colors: Option<usize>, 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<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,
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<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>>();
ColorIndex::new(name, colors)
export_html(export_path, colorblobs);
}
fn extract_colors(image_path: &PathBuf, nb_colors: Option<usize>, 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<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(".")
.next()
.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();
}
// 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(())
// }

40
src/structs.rs Normal file
View File

@ -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<RichColor>,
}
impl ColorIndex {
pub(crate) fn new(name: String, colors: Vec<RichColor>) -> 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 }
}
}

145
src/utilities.rs Normal file
View File

@ -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<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(".")
.next()
.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();
}
// 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(())
// }