swatchthis
A Rust library for extracting dominant colour swatches from images using k-means clustering. Works in native Rust and WebAssembly.
Features
- K-means and k-means++ centroid initialisation
- RGB and CIELAB colour space clustering
- CIEDE2000 Distance for CIELAB, slower but good perceptual accuracy
- WebAssembly support via
wasm-bindgen(behind thewasmfeature flag) - No runtime dependencies for native builds (deterministic PRNG, no
randcrate)
Usage
Add to your Cargo.toml:
[]
= "0.1"
Extract swatches from raw RGBA pixel data
use ;
use ;
let rgba_data: & = &;
let pixels = pixels_from_rgba;
let swatches = generate_swatches;
for swatch in &swatches
Work with colours directly
use Rgb;
let red = new;
let lab = red.to_lab;
let back = lab.to_rgb;
assert_eq!;
println!; // #ff0000
Lower-level clustering
use Rgb;
use ;
let pixels: = vec!;
let results = extract_colors;
for in &results
WebAssembly
Enable the wasm feature and build with wasm-pack:
The WASM module exposes a generateSwatches function:
import init from './pkg/swatchthis.js';
await ;
const canvas = document.;
const ctx = canvas.;
const imageData = ctx.;
const json = ;
const swatches = JSON.;
// [{ hex: "#ff0000", r: 255, g: 0, b: 0, population: 1234 }, ...]
A demo app is included in demos/web/. Build it with:
&&
Licence
MIT