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:
As a library:
from color_tools import rgb_to_labAs a CLI tool:
python -m color_tools color --name coralAs 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:
📖 Usage Guide - Library and CLI usage examples
⚙️ Installation - Installation instructions
🎨 Customization - User overrides and custom palettes
❓ FAQ - Frequently asked questions
📋 Quick Reference - Command cheat sheet
🔧 Troubleshooting - Common issues and solutions
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 space conversion functions. |
|
Color distance metrics for measuring perceptual color differences. |
|
Gamut checking and mapping for sRGB color space. |
|
Generate color harmonies in CIE LCH space. |
|
Immutable color science constants from international standards. |
|
Color transformation matrices for various operations. |
|
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:
- 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:
- 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
#RRGGBBform.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:
- 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:
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.
Minimal PNG writer for repeated-row RGB images. |
Color & Filament Data
Color palette management with fast lookup. |
|
Structured results from loading and merging color data. |
|
Canonical stable identifiers for filament records. |
|
Structured results from loading and merging filament data. |
|
Filament palette management for 3D printing color matching. |
|
Structured results from loading and merging maker synonyms. |
|
Reusable inclusion and exclusion criteria for filament searches. |
|
Predefined, lazily loaded filament collections. |
|
Color naming utilities for generating descriptive names from RGB values. |
|
Color validation functions to check if a hex code matches a color name. |
|
Color vision deficiency simulation and correction. |
Export System
Export system for filaments and colors. |
|
Palette exporter package. |
|
Base classes, metadata, and dependency handling for palette exporters. |
|
Base class for exporter-specific options. |
|
Metadata-bearing filament transfer model. |
|
Collection-level metadata for filament import and export. |
|
Palette export data model. |
|
Palette-level metadata. |
|
Exporter registry and discovery utilities. |
|
Adobe Swatch Exchange (ASE) palette exporter. |
|
Aseprite native palette export as a single-frame swatch document. |
|
AutoForge filament library CSV exporter. |
|
CSS custom-properties palette exporter. |
|
Generic CSV exporter for colors and filaments. |
|
GLSL source-code palette exporter. |
|
GIMP Palette (.gpl) exporter. |
|
HEX palette exporter. |
|
HueForge filament-library JSON exporter. |
|
JASC-PAL palette exporter. |
|
Generic JSON exporter for colors and filaments. |
|
Krita Palette (.kpl) exporter. |
|
Lospec JSON palette exporter. |
|
PAINT.NET palette format exporter. |
|
Palette LUT PNG exporter. |
|
Python source-code palette exporter. |
|
Microsoft RIFF PAL palette exporter. |
|
Scribus XML palette exporter. |
|
SketchPalette exporter. |
|
LibreOffice/OpenOffice SOC palette exporter. |
|
Palette swatch image exporter. |
|
Typed planning and result models for user-color persistence. |
|
State-aware exporter for Color Tools |
|
Typed planning and result models for user-filament persistence. |
|
State-aware exporter for Color Tools |
|
Planning and result models for additive owned-filament updates. |
|
State-aware exporter for additive |
Import System
Base contract and shared color construction for palette importers. |
|
Base contract for filament collection importers. |
|
Typed registries for palette and filament import formats. |
|
GIMP Palette (GPL) importer. |
|
HEX palette importer. |
|
Importer for HueForge filament-library JSON files. |
|
JASC PAL palette importer. |
|
RIFF PAL palette importer. |
|
Importer for Color Tools |
|
Importer for Color Tools |
|
Canonical parsing, merging, and serialization for user color records. |
Filament Reconciliation
Format-neutral models for filament catalog reconciliation. |
|
Caller decisions applied to filament reconciliation plans. |
|
Base contract for reusable external-filament reconciliation. |
|
HueForge-specific filament candidate ranking. |
|
Format-neutral orchestration for reconciled filament imports. |
Image Processing (requires [image] extra)
Image processing tools for color analysis and manipulation. |
|
Image analysis functions for color extraction and manipulation. |
|
Basic image analysis functions for color_tools. |
|
Photoshop-compatible blend mode operations for image layers. |
|
Image format conversion utilities. |
|
Perceptual dominant-color analysis for images. |
|
Watermarking functionality for images. |
Command Line Interface
Command-line interface for color_tools. |
|
CLI package for color_tools. |
|
Utility functions for CLI argument parsing and validation. |
|
Reporting and diagnostic utilities for user data and overrides. |
|
Command handlers for color_tools CLI. |
|
Color command handler - Search and query CSS colors. |
|
Convert command handler - Convert between color spaces and check gamut. |
|
CVD command handler - Color vision deficiency simulation and correction. |
|
Harmony command handler - Generate styled LCH color harmonies. |
|
Filament command handler - Search and query 3D printing filaments. |
|
CLI orchestration for reconciled external filament imports. |
|
Image processing command handler. |
|
Name command handler - Generate descriptive color names from RGB values. |
|
Validate command handler - Verify color name/hex pairings. |
Logging (optional [logging] extra for colorized output)
Centralized logging configuration for color_tools. |
Interactive Terminal Features (requires [interactive] extra)
Interactive filament library manager using prompt_toolkit TUI. |
|
Interactive wizard for color-tools. |
|
Prompt-toolkit resolution UI for ambiguous filament imports. |
Model Context Protocol (requires [mcp] extra)
Model Context Protocol integration for Color Tools. |
|
Structured input and output models for the 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:
As a library: from color_tools import rgb_to_lab
As a CLI tool: python -m color_tools color –name coral
As installed command: color_tools filament –list-makers (needs pip install)