4 releases (2 breaking)
Uses new Rust 2024
| 0.3.0 | Apr 19, 2026 |
|---|---|
| 0.2.0 | Mar 28, 2026 |
| 0.1.1 | Mar 27, 2026 |
| 0.1.0 | Mar 27, 2026 |
#15 in #k-means
7MB
326 lines
dominant-color
A Rust library to extract the most dominant color from an image using K-Means clustering and silhouette scoring.
Overview
This library calculates the dominant color of an image by:
- Resizing the image for performance.
- Running K-Means clustering across a range of possible cluster counts ($K$).
- Using the silhouette score to find the optimal number of clusters.
- Selecting the cluster centroid with the highest saturation as the dominant color.
Usage
Simple Example
use dominant_color_rs::{Settings, dominant_color};
fn main() {
let img = image::open("path/to/image.jpg").expect("Failed to open image");
// Use default settings
let settings = Settings::default();
if let Some(color) = dominant_color(&img, &settings) {
println!("Dominant color (RGB 0.0-1.0): {:?}", color);
println!(
"Dominant color (RGB 0-255): [{}, {}, {}]",
(color[0] * 255.0).round() as u8,
(color[1] * 255.0).round() as u8,
(color[2] * 255.0).round() as u8
);
}
}
Custom Settings
You can tune the performance and accuracy by modifying the Settings struct:
use dominant_color_rs::{Settings, KMeansInit, ColorSpace};
let settings = Settings {
img_size: 128, // Internal resize dimension (default: 72)
clusters: 2..=10, // Range of K values to test (default: 2..=6)
max_iters: 200, // Max iterations for K-Means (default: 100)
eps: 1e-7, // Convergence threshold (default: 1e-6)
init: KMeansInit::KMeansPlusPlus, // Initialization method (default: KMeansPlusPlus)
color_space: ColorSpace::Oklab, // Perceptually uniform clustering (default: Oklab)
};
Color Spaces:
ColorSpace::Oklab(Default): Clusters colors in a perceptually uniform space.ColorSpace::Rgb: Raw sRGB space clustering. Slightly faster but not perceptually accurate.
Examples
The library comes with several built-in examples. You can run them using cargo run --example:
extract_dominant: Extract dominant color from a single image.cargo run --example extract_dominant path/to/image.jpgextract_directory: Process all images in a directory.cargo run --example extract_directory ./testimgegui_viewer: Interactive GUI viewer to explore the impact of settings on the resulting dominant colors.cargo run --example egui_viewerbenchmark: Compare the performance and stability between K-Means initialization methods and clustering color spaces (RGB vs Oklab).cargo run --release --example benchmark
License
MIT