Colorthief

0.2.1 · active · verified Thu Apr 16

Colorthief is a minimalistic Python module (version 0.2.1) for extracting the dominant color or a representative color palette from an image. It relies on the Pillow library for image processing and uses a modified median cut quantization algorithm. While it hasn't seen recent updates, it remains functional for basic color extraction tasks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `ColorThief` object from an image file, extract its dominant color, and generate a color palette. It includes an example of creating a dummy image for easy testing.

import os

# NOTE: Pillow is a required dependency for colorthief.
# Ensure it's installed: pip install Pillow

try:
    from PIL import Image
    from colorthief import ColorThief

    # Create a dummy image for demonstration if it doesn't exist
    # In a real scenario, replace 'temp_image.png' with your image file path.
    dummy_image_path = "temp_image.png"
    if not os.path.exists(dummy_image_path):
        # Create a simple image with a dominant red color
        img = Image.new('RGB', (100, 100), color = 'red')
        img.save(dummy_image_path)
        print(f"Created a dummy image: {dummy_image_path}")

    # Initialize ColorThief with your image file path
    color_thief = ColorThief(dummy_image_path)

    # Get the dominant color (RGB tuple)
    # quality=1 provides the highest quality but is slower.
    dominant_color = color_thief.get_color(quality=1)
    print(f"Dominant color (RGB): {dominant_color}")

    # Get a color palette (list of RGB tuples)
    # color_count: desired number of colors in the palette
    # quality: higher numbers are faster but lower quality
    palette = color_thief.get_palette(color_count=6, quality=10)
    print(f"Color palette (RGB): {palette}")

    # To clean up the dummy image after use:
    # os.remove(dummy_image_path)

except ImportError as e:
    if "Pillow" in str(e):
        print("Error: Pillow is not installed. Please install it with 'pip install Pillow'.")
    else:
        print(f"An import error occurred: {e}")
except FileNotFoundError:
    print(f"Error: The image file '{dummy_image_path}' was not found.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →