swatchthis
A Rust library for extracting dominant colour swatches from images. Works in native Rust and WebAssembly.
[demo]
Features
- Three palette algorithms: k-means (with k-means++ init), octree quantisation, and median cut
- RGB and CIELAB colour space clustering
- CIEDE2000 distance for CIELAB, slower but good perceptual accuracy
- Superpixel preprocessors: SLIC and SEEDS, for reducing an image to region-averaged colours before palette extraction
- 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.2"
Extract swatches with k-means
use ;
use ;
let rgba_data: & = &;
let pixels = pixels_from_rgba;
let swatches = generate_swatches_kmeans;
for swatch in &swatches
Octree quantisation
use ;
use ;
let pixels = pixels_from_rgba;
let swatches = generate_swatches_octree;
Median cut
use ;
let pixels = pixels_from_rgba;
let swatches = generate_swatches_median_cut;
Superpixel preprocessing
For photographic images, reducing pixels to superpixel averages first can produce cleaner palettes. The output of either preprocessor can be passed straight to any of the palette functions above.
use ;
use ;
use ;
let pixels = pixels_from_rgba;
// SLIC: num_superpixels, compactness (10–40 typical)
let regions = slic_preprocess;
// or SEEDS: num_superpixels, num_levels (3–5), histogram_bins (~5)
// let regions = seeds::seeds_preprocess(&pixels, width, height, 200, 4, 5);
let swatches = generate_swatches_kmeans;
Work with colours directly
use Rgb;
let red = new;
let lab = red.to_lab;
let back = lab.to_rgb;
assert_eq!;
println!; // #ff0000
WebAssembly
CDN (jsdelivr)
Use the pre-built WASM files directly from jsdelivr — pin to a specific version:
import init from 'https://cdn.jsdelivr.net/gh/OwenElliottDev/swatchthis@wasm-0.2.0/swatchthis.js';
await ;
const canvas = document.;
const ctx = canvas.;
const imageData = ctx.;
// k-means: (rgba, count, colorSpace, initMethod, seed)
// colorSpace: "rgb" | "lab" | "lab-ciede2000"
// initMethod: "kmeans++" | "random"
const json = ;
const swatches = JSON.;
// [{ hex: "#ff0000", r: 255, g: 0, b: 0, population: 1234 }, ...]
// octree: (rgba, count, colorSpace, maxDepth)
const octreeJson = ;
// median cut: (rgba, count)
const medianJson = ;
// SLIC preprocess: returns RGBA bytes of region-averaged pixels
const slicRgba = ;
// SEEDS preprocess
const seedsRgba = ;
// Complementary colour: returns [r, g, b]
const = ;
Build from source
A demo app is included in demos/web_image/. Build it with:
&&
Licence
MIT