Skip to main content

Pylette [WIP]

PyPI version Downloads

A color palette extractor written in Python using KMeans clustering.

Motivation

Working with computer graphics and visualizations, one often needs a way of specifying a set of colors with a certain visual appeal. Such a set of colors is often called a color palette. The aim of this library is to easily extract a set of colors from a supplied image, with support for the various color modes (RGB, RGBa, HSV, etc). Dabbling in generative art, the need often arises for being able to pick colors at random from a palette. Pylette supports this, both picking colors uniformly, but also using the color frequency from the original image as probabilities.

  1. Color Thief: Extraction of color palettes using the median cut algorithm.
  2. Palettable: Generation of matplotlib compatible color schemes
  3. Colorgram: Extraction of colors from images (similar to the intended use of this library), however, I was unable to install this.

Installation

Pylette is available in the python package index (PyPi), and can be installed using pip:

pip install Pylette

Basic usage

A Palette object is created by calling the extract_colors function.

from Pylette import extract_colors

palette = extract_colors('image.jpg', palette_size=10, resize=True)
palette = extract_colors('image.jpg', palette_size=10, resize=True, mode='MC', sort_mode='luminance')

This yields a palette of ten colors, and the resize flag tells Pylette to resize the image to a more manageable size before beginning color extraction. This significantly speeds up the extraction, but reduces the faithfulness of the color palette. One can choose between color quantization using K-Means (default) or Median-Cut algorithms, by setting in the mode-parameter. One can also specify to alternatively sort the color palette by the luminance (percieved brightness).

The palette object supports indexing and iteration, and the colors are sorted from highest to lowest frequency by default. E.g, the following snippet will fetch the most common, and least common color in the picture if the palette was sorted by frequency, or the darkest to lightest color if sorted by luminance:

most_common_color = palette[0]
least_common_color = palette[-1]
three_most_common_colors = palette[:3]

As seen, slicing is also supported.

The Palette object contains a list of Color objects, which contains a representation of the color in various color modes, with RGB being the default. Accessing the color attributes is easy:

color = palette[0]

print(color.rgb)
print(color.hls)
print(color.hsv)

To display the extracted color palette, simply call the display-method, which optionally takes a flag for saving the palette to an image file. The palette can be dumped to a CSV-file as well, where each row represents the RGB values and the corresponding color frequency (optional).

palette.display(save_to_file=False)
palette.to_csv(filename='color_palette.csv', frequency=True)

In order to pick colors from the palette at random, Pylette offers the random_color-method, which supports both drawing uniformly, and from the original color distribution, given by the frequencies of the extracted colors:

random_color = palette.random_color(N=1, mode='uniform')
random_colors = palette.random_color(N=100, mode='frequency')

Example Palettes

A selection of example palettes. Each palette is sorted by luminance (percieved brightness). The top row corresponds to extraction using K-Means, and the bottom row corresponds to Median-Cut extraction.

Original Image Extracted Palette

Command Line Tool

The new version of Pylette also comes bundled with a command line tool, which can be used to extract color palettes from the command line.

usage: pylette [-h] [--mode {KM,MC}] [--n N] [--sort_by {luminance,frequency}]
               [--stdout STDOUT] [--colorspace {rgb,hsv,hls}]
               [--out_filename OUT_FILENAME] [--display-colors DISPLAY_COLORS]
               filename

positional arguments:
  filename              path to image file

optional arguments:
  -h, --help            show this help message and exit
  --mode {KM,MC}        extraction_mode (KMeans/MedianCut (default: KM)
  --n N                 the number of colors to extract (default: 5)
  --sort_by {luminance,frequency}
                        sort by luminance or frequency (default: luminance)
  --stdout STDOUT       whether to display the extracted color values in the
                        stdout (default: True)
  --colorspace {rgb,hsv,hls}
                        color space to represent colors in (default: RGB)
  --out_filename OUT_FILENAME
                        where to save the csv file (default: None)
  --display-colors DISPLAY_COLORS
                        Open a window displaying the extracted palette
                        (default: False)

Pylette GUI

Pylette now comes bundled with a barebones graphical user interface, using PyQt5 as the backend. From the command line, the GUI can be accessed by running

pylette_gui

opens the interface. Import an image by clicking

File -> Open Image

select the number of colors, and hit "Extract Colors". Hover over each extracted color to see the corresponding RGB values.

In future versions, automatic copy of hex-values to clipboard, and additional options for the extraction will be available in the GUI menus.

Under the hood

Currently, Pylette uses KMeans for the color quantization. There are plans for implementing other color quantization schemes, like:

  1. Median-cut [Implemented]
  2. Octree
  3. Modified minmax

The article Improving the Performance of K-Means for Color Quantization gives a nice overview of available methods.

Feedback

Any feedback and suggestions is much appreciated. This is very much a work in progress.

Metadata

Release files for pylette-windows 3.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pylette-windows 3.0.0
File Size Uploaded Provenance Actions
pylette-windows-3.0.0.tar.gz 13.4 kB Without provenance Details for pylette-windows-3.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pylette-windows 3.0.0
File Interpreter ABI Platform Actions
pylette_windows-3.0.0-py3-none-any.whl Python 3 none any Details for pylette_windows-3.0.0-py3-none-any.whl

Total release size: 25.7 kB

Release files / pylette-windows-3.0.0.tar.gz

Download URL pylette-windows-3.0.0.tar.gz
Size 13.4 kB
Tags Source
SHA-256 checksum
How to use checksums
6e0158238558fcd337f8ee02a4175a3582dc3202fa443b80551420366bec6e02
BLAKE2b-256 checksum
How to use checksums
b057069c3a13dbb35da13f412df30f42c5bc51405383ad03228bb74f1b91a4e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.4

Release files / pylette_windows-3.0.0-py3-none-any.whl

Download URL pylette_windows-3.0.0-py3-none-any.whl
Size 12.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
230e476cea6ee0f4f98a39b1fb319d42214c64bd236ab93f3f16ac6b4e1b4cd8
BLAKE2b-256 checksum
How to use checksums
b3c041e759218a9d339768a7d27770b75deab5d9b71ee5207499a022167ed184
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.4

Security for pylette-windows 3.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page