#color-palette #color #palette #quantization #image #mmcq

palette_extract

A Rust port of Leptonica's modified media cut quantization algorithm

1 unstable release

0.1.0 Mar 6, 2022

#900 in Images

Download history 25/week @ 2024-03-11 32/week @ 2024-03-18 7/week @ 2024-03-25 51/week @ 2024-04-01 37/week @ 2024-04-08 114/week @ 2024-04-15 89/week @ 2024-04-22 31/week @ 2024-04-29 24/week @ 2024-05-06 28/week @ 2024-05-13 59/week @ 2024-05-20 23/week @ 2024-05-27 34/week @ 2024-06-03 47/week @ 2024-06-10 25/week @ 2024-06-17 14/week @ 2024-06-24

122 downloads per month

MIT license

705KB
627 lines

palette-extract-rs

A Rust lib for extracting a color palette from an image!

Based on a port of Leptonica's modified median cut quantization algorithm.

Example

drawing[^1]

color1 color2 color3 color4 color5 color6 color7 color8 color9

[^1]: Image credit: João Pacheco

Credits

This Rust implementation of modified median cut quantization (MMCQ) is adapted from Kazuki Ohara's ColorThiefSwift.

Special thanks

Installation

To use, add the following to Cargo.toml under [dependencies]:

palette_extract = "0.1.0"

Usage

Using the library consists of calling get_palette_rgb or get_palette_with_options with a set of RGB or RGBA pixels represented as a u8 slice.

Basic

A minimal example using 4 red pixels represented in RGB looks like this:

use palette_extract::{get_palette_rgb, Color};

fn main() {
    let pixels: [u8; 12] = [255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0];

    let r = get_palette_rgb(&pixels);

    assert_eq!(r.len(), 1);
    assert_eq!(r[0], Color::new(252, 4, 4));
}

Image from file/somewhere else

Here's one way to extract the color palette of an image by leveraging the image crate to read and decode an image file (see full working example in examples directory):

    let image_path = "./path/to/image.jpg";

    // open and decode the image using the `image` crate
    let img = image::open(image_path).unwrap();

    // grab a reference to the underlying pixels/RGB buffer
    let pixels = img.as_bytes();

    // extract the color palette
    let palette = get_palette_rgb(&pixels);

    // output the extracted color palette
    palette.iter().for_each(|x| println!("{:?}", x));

More usage examples can be found in the examples directory!

Background/Further reading

No runtime deps