Color Tools API Reference

Version: 7.1.2

Welcome to the Color Tools API documentation! This library provides comprehensive color science tools for accurate color space conversions, perceptual color distance metrics, and color matching.

🎨 Three Ways to Use Color Tools:

  1. As a library: from color_tools import rgb_to_lab

  2. As a CLI tool: python -m color_tools color --name coral

  3. As installed command: color-tools filament --list-makers (needs pip install)

Quick Start

from color_tools import rgb_to_lab, delta_e_2000, Palette

# Convert RGB to LAB
lab = rgb_to_lab((255, 128, 64))

# Find nearest CSS color
palette = Palette.load_default()
nearest, distance = palette.nearest_color(lab)
print(f"Nearest color: {nearest.name}")

Documentation

For comprehensive guides and CLI usage:

CLI Commands

The CLI provides eight commands:

  • color - Search CSS colors by name or find nearest color

  • harmony - Generate styled LCH color harmonies

  • filament - Search 3D printing filaments with filtering (maker, type, finish)

  • convert - Convert between color spaces and check gamut

  • name - Generate descriptive names for RGB colors

  • validate - Validate if hex codes match color names (fuzzy matching + Delta E)

    • Optional: Install [fuzzy] extra for improved fuzzy matching: pip install color-match-tools[fuzzy]

  • cvd - Color vision deficiency simulation and correction

  • image - Image color analysis and manipulation

    • Requires: Install [image] extra: pip install color-match-tools[image]

See the Usage Guide for detailed CLI examples.

Selected Data Models

The library uses typed dataclasses and models to represent colors, filaments, export configuration, and results. Record and result types are immutable where their contracts require it; export metadata and option objects remain mutable.

  • ColorRecord - CSS colors with precomputed values in all color spaces

  • ColorLoadEvent / ColorLoadReport - Structured user-color merge changes and counts

  • FilamentRecord - 3D printing filaments retaining source RGB components and an effective color

  • FilamentFilterCriteria - Reusable maker, type, finish, color, and TD filters

  • HarmonyColor / HarmonyResult - Ideal and displayable LCH harmony results

  • ColorValidationRecord - Color name/hex validation results with fuzzy matching

  • PaletteMetadata / PaletteExportData - Palette-level export metadata and ordered colors

  • HexExportOptions / HueForgeExportOptions - Typed per-export behavior

  • UserColorExportPlan / UserColorExportResult - Stateful user-color merge planning and apply results

  • UserFilamentExportPlan / UserFilamentExportResult - ID-based user-filament merge planning and apply results

  • ColorCluster - Image color clusters from k-means analysis (requires [image] extra)

  • ColorChange - Luminance redistribution results for HueForge (requires [image] extra)

The module pages below are the authoritative class and function inventory. See the Usage Guide for a quick reference table.

Core API Reference

Public Package API

The package root contains the supported convenience imports intended for most library users. The owning module pages below provide the detailed API grouped by responsibility.

Color Science

color_tools.conversions

Color space conversion functions.

color_tools.distance

Color distance metrics for measuring perceptual color differences.

color_tools.gamut

Gamut checking and mapping for sRGB color space.

color_tools.harmony

Generate color harmonies in CIE LCH space.

color_tools.constants

Immutable color science constants from international standards.

color_tools.matrices

Color transformation matrices for various operations.

color_tools.config

Immutable execution-context configuration for color processing.

Color Input Contracts

The public helpers below share one canonical implementation. RGB validation requires exactly three built-in integer channels in 0-255. Hex parsing accepts RGB/RGBA short and long forms; alpha is validated and discarded.

color_tools.conversions.validate_rgb(rgb)[source]

Check that RGB contains exactly three built-in integers in 0-255.

Channels are interpreted as red, green, and blue, in that order. Both endpoints are allowed. Booleans, floats (including integral floats), and subclasses of int are rejected because each channel must have type int. Values are not converted, rounded, or clamped, and the input is not modified. Only tuple and list containers are accepted.

Parameters:

rgb (object) – Three 8-bit RGB channels to validate.

Return type:

None

Returns:

None when all checks pass.

Raises:

ValueError – If the channel count is not three, a channel is not a built-in integer, or a channel is outside the inclusive 0-255 range.

Example

>>> validate_rgb((255, 127, 0))
color_tools.conversions.parse_hex_colors(hex_code)[source]

