Reference
Here you can find the reference for the user facing API of Pylette. This consists of
the extract_colors function, which is used to extract a color palette from an image,
and the Palette and Color classes, which are used to work with the extracted color palette.
Key Features
- JSON Export: Export palettes to structured JSON format with metadata
- Hex Colors: Access hex color codes through the
Color.hexproperty - Semantic Fields: Export uses semantic field names (rgb, hsv, hls) instead of generic values
- Metadata: Rich metadata including extraction parameters, timing, and image info
- Batch Processing: Process multiple images with parallel execution support
pylette.extract_colors
Extracts a set of 'palette_size' colors from the given image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ImageInput
|
The input image. |
required |
palette_size
|
int
|
The number of colors to extract. |
5
|
resize
|
int | bool | None
|
The sample size. The image is downscaled to |
256
|
mode
|
ExtractionMethod | str
|
The color quantization algorithm to use. |
KM
|
sort_mode
|
Literal['luminance', 'frequency'] | None
|
The mode to sort colors. |
None
|
alpha_mask_threshold
|
int | None
|
Optional integer between 0, 255. Any pixel with alpha less than this threshold will be discarded from calculations. |
None
|
Returns: Palette: A palette of the extracted colors.
Guarantees
The returned palette satisfies these invariants for every extraction
method (pinned by the property suite in tests/integration/test_invariants.py):
len(palette) <= palette_size. Fewer colors are returned when the image has fewer distinct colors than requested.- The color frequencies sum to
1.0. - Every channel of every
Color.rgbis anintin[0, 255]. - Extraction is deterministic: the same image and arguments always produce the same palette.
- Colors are ordered by
sort_mode— ascendingluminanceor, by default, descendingfrequency— and that ordering is stable. - Degenerate inputs (a solid color, a 1x1 image,
palette_sizegreater than the number of distinct colors, a partial alpha mask) are handled without error. The one expected failure is an image with no pixels left to sample (e.g. a fully alpha-masked image), which raises :class:~pylette.NoValidPixelsError.
Raises:
| Type | Description |
|---|---|
InvalidImageError
|
If the image cannot be loaded or its type is unsupported. |
NoValidPixelsError
|
If no pixels remain after alpha masking. |
UnknownExtractionMethodError
|
If |
Examples:
Colors can be extracted from a variety of sources, including local files, byte streams, URLs, and numpy arrays.
>>> extract_colors("path/to/image.jpg", palette_size=5, resize=256, mode="KM", sort_mode="luminance")
>>> extract_colors(b"image_bytes", palette_size=5, resize=None, mode="KM", sort_mode="luminance")
Source code in pylette/src/color_extraction.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
pylette.batch_extract_colors
Extract colors from multiple images in parallel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
progress_callback
|
Callable[[int, BatchResult], None] | None
|
Optional callback function called when each task completes. Receives (task_number, result) as arguments. |
None
|
Source code in pylette/src/color_extraction.py
pylette.Palette
Source code in pylette/src/palette.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
extraction_params: ExtractionParams | None
property
Get the extraction parameters from metadata.
image_info: ImageInfo | None
property
Get the image information from metadata.
image_source: str | None
property
Get the image source from metadata.
processing_stats: ProcessingStats | None
property
Get the processing statistics from metadata.
source_type: SourceType | None
property
Get the source type from metadata.
__init__
Initializes a color palette with a list of Color objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colors
|
list[Color]
|
A list of Color objects. |
required |
Note
For a palette produced by :func:~pylette.extract_colors,
frequencies are the per-color relative weights and sum to 1.0.
Source code in pylette/src/palette.py
dedup
Return a new palette with exactly-equal colors merged (frequencies summed).
Only colorspace-identical colors (same 8-bit RGB) are collapsed; for
perceptual near-duplicates use :meth:merge_similar. The original palette
is left unchanged.
Returns:
| Name | Type | Description |
|---|---|---|
Palette |
Palette
|
A new palette with exact duplicates removed. |
Source code in pylette/src/palette.py
display
Displays the color palette as an image, with an option for saving the image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
w
|
int
|
Width of each color component. |
50
|
h
|
int
|
Height of each color component. |
50
|
save_to_file
|
bool
|
Whether to save the file or not. |
False
|
filename
|
str
|
Filename. |
'color_palette'
|
extension
|
str
|
File extension. |
'jpg'
|
Source code in pylette/src/palette.py
export
Export palette to JSON format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
File to save to (extension will be added automatically if not present). |
required |
colorspace
|
ColorSpace | str
|
Color space to use (enum member, its value, or case-insensitive name). |
RGB
|
include_metadata
|
bool
|
Whether to include metadata. |
True
|
Source code in pylette/src/palette.py
gradient
Return a new palette with interpolated colors bridging consecutive swatches.
Between each consecutive pair of colors, steps_between OKLab-interpolated
colors are inserted, producing a smooth ramp across the whole palette. The
result has equal frequencies summing to 1.0. A palette with fewer than two
colors has nothing to bridge and is returned unchanged. The original palette
is left unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps_between
|
int
|
Colors to insert between each pair (>= 1). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Palette |
Palette
|
A new palette holding the gradient. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in pylette/src/palette.py
harmony
Return a color-harmony scheme seeded from this palette's dominant color.
Seeds from the dominant (highest-frequency) color and delegates to the harmony operation. An empty palette yields an empty palette.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
HarmonyKind | str
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
Palette |
Palette
|
A new palette holding the harmony scheme. |
Raises:
| Type | Description |
|---|---|
InvalidHarmonyError
|
If |
Source code in pylette/src/palette.py
merge_similar
Return a new palette with perceptually similar colors merged.
Colors within delta_e of each other (OKLab ΔE, see
:meth:Color.delta_e) collapse to their frequency-weighted OKLab mean, with
frequencies summed (so the total stays ≈ 1.0). The original palette is left
unchanged. For exact duplicates only, use :meth:dedup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta_e
|
float
|
Non-negative ΔE threshold; larger merges more. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Palette |
Palette
|
A new palette with near-duplicates merged. |
Source code in pylette/src/palette.py
random_color
Returns N random colors from the palette, either using the frequency of each color, or choosing uniformly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N
|
int
|
Number of random colors to return. |
required |
mode
|
str
|
Mode to use for selection. Can be "frequency" or "uniform". |
'frequency'
|
Returns:
| Type | Description |
|---|---|
list[Color]
|
list[Color]: List of N random colors from the palette. |
Source code in pylette/src/palette.py
save
Saves the color palette as an image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
w
|
int
|
Width of each color component. |
50
|
h
|
int
|
Height of each color component. |
50
|
filename
|
str
|
Filename. |
'color_palette'
|
extension
|
str
|
File extension. |
'jpg'
|
Source code in pylette/src/palette.py
sort_perceptual
Return a new palette sorted by perceptual lightness (OKLab L).
Ascending by default (darkest first). The sort is stable and idempotent. The original palette is left unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
descending
|
bool
|
If True, sort lightest first. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Palette |
Palette
|
A new, perceptually sorted palette. |
Source code in pylette/src/palette.py
to_json
Exports the palette to JSON format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | None
|
File to save to. If None, returns the dictionary. |
None
|
colorspace
|
ColorSpace | str
|
Color space to use (enum member, its value, or case-insensitive name). |
RGB
|
include_metadata
|
bool
|
Whether to include palette metadata. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, object] | None
|
dict | None: The palette data as a dictionary if filename is None. |
Source code in pylette/src/palette.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
pylette.Color
A single palette color.
The canonical representation is float sRGB in [0, 1] (plus a float
alpha). 8-bit quantization happens only at the output boundaries
(:attr:rgb, :attr:rgba, :attr:a, :attr:hex), so colors constructed
from continuous centroids keep their precision until they are read out.
Source code in pylette/src/color.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | |
a: int
property
Deprecated alias for :attr:alpha.
alpha: int
property
The alpha channel as a raw 8-bit value (matches :attr:rgba).
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Alpha as a plain Python int in [0, 255]. |
freq: float
property
Deprecated alias for :attr:frequency.
hex: str
property
Returns the color as a hexadecimal string.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The color in hexadecimal format (e.g., "#FF5733"). |
hls: tuple[float, float, float]
property
Converts the color to HLS color space, derived from the canonical float store.
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
tuple[float, float, float]: The color values in HLS color space. |
hsv: tuple[float, float, float]
property
Converts the color to HSV color space, derived from the canonical float store.
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
tuple[float, float, float]: The color values in HSV color space. |
luminance: float
property
Calculates the luminance of the color, derived from the canonical float store.
Returns: float: The luminance of the color, on the same 0-255 scale as the 8-bit channels.
oklab: tuple[float, float, float]
property
Converts the color to the perceptual OKLab color space.
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
tuple[float, float, float]: The |
opacity: float
property
The alpha channel as a fraction (opacity) in [0, 1].
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Opacity in [0, 1]. |
rgb: tuple[int, int, int]
property
The color as 8-bit sRGB.
Returns:
| Type | Description |
|---|---|
tuple[int, int, int]
|
tuple[int, int, int]: (r, g, b) as plain Python ints in [0, 255]. |
rgb_float: tuple[float, float, float]
property
The canonical color as float sRGB components in [0, 1].
Returns:
| Type | Description |
|---|---|
tuple[float, float, float]
|
tuple[float, float, float]: The (r, g, b) components. |
rgba: tuple[int, int, int, int]
property
The color as 8-bit RGBA.
Returns:
| Type | Description |
|---|---|
tuple[int, int, int, int]
|
tuple[int, int, int, int]: (r, g, b, a) as plain Python ints in [0, 255]. |
weight: float
property
Deprecated alias for :attr:opacity.
The name is misleading: in a palette context "weight" reads as relative
importance (frequency), but it holds opacity. Use :attr:opacity.
__init__
Initializes a Color object from 8-bit RGBA values.
The 8-bit input is the quantized view of the color; it is converted to the canonical float store on construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgba
|
tuple[int, ...]
|
A tuple of RGBA values, each in [0, 255]. |
required |
frequency
|
float
|
The frequency of the color. |
required |
Source code in pylette/src/color.py
__lt__
Compares the frequency of this color with another color.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Color
|
The other Color object to compare with. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the frequency of this color is less than the frequency of the other color, False otherwise. |
Source code in pylette/src/color.py
delta_e
Perceptual color difference to other as Euclidean distance in OKLab.
OKLab is built so that straight-line distance approximates perceived difference, so no extra weighting is applied. Symmetric, non-negative, and zero for colors with identical OKLab coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Color
|
The color to compare against. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The OKLab ΔE between the two colors. |
Source code in pylette/src/color.py
display
Displays the color in a window of specified width and height.
Parameters: w (int): Width of the window in pixels. h (int): Height of the window in pixels.
Source code in pylette/src/color.py
from_srgb_float
classmethod
Constructs a Color from float sRGB components in [0, 1].
This is the precision-preserving entry point for extractors whose
centroids live in continuous space (e.g. OKLab); it avoids the round
trip through 8-bit that :meth:__init__ performs. Components are
clamped into [0, 1] so out-of-gamut centroids are handled gracefully.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
srgb
|
tuple[float, float, float]
|
Gamma-encoded sRGB components. |
required |
frequency
|
float
|
The frequency of the color. |
required |
alpha
|
float
|
Alpha in |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Color |
Color
|
A color whose canonical store holds the given floats. |
Source code in pylette/src/color.py
get_colors
Deprecated alias for :meth:to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colorspace
|
ColorSpace | str
|
The color space to use (enum member, its value, or case-insensitive name). |
RGB
|
Returns:
| Type | Description |
|---|---|
tuple[int, ...] | tuple[float, ...]
|
tuple[int, ...] | tuple[float, ...]: The color values in the specified color space. |
Source code in pylette/src/color.py
gradient_to
Return a palette of steps colors interpolated from this color to other.
Interpolation runs in OKLab for a perceptually even ramp and includes both endpoints. The generated colors get equal frequencies summing to 1.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Color
|
The end color of the ramp. |
required |
steps
|
int
|
Total number of colors, including both endpoints (>= 2). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Palette |
Palette
|
A new palette holding the gradient. |
Source code in pylette/src/color.py
harmony
Return a color-harmony scheme generated from this color.
kind is "complementary", "triadic", or "analogous" (a
:class:HarmonyKind member, its value, or case-insensitive name). The
returned palette holds the seed plus its hue-rotated partners with equal
frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
HarmonyKind | str
|
The harmony to generate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Palette |
Palette
|
A new palette holding the harmony scheme. |
Raises:
| Type | Description |
|---|---|
InvalidHarmonyError
|
If |
Source code in pylette/src/color.py
to
Returns the color in the requested color space.
This is the single conversion entry point; get_colors, hsv,
hls, and the OKLab view all route through it, and all space math
lives in :mod:pylette.src.colorspaces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
space
|
ColorSpace | str
|
The target space (enum member, its value,
or case-insensitive name): |
RGB
|
Returns:
| Type | Description |
|---|---|
tuple[int, ...] | tuple[float, ...]
|
tuple[int, ...] | tuple[float, ...]: The color values in that space |
tuple[int, ...] | tuple[float, ...]
|
(RGB as 8-bit ints; the others as floats). |
Source code in pylette/src/color.py
Exceptions
Every error Pylette raises derives from PyletteError, so you can catch any
Pylette-originated failure with a single except pylette.PyletteError and branch
on the concrete subclass to identify the failure mode. Each subclass also derives
from ValueError, so existing except ValueError handlers keep working.