pixelization/
pixelizer.rs

1extern crate image;
2use image::DynamicImage;
3use thiserror::Error;
4use rand::Rng;
5
6/// Defines how the image should be cropped when scaling.
7pub enum CropMethod{
8    /// No Crop
9    NoCrop,
10    /// Crop the center to match the target aspect ratio.
11    CropEqual,
12    /// Crop a random portion of the image.
13    CropRandom
14}
15
16/// Helper function to scale an image to a specific size with cropping options.
17/// Returns the new image and the effective dimensions.
18pub fn scale_to_size<'a>(img: DynamicImage, scale: &u32, crop: CropMethod) -> (DynamicImage, (u32, u32)){
19    let (w, h) = (img.width()/scale, img.height()/scale);
20    match crop {
21        CropMethod::NoCrop => (img, (w, h)),
22        CropMethod::CropEqual => {
23            let (new_w, new_h) = (w*scale, h*scale);
24            let left = (img.width() - new_w) / 2;
25            let top = (img.height() - new_h) / 2;
26            (img.crop_imm(left, top, new_w, new_h), (w, h))
27        },
28        CropMethod::CropRandom => {
29            let mut rng = rand::thread_rng();
30            let (new_w, new_h) = (w*scale, h*scale);
31            let left = rng.gen_range(0..(img.width() - new_w));
32            let top = rng.gen_range(0..(img.height() - new_h));
33            (img.crop_imm(left, top, new_w, new_h), (w, h))
34        }
35    }
36}
37
38/// The color space used for calculating distances between colors for K-means pixelization.
39#[derive(Debug, Clone, Copy)]
40pub enum ColorType {
41    /// Standard RGB space.
42    Rgb,
43    /// CIELAB color space.
44    Lab
45}
46
47/// Errors that can occur during the pixelization process.
48#[derive(Debug, Error)]
49pub enum PixelizationError {
50    #[error("Dimension error: {0}")]
51    DimensionError(String),
52    #[error("Color error: {0}")]
53    ColorError(String),
54}
55
56/// The main trait for any pixelization algorithm.
57pub trait Pixelizer{
58    /// Transforms the input image into a pixelated version.
59    ///
60    /// # Arguments
61    /// * `img` - The source image.
62    /// * `width` - Target width of the pixel grid.
63    /// * `height` - Target height of the pixel grid.
64    /// * `num_colors` - The maximum number of colors (palette size) to use.
65    fn pixelize(&self, img: &DynamicImage, width : u32, height: u32,  num_colors : usize) -> Result<DynamicImage, PixelizationError>;
66}
67
68pub mod kmeans_pixelizer;
69pub mod pia;