Skip to main content

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

Project description

Color Extract

PyPI version Python Support License: MIT

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

Example A Example B Example C

Features

Extraction Methods

  • Original K-Means: Standard clustering approach
  • LAB Enhanced: Perceptually uniform color space (default)
  • Aggressive Weighting: Emphasizes vibrant colors
  • Vibrant Separate: Separate clustering for vibrant and base colors
  • Multi-stage: Extract vibrant colors first, then distinct base colors

Sorting

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

Installation

pip install 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 --colors 8 --method vibrant

Compare all methods:

color-extract image.jpg --method all --output comparison.png

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
  --no-plot            Disable plot generation (console output only)
  --sort               Color sorting: (default: x-axis)
  --max-dimension      Max dimension for downscaling (default: 64)
  --dpi                DPI for output plots (default: 150)

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')

TouchDesigner Integration

# In TouchDesigner, use with TOP operators
import color_extract

def extract_from_top(top):
    # Get pixels from TOP (TouchDesigner returns 0-1 range)
    pixels = top.numpyArray(delayed=True)

    # Convert to 0-255 range
    img_array = color_extract.normalize_image_array(
        pixels,
        input_range=(0, 1),
        output_range=(0, 255)
    )

    # Extract colors
    colors = color_extract.extract_colors(img_array, method='lab')

    # Convert to hex for use in TouchDesigner
    hex_colors = [color_extract.rgb_to_hex(c) for c in colors]

    return hex_colors

API Reference

Main Functions

extract_colors(image, method='lab', n_colors=6, sort_by='x-axis')

Main convenience function for color extraction.

Parameters:

  • image: File path (str) or numpy array (H, W, 3)
  • method: Extraction method name
  • n_colors: Number of colors to extract
  • sort_by: Sorting method ('x-axis', 'y-axis', 'frequency')

Returns:

  • List of RGB tuples

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)

Utility Functions

# Color conversion
hex_color = rgb_to_hex((255, 128, 0))  # Returns '#ff8000'
rgb = hex_to_rgb('#ff8000')  # Returns (255, 128, 0)

# Spatial sorting
sorted_colors = sort_colors_by_spatial_position(img_array, colors, axis='x')

# Calculate statistics
stats = calculate_color_statistics(img_array, colors)

# Normalize arrays (useful for TouchDesigner)
normalized = normalize_image_array(array, input_range=(0, 1), output_range=(0, 255))

Visualization Functions

# Plot single result
fig = plot_single_result(img, img_array, colors, 'Method Name', 'output.png')

# Compare multiple methods
algorithms_dict = {
    'Method 1': colors1,
    'Method 2': colors2
}
fig = plot_comparison(img, img_array, algorithms_dict, 'comparison.png')

# Create simple palette image
palette_array = create_color_palette_image(colors, width=100, height=100)

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.1.tar.gz (14.4 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.1-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for color_extract-0.0.1.tar.gz
Algorithm Hash digest
SHA256 2a0f2b50176df885438013ea922420dcb711fabacaff08f12a6939611a3b5a75
MD5 9f2916be12fe2810e72dc13f4fdf6426
BLAKE2b-256 8ab243652bedd5825315cddd3ca48da4b615fe97b70a69a2ff0fc054dca9d391

See more details on using hashes here.

Provenance

The following attestation bundles were made for color_extract-0.0.1.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.1-py3-none-any.whl.

File metadata

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

File hashes

Hashes for color_extract-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6296a6f496dabec2194a9bca7f3f4e1e16d17c4cb25f2c7db41391996eb74f1f
MD5 425e88c3b60d13cf7ab811564ed4dc4c
BLAKE2b-256 f72c97ef3710e34b84686d2f265364e43b9b0b7dcc81a13bbe07fffc3ec2649c

See more details on using hashes here.

Provenance

The following attestation bundles were made for color_extract-0.0.1-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