Parse ordered components separated by -, spaces, comma, _, /, :, or ;.

ASCII spaces may surround punctuation and the complete compound value. Repeated punctuation and empty components are errors, not discarded colors. All components are validated, including alpha, and duplicates are retained. Any positive number of components is supported. Each uses the single-color RGB/RGBA/RRGGBB/RRGGBBAA grammar; alpha is validated then dropped.

Parameters:

hex_code (object) – Original single or compound hex string.

Return type:

tuple[tuple[int, int, int], ...]

Returns:

An immutable ordered tuple of RGB triples.

Raises:

ValueError – If the input type or any component is invalid.

Example

>>> parse_hex_colors("#f00 / #00f")
((255, 0, 0), (0, 0, 255))
color_tools.conversions.normalize_hex(hex_code)[source]

Return a validated single color in canonical uppercase #RRGGBB form.

Short forms are expanded and valid CSS/PNG alpha-last components are discarded according to parse_hex()’s contract.

Parameters:

hex_code (str) – RGB, RGBA, RRGGBB, or RRGGBBAA with an optional leading #.

Return type:

str

Returns:

The parsed RGB color formatted as uppercase #RRGGBB.

Raises:

ValueError – If the input type or syntax is invalid.

Example

>>> normalize_hex("#a1c8")
'#AA11CC'

The implementation module is also documented for maintainers:

color_tools._color_utils

Canonical strict RGB validation, hex parsing, and hex formatting.

Dependency-Free PNG Writing

from color_tools.png_writer import SimplePNGWriter writes sRGB-tagged 8-bit RGB solid, block, gradient, and equal-width swatch images without Pillow or NumPy. It is part of the base package, not color_tools.image.

color_tools.png_writer

Minimal PNG writer for repeated-row RGB images.

Color & Filament Data

color_tools.palette

Color palette management with fast lookup.

color_tools.color_load_report

Structured results from loading and merging color data.

color_tools.filament_id

Canonical stable identifiers for filament records.

color_tools.filament_load_report

Structured results from loading and merging filament data.

color_tools.filament_palette

Filament palette management for 3D printing color matching.

color_tools.synonym_load_report

Structured results from loading and merging maker synonyms.

color_tools.filament_filter_criteria

Reusable inclusion and exclusion criteria for filament searches.

color_tools.filament_collections

Predefined, lazily loaded filament collections.

color_tools.naming

Color naming utilities for generating descriptive names from RGB values.

color_tools.validation

Color validation functions to check if a hex code matches a color name.

color_tools.color_deficiency

Color vision deficiency simulation and correction.

Export System

color_tools.export

Export system for filaments and colors.

color_tools.exporters

Palette exporter package.

color_tools.exporters.base

Base classes, metadata, and dependency handling for palette exporters.

color_tools.exporters.export_options_base

Base class for exporter-specific options.

color_tools.exporters.filament_export_data

Metadata-bearing filament transfer model.

color_tools.exporters.filament_metadata

Collection-level metadata for filament import and export.

color_tools.exporters.palette_export_data

Palette export data model.

color_tools.exporters.palette_metadata

Palette-level metadata.

color_tools.exporters.registry

Exporter registry and discovery utilities.

color_tools.exporters.ase_exporter

Adobe Swatch Exchange (ASE) palette exporter.

color_tools.exporters.aseprite_exporter

Aseprite native palette export as a single-frame swatch document.

color_tools.exporters.autoforge_exporter

AutoForge filament library CSV exporter.

color_tools.exporters.css_exporter

CSS custom-properties palette exporter.

color_tools.exporters.csv_exporter

Generic CSV exporter for colors and filaments.

color_tools.exporters.glsl_exporter

GLSL source-code palette exporter.

color_tools.exporters.gpl_exporter

GIMP Palette (.gpl) exporter.

color_tools.exporters.hex_exporter

HEX palette exporter.

color_tools.exporters.hueforge_exporter

HueForge filament-library JSON exporter.

color_tools.exporters.jascpal_exporter

JASC-PAL palette exporter.

color_tools.exporters.json_exporter

Generic JSON exporter for colors and filaments.

color_tools.exporters.kpl_exporter

Krita Palette (.kpl) exporter.

color_tools.exporters.lospec_exporter

Lospec JSON palette exporter.

color_tools.exporters.paintnet_exporter

PAINT.NET palette format exporter.

