Choosing a method for `Image.dominant_color/2`
mainThe Image.dominant_color/2 function supports two different methods for extracting dominant colors, each with different performance and quality characteristics:
:histogram(Default)- How it works: Uses a coarse 3D RGB histogram via
vips_hist_find_ndimto return the centers of the most populated bins. - Performance: Extremely fast (two to three orders of magnitude faster than
:imagequant). It scales well with image size and its cost barely increases with the number of colors requested (top_n). - Best for: Hot paths, bulk processing, or simple questions like "what is the overall dominant color?"
- Output: Colors are quantized to the centers of a fixed 3D grid.
- How it works: Uses a coarse 3D RGB histogram via
:imagequant- How it works: Routes through
vips_gifsave_bufferto runlibimagequant, creating a quantized Global Color Table (GCT). The GCT is then parsed into RGB tuples ordered by perceptual importance. - Performance: Significantly slower. The cost scales with both pixel count and the number of colors requested (
top_n). - Best for: High-quality color extraction where palette quality matters more than latency (e.g., building UI swatches or accents from photographs).
- Output: Perceptually representative colors.
- How it works: Routes through
Optimizing :imagequant with :effort
You can control the quantization quality/speed using the :effort option. On larger images, dropping from the default effort: 7 to effort: 3 can cut runtime by approximately 5× with minimal perceived quality loss.
# Example usage (conceptual)
Image.dominant_color(image, :histogram, top_n: 5)
Image.dominant_color(image, :imagequant, top_n: 5, effort: 3)