Skip to main content

Extract dominant colors from images using various K-Means clustering approaches

Project description

color-extract

PyPI version Python Support

A toolkit to extract dominant colors from images using various K-Means clustering approaches.

Example
colors_Additional_073_all_6

Features

Extraction Methods

  • Original K-Means: Standard K-Means clustering approach
  • Aggressive Weighting: K-Means with aggressive saturation weighting to emphasize vibrant colors
  • Vibrant Separate: Separate clustering for vibrant minority colors and base colors
  • LAB Enhanced: LAB color space with saturation-weighted sampling for perceptually uniform clustering
  • Multi-stage: Multi-stage extraction: vibrant colors first, then distinct base colors

Sorting

  • Spatial sorting (left-to-right or top-to-bottom)
  • Frequency-based sorting

Installation

With pip:

pip install color-extract

Or with uv:

uv add color-extract

Command Line Usage

# Basic extraction with default settings
color-extract image.jpg

# Extract 8 colors using the vibrant method
color-extract image.jpg -c 8 -m vibrant

# Compare all methods and define output folder
color-extract image.jpg -m all -o ./myfolder

CLI Options

usage: color-extract [options] image

Arguments:
  image                Path to the input image

Options:
  -h, --help           Show help message
  --colors, -c         Number of colors to extract (default: 6)
  --method, -m         Extraction method (default: lab)
  --output, -o         Output file path (default: ./output)
  --sort, -s           Sorting method: (default: frequency)
  --weights, -w        Show color weights (default: False)
  --no-plot            Disable plot generation
  --max-dimension      Max dimension for downscaling (default: 64)
  --dpi                DPI for output plots (default: 150)

Output Examples

Console

┌─────────────────────────────────────┐
│ LAB Enhanced                        │
└─────────────────────────────────────┘
┌───────┬──────────┬──────────────────┐
│  ■■■  │ #277595  │ (39, 117, 149)   │
│  ■■■  │ #68b2c6  │ (104, 178, 198)  │
│  ■■■  │ #6c6963  │ (108, 105, 99)   │
│  ■■■  │ #394d4d  │ (57, 77, 77)     │
│  ■■■  │ #782722  │ (120, 39, 34)    │
│  ■■■  │ #102937  │ (16, 41, 55)     │
└───────┴──────────┴──────────────────┘
Result saved to output/colors_image_lab_6.png

Plotted Images

Aggressive Weighting LAB Enhanced
colors_OilDrums_aggressive_6 colors_Additional_847_lab_6
Multi-stage K-Means
colors_Additional_1974_multistage_6 colors_Additional_0966_kmeans_6

Python API Usage

import color_extract
import numpy as np
from PIL import Image

# Simple extraction from file
colors = color_extract.extract_colors('image.jpg', method='lab', n_colors=5)
for color in colors:
    print(color_extract.rgb_to_hex(color))

# Use with numpy array
img = Image.open('image.jpg')
img_array = np.array(img)
colors = color_extract.extract_colors(img_array, method='aggressive')

# Advanced usage with visualization
from color_extract import plot_single_result, load_and_prepare_image

img, img_array = load_and_prepare_image('image.jpg')
colors = color_extract.extract_colors_lab_enhanced(img_array, n_colors=6)
sorted_colors = color_extract.sort_colors_by_spatial_position(img_array, colors)

# Generate visualization
plot_single_result(img, img_array, sorted_colors, 'LAB Enhanced', 'output.png')

API Reference

Main Functions

Main convenience function for color extraction.

colors = extract_colors(image, method='lab', n_colors=6, sort_by='frequency', weights=False)

# Parameters:
# - image: File path (str) or numpy array (H, W, 3)
# - method: Extraction method name ('kmeans', 'aggressive', 'vibrant', 'lab', 'multstage')
# - n_colors: Number of colors to extract
# - sort_by: Sorting method ('x-axis', 'y-axis', 'frequency')
# - weights: If True, also return each color's weight (its share of the image)

# Returns:
# - List of RGB tuples (default)
# - If weights=True: list of dicts in the same order, with weights summing to ~1.0:
#   [{'rgb': (r, g, b), 'hex': '#rrggbb', 'lab': (L, a, b), 'weight': <float 0-1>}, ...]

# Get colors with their weights
result = extract_colors('image.jpg', weights=True)
for item in result:
    print(item['hex'], item['rgb'], item['lab'], item['weight'])

Individual Extraction Methods

Each method can be used directly for more control:

# Original K-Means
colors = extract_colors_kmeans_original(img_array, n_colors=6)

# LAB color space
colors = extract_colors_lab_enhanced(img_array, n_colors=6, saturation_boost=5.0)

# Aggressive saturation weighting
colors = extract_colors_weighted_aggressive(img_array, n_colors=6, saturation_boost=10.0)

# Separate vibrant colors
colors = extract_colors_vibrant_separate(img_array, n_colors=6, n_vibrant=3)

# Multi-stage extraction
colors = extract_colors_multistage(img_array, n_colors=6)

Further Reading

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

color_extract-0.0.5.tar.gz (16.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

color_extract-0.0.5-py3-none-any.whl (16.2 kB view details)

Uploaded Python 3

File details

Details for the file color_extract-0.0.5.tar.gz.

File metadata

  • Download URL: color_extract-0.0.5.tar.gz
  • Upload date:
  • Size: 16.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for color_extract-0.0.5.tar.gz
Algorithm Hash digest
SHA256 5b1bd25efc9217aa65c137af1a9fa81f3d89e8992e622dcb3284aa86e9cc74fe
MD5 5b6014766839186ec573daf0dbceea19
BLAKE2b-256 4386fc105a64790781ac00a6da89345b2f8e7b5d07f14625549d397ea0505ae7

See more details on using hashes here.

Provenance

The following attestation bundles were made for color_extract-0.0.5.tar.gz:

Publisher: publish.yml on brunoimbrizi/color-extract

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file color_extract-0.0.5-py3-none-any.whl.

File metadata

  • Download URL: color_extract-0.0.5-py3-none-any.whl
  • Upload date:
  • Size: 16.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for color_extract-0.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 2a1e1886d4d017c5ee47e963c7c082040f827e2bf3088811e1d7b6f395f94513
MD5 50c83bfb60191e684def38f272b44658
BLAKE2b-256 121aae73ad3e09a0f6b34e1b40ac8a9a239fe8c474fc3c31fee02183fc3dc0b3

See more details on using hashes here.

Provenance

The following attestation bundles were made for color_extract-0.0.5-py3-none-any.whl:

Publisher: publish.yml on brunoimbrizi/color-extract

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page