color_tools.exporters.palette_lut_exporter

Palette LUT PNG exporter.

color_tools.exporters.python_exporter

Python source-code palette exporter.

color_tools.exporters.riffpal_exporter

Microsoft RIFF PAL palette exporter.

color_tools.exporters.scribus_exporter

Scribus XML palette exporter.

color_tools.exporters.sketchpalette_exporter

SketchPalette exporter.

color_tools.exporters.soc_exporter

LibreOffice/OpenOffice SOC palette exporter.

color_tools.exporters.swatch_image_exporter

Palette swatch image exporter.

color_tools.exporters.user_color_export_models

Typed planning and result models for user-color persistence.

color_tools.exporters.user_colors_exporter

State-aware exporter for Color Tools user-colors.json data.

color_tools.exporters.user_filament_export_models

Typed planning and result models for user-filament persistence.

color_tools.exporters.user_filaments_exporter

State-aware exporter for Color Tools user-filaments.json data.

color_tools.exporters.owned_filament_export_models

Planning and result models for additive owned-filament updates.

color_tools.exporters.owned_filaments_exporter

State-aware exporter for additive owned-filaments.json updates.

Import System

color_tools.importers.base

Base contract and shared color construction for palette importers.

color_tools.importers.filament_importer

Base contract for filament collection importers.

color_tools.importers.registry

Typed registries for palette and filament import formats.

color_tools.importers.gpl_importer

GIMP Palette (GPL) importer.

color_tools.importers.hex_importer

HEX palette importer.

color_tools.importers.hueforge_importer

Importer for HueForge filament-library JSON files.

color_tools.importers.jascpal_importer

JASC PAL palette importer.

color_tools.importers.riffpal_importer

RIFF PAL palette importer.

color_tools.importers.user_colors_importer

Importer for Color Tools user-colors.json files.

color_tools.importers.user_filaments_importer

Importer for Color Tools user-filaments.json files.

color_tools.user_color_data

Canonical parsing, merging, and serialization for user color records.

Filament Reconciliation

color_tools.reconcilers.filament_reconciliation_models

Format-neutral models for filament catalog reconciliation.

color_tools.reconcilers.resolutions

Caller decisions applied to filament reconciliation plans.

color_tools.reconcilers.filament_reconciler

Base contract for reusable external-filament reconciliation.

color_tools.reconcilers.hueforge_filament_reconciler

HueForge-specific filament candidate ranking.

color_tools.filament_import_workflow

Format-neutral orchestration for reconciled filament imports.

Image Processing (requires [image] extra)

color_tools.image

Image processing tools for color analysis and manipulation.

color_tools.image.analysis

Image analysis functions for color extraction and manipulation.

color_tools.image.basic

Basic image analysis functions for color_tools.

color_tools.image.blend

Photoshop-compatible blend mode operations for image layers.

color_tools.image.conversion

Image format conversion utilities.

color_tools.image.dominance

Perceptual dominant-color analysis for images.

color_tools.image.watermark

Watermarking functionality for images.

Command Line Interface

color_tools.cli

Command-line interface for color_tools.

color_tools.cli_commands

CLI package for color_tools.

color_tools.cli_commands.utils

Utility functions for CLI argument parsing and validation.

color_tools.cli_commands.reporting

Reporting and diagnostic utilities for user data and overrides.

color_tools.cli_commands.handlers

Command handlers for color_tools CLI.

color_tools.cli_commands.handlers.color

Color command handler - Search and query CSS colors.

color_tools.cli_commands.handlers.convert

Convert command handler - Convert between color spaces and check gamut.

color_tools.cli_commands.handlers.cvd

CVD command handler - Color vision deficiency simulation and correction.

color_tools.cli_commands.handlers.harmony

Harmony command handler - Generate styled LCH color harmonies.

color_tools.cli_commands.handlers.filament

Filament command handler - Search and query 3D printing filaments.

color_tools.cli_commands.handlers.filament_import

CLI orchestration for reconciled external filament imports.

color_tools.cli_commands.handlers.image

Image processing command handler.

color_tools.cli_commands.handlers.name

Name command handler - Generate descriptive color names from RGB values.

color_tools.cli_commands.handlers.validate

Validate command handler - Verify color name/hex pairings.

Logging (optional [logging] extra for colorized output)

color_tools.logging_config

Centralized logging configuration for color_tools.

Interactive Terminal Features (requires [interactive] extra)

color_tools.interactive_manager

Interactive filament library manager using prompt_toolkit TUI.

color_tools.interactive_wizard

Interactive wizard for color-tools.

color_tools.filament_reconciliation_tui

Prompt-toolkit resolution UI for ambiguous filament imports.

Model Context Protocol (requires [mcp] extra)

color_tools.mcp

Model Context Protocol integration for Color Tools.

color_tools.mcp.models

Structured input and output models for the Color Tools MCP server.

color_tools.mcp.server

MCP server exposing Color Tools color science and filament expertise.

Palette and filament importer system.

Importers convert external files into the corresponding shared transfer model:

PaletteExportData

├── list[ColorRecord] └── PaletteMetadata

FilamentExportData

├── list[FilamentRecord] └── FilamentMetadata

Importer classes register automatically when this package is imported.

Basic usage:

>>> from color_tools.importers import import_palette
>>>
>>> palette = import_palette("palette.gpl")
>>> print(palette.metadata.name)

Explicit importer selection is also available:

>>> from color_tools.importers import get_importer
>>>
>>> importer = get_importer("gpl")
>>> palette = importer.import_palette("palette.gpl")

Automatic detection becomes especially useful for extensions shared by multiple formats. For example, future JASC PAL and RIFF PAL importers can both register the .pal extension and distinguish themselves by inspecting file contents.

Palette and filament registries are separate, so JSON formats are detected in the context of the requested data kind.

Filament reconciliation planning and caller-controlled resolution.

Color science tools for matching, conversion, and analysis.

A comprehensive toolkit for working with colors in multiple color spaces, finding nearest color matches, and working with 3D printing filament colors.

Quick Start:
>>> from color_tools import rgb_to_lab, delta_e_2000, Palette
>>>
>>> # Convert RGB to LAB
>>> lab = rgb_to_lab((255, 128, 64))
>>>
>>> # Find nearest CSS color
>>> palette = Palette.load_default()
>>> nearest, distance = palette.nearest_color(lab)
>>> print(f"Nearest color: {nearest.name}")
Color Validation:
>>> from color_tools import validate_color
>>>
>>> # Validate if a hex code matches a color name
>>> # Note: Install [fuzzy] extra for improved matching: pip install color-match-tools[fuzzy]
>>> result = validate_color("light blue", "#ADD8E6")
>>> print(f"Match: {result.is_match}, Confidence: {result.name_confidence:.0%}")
Match: True, Confidence: 100%
Image Processing (requires pip install color-match-tools[image]):
>>> from color_tools.image import simulate_cvd_image, quantize_image_to_palette, convert_image, add_watermark
>>>
>>> # Convert image formats (WebP, PNG, JPEG, HEIC, AVIF, etc.)
>>> convert_image("photo.webp", output_format="png")  # Creates photo.png
>>> convert_image("photo.jpg", output_format="webp", lossless=True)
>>>
>>> # Add watermarks
>>> add_watermark("photo.jpg", text="© 2025 MyBrand", output="watermarked.jpg")
>>>
>>> # Test accessibility - simulate colorblindness
>>> sim_image = simulate_cvd_image("chart.png", "deuteranopia")
>>> sim_image.save("colorblind_view.png")
>>>
>>> # Create retro artwork - convert to CGA palette
>>> retro_image = quantize_image_to_palette("photo.jpg", "cga4", dither=True)
>>> retro_image.save("retro_art.png")
Export & Integration (v6.0.0+ plugin system):
>>> from color_tools import Palette, get_exporter, list_export_formats
>>>
>>> # List available export formats
>>> formats = list_export_formats('colors')
>>> # {'csv': '...', 'json': '...', 'gpl': 'GIMP Palette format...'}
>>>
>>> # Export to GIMP Palette format (.gpl)
>>> palette = Palette.load_default()
>>> exporter = get_exporter('gpl')
>>> exporter.export_colors(palette.records[:20], 'my_colors.gpl')
>>>
>>> # Create custom exporters with plugin architecture
>>> from color_tools import register_exporter, PaletteExporter, ExporterMetadata
>>> # See exporters/gpl_exporter.py for complete example
Three Ways to Use:
  1. As a library: from color_tools import rgb_to_lab

  2. As a CLI tool: python -m color_tools color –name coral

  3. As installed command: color_tools filament –list-makers (needs pip install)

Indices and tables