Skip to main content

Python CLI tool for color palette analysis. Extract colors from images and SVG files, generate professional PDF swatches with HEX/RGB/CMYK values, frequency stats, pie charts, color harmonies, and WCAG accessibility ratings.

Project description

ChromaSpec

A professional Python package for color palette extraction, analysis, and visualization from SVG and image files.

PyPI version Tests DOI Python 3.9+ License: MIT Type Checked: mypy

Statement of Need

In contemporary UI/UX and accessibility research, the ability to analyze and generate color palettes that satisfy WCAG standards is essential. Existing tools either extract colors from images but lack accessibility analysis, or provide accessibility metrics without automated extraction. Researchers often resort to a multi-step workflow — extracting colors manually, then using separate libraries to evaluate contrast — which is error-prone and time-consuming.

ChromaSpec addresses this gap by offering an end-to-end solution: automated extraction from SVG and raster images, built-in WCAG 2.1 compliance checks, dark-mode compatibility assessment, and generation of WCAG-compliant palettes — all within a single, well-documented Python package. This integration reduces experimental overhead, improves reproducibility, and enables large-scale color studies that were previously impractical.

Documentation

Features

  • Color Extraction: Extract colors from SVG files and image formats (PNG, JPG, JPEG, GIF, BMP, TIFF, WEBP)
  • Color Analysis:
    • Color categorization (Red, Green, Blue)
    • Color harmonies (Complementary, Analogous, Split-Complementary, Triadic)
    • WCAG 2.1 accessibility analysis and contrast ratios
    • Dark mode compatibility - Verify colors work in both light and dark themes
  • Color Palette Generator: Generate harmonious palettes with WCAG accessibility compliance
    • Complementary palettes (2 colors)
    • Triadic palettes (3 colors, 120° apart)
    • Split-complementary palettes (3 colors)
    • Tetradic palettes (4 colors, 90° apart)
  • Color Conversions: RGB, HSL, CMYK, and HEX formats
  • PDF Reports: Generate comprehensive color swatch documents with visualizations
  • Batch Processing: Process multiple files at once via CLI with consolidated reports
  • Security: Input validation and protection against DoS/ReDoS attacks
  • Performance: Optimized image processing with LRU caching

Installation

pip install chromaspec

For image processing support:

pip install chromaspec[image]
# or
pip install Pillow

For development:

pip install chromaspec[dev]

Quick Start

Command Line

# Process an SVG file
chromaspec image.svg

# Process an image file
chromaspec photo.png

# Specify custom output
chromaspec image.jpg custom_report.pdf

# Batch process multiple files (generates consolidated JSON report)
chromaspec --batch --pattern "*.svg" --output report.json

# Batch process with individual PDFs
chromaspec --batch --pattern "images/*.png" --pdfs

# Batch process with CSV output
chromaspec --batch --pattern "*.jpg" --output results.csv --format csv

# Enable verbose logging
chromaspec image.svg -v

# Suppress output except errors
chromaspec image.png -q

Python API

from pathlib import Path
from chromaspec import ChromaSpec

# Initialize analyzer
analyzer = ChromaSpec()

# Extract colors from a file
colors = analyzer.extract_colors(Path("image.png"))

# Analyze colors
categories = analyzer.categorize_colors(colors)

# Generate color harmonies
from chromaspec.analyzers import get_complementary_color
comp = get_complementary_color("#FF0000")

# Check accessibility
from chromaspec.analyzers import get_contrast_ratio, get_wcag_rating
ratio = get_contrast_ratio("#FF0000", "#FFFFFF")
rating = get_wcag_rating(ratio)

# Generate color palettes with accessibility
from chromaspec.generators import (
    ColorPalette,
    generate_accessibility_palette,
    generate_triadic_palette,
)
palette = generate_triadic_palette("#FF0000", target_rating="AA")
print(f"Primary: {palette.primary}")
print(f"Secondary: {palette.secondary}")
print(f"Background: {palette.background}")
print(f"WCAG Rating: {palette.wcag_rating}")

# Check dark mode compatibility
from chromaspec.analyzers import check_dark_mode_compatibility
result = check_dark_mode_compatibility("#FF0000")
print(f"Compatible: {result.is_compatible}")
print(f"Light mode: {result.light_contrast:.2f}:1 ({result.light_rating})")
print(f"Dark mode: {result.dark_contrast:.2f}:1 ({result.dark_rating})")

Supported File Formats

  • SVG: .svg
  • Images: .png, .jpg, .jpeg, .gif, .bmp, .tiff, .webp

New Features Documentation

Color Palette Generator

Generate harmonious color palettes that meet WCAG accessibility standards:

from chromaspec.generators import (
    generate_accessibility_palette,
    generate_triadic_palette,
    generate_split_complementary_palette,
    generate_tetradic_palette,
)

# Generate complementary palette (2 colors)
palette = generate_accessibility_palette("#FF0000", target_rating="AA")
print(palette)

# Generate triadic palette (3 colors, 120° apart)
palette = generate_triadic_palette("#3B82F6", target_rating="AAA")

# Generate split-complementary palette
palette = generate_split_complementary_palette("#10B981")

# Generate tetradic palette (4 colors, 90° apart)
palette = generate_tetradic_palette("#8B5CF6")

Dark Mode Compatibility Checker

Verify that colors work well in both light and dark themes:

from chromaspec.analyzers import (
    check_dark_mode_compatibility,
    generate_dark_mode_palette,
    get_compatible_text_color,
    suggest_dark_mode_adjustments,
)

# Check a single color
result = check_dark_mode_compatibility("#333333")
if result.is_compatible:
    print("✓ Color works in both modes")
else:
    print("✗ Color needs adjustment")

# Generate a full palette tested for dark mode
results = generate_dark_mode_palette("#FF0000")
for color_name, result in results.items():
    print(f"{color_name}: {'✓' if result.is_compatible else '✗'}")

# Find a text color that works in both modes
text_color = get_compatible_text_color(
    background_light="#FFFFFF",
    background_dark="#121212",
    target_rating="AA"
)

# Get suggestions to fix incompatible colors
suggestions = suggest_dark_mode_adjustments("#FF0000")
for suggestion in suggestions:
    print(f"Try {suggestion['color']} ({suggestion['adjustment']})")

Batch Processing CLI

Process multiple files at once with consolidated reports:

# Generate JSON report
chromaspec --batch --pattern "*.svg" --output report.json

# Generate CSV report
chromaspec --batch --pattern "images/*.png" --output results.csv --format csv

# Generate individual PDFs + consolidated report
chromaspec --batch --pattern "*.jpg" --pdfs --output summary.json

# Quiet mode (less output)
chromaspec --batch --pattern "*.svg" --output report.json -q

# Using a directory
chromaspec --batch ./my_images --output report.json

Report format includes:

  • File-by-file color breakdown
  • Red, Green, and Blue color counts
  • Total colors per file
  • Summary statistics (total files, colors found, average colors per file)
  • Error tracking for failed files

Module Documentation

chromaspec.converters

Color conversion functions:

from chromaspec.converters import hex_to_rgb, rgb_to_hsl, rgb_to_cmyk

# HEX to RGB
rgb = hex_to_rgb("#FF0000")  # (255, 0, 0)

# RGB to HSL
hsl = rgb_to_hsl((255, 0, 0))  # (0.0, 100.0, 50.0)

# RGB to CMYK
cmyk = rgb_to_cmyk((255, 0, 0))  # (0, 100, 100, 0)

# Calculate luminance (for contrast ratios)
from chromaspec.converters import calculate_luminance
lum = calculate_luminance((255, 0, 0))  # ~0.21

chromaspec.analyzers

Color analysis and classification:

from chromaspec.analyzers import (
    is_red_color, is_green_color, is_blue_color,
    categorize_colors,
    get_complementary_color, get_analogous_colors,
    get_contrast_ratio, get_wcag_rating
)

# Classify colors
is_red_color((255, 0, 0))  # True

# Get color harmonies
comp = get_complementary_color("#FF0000")  # "#00FFFF"
analogs = get_analogous_colors("#FF0000")  # ("#FF9900", "#FF0099")

# Accessibility analysis
ratio = get_contrast_ratio("#FF0000", "#FFFFFF")  # ~3.98
rating = get_wcag_rating(ratio)  # "AA Large"

chromaspec.extractors

Color extraction from files:

from pathlib import Path
from chromaspec.extractors import extract_colors

# Extract colors with frequencies
colors = extract_colors(Path("image.svg"))
# Returns: {"#FF0000": 25.5, "#00FF00": 30.2, ...}

# Extract specific formats
from chromaspec.extractors import extract_hex_colors_from_svg
svg_colors = extract_hex_colors_from_svg(svg_content)

from chromaspec.extractors import extract_colors_from_image
img_colors = extract_colors_from_image(Path("photo.png"))

chromaspec.generators

PDF report generation:

from pathlib import Path
from chromaspec.generators import generate_color_pdf
from chromaspec.analyzers import categorize_colors

# Generate PDF report
colors = extract_colors(Path("image.png"))
categories = categorize_colors(colors)
generate_color_pdf(
    Path("report.pdf"),
    categories,
    Path("image.png")
)

Development

Running Tests

# Install development dependencies
pip install -e .[dev]

# Run tests
pytest

# Run tests with coverage
pytest --cov=chromaspec --cov-report=html

# Run specific test file
pytest tests/test_converters.py

Code Quality

# Format code with Black
black chromaspec tests

# Sort imports with isort
isort chromaspec tests

# Lint with flake8
flake8 chromaspec tests

# Type check with mypy
mypy chromaspec

Pre-commit Hooks

# Install pre-commit hooks
pre-commit install

# Run pre-commit manually
pre-commit run --all-files

Project Structure

chromaspec/
├── __init__.py                # Package initialization
├── cli.py                     # Command-line interface with batch support
├── exceptions.py              # Custom exception hierarchy
├── analyzers/                 # Color analysis modules
│   ├── classification.py      # Color categorization
│   ├── harmonies.py           # Color harmony calculations
│   ├── accessibility.py       # WCAG contrast analysis
│   └── dark_mode.py           # Dark mode compatibility checker
├── converters/                # Color conversion modules
│   ├── rgb_converters.py      # RGB, CMYK, HEX conversions
│   └── hsl_converters.py      # HSL conversions
├── extractors/                # Color extraction modules
│   ├── svg_extractor.py       # SVG color extraction
│   └── image_extractor.py     # Image color extraction
├── generators/                # PDF generation modules
│   ├── pdf_pages.py           # PDF page layouts
│   ├── charts.py              # Chart generation
│   ├── accessibility_page.py
│   ├── palette.py             # Color palette generator
│   └── pdf_generator.py       # Main PDF generator
└── utils/                     # Utility modules
    ├── constants.py           # Configuration constants
    └── validators.py          # Input validation

Performance Optimizations

  • LRU Caching: RGB to HSL conversions are cached for repeated lookups
  • Image Resizing: Large images are automatically resized for efficient processing
  • Memory Efficiency: Color counting uses Counter directly on pixel data iterators
  • Input Validation: Size limits prevent DoS attacks on SVG processing

Security

  • Input validation for all user-provided data
  • Protection against ReDoS (Regex Denial of Service) attacks
  • File format validation before processing
  • Size limits for SVG content and color matches

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes with tests
  4. Run the linters and tests
  5. Submit a pull request

License

MIT License - see LICENSE for details.

Citation

If you use ChromaSpec in your research, please cite:

@software{chromaspec,
  author = {Semoglou, Michail},
  title = {ChromaSpec: Color Palette Analyzer},
  version = {1.2.0},
  year = {2026},
  url = {https://github.com/MichailSemoglou/chromaspec},
  doi = {10.5281/zenodo.17864788}
}

Acknowledgments

  • Color conversion algorithms based on standard color science
  • WCAG accessibility calculations follow W3C specifications
  • ReportLab for PDF generation
  • Pillow for image processing

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chromaspec-1.2.0.tar.gz (19.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chromaspec-1.2.0-py3-none-any.whl (7.6 kB view details)

Uploaded Python 3

File details

Details for the file chromaspec-1.2.0.tar.gz.

File metadata

  • Download URL: chromaspec-1.2.0.tar.gz
  • Upload date:
  • Size: 19.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for chromaspec-1.2.0.tar.gz
Algorithm Hash digest
SHA256 754cc96328ea5da15b9cd6a7dea57e2b71e186a6a0a1cded5c1daded717ef524
MD5 95b4a34d50083253859736088e41033d
BLAKE2b-256 a1aabae9513bc3b70112335d49eca9fd98efab89860a1f81c41ad01499e41bb8

See more details on using hashes here.

Provenance

The following attestation bundles were made for chromaspec-1.2.0.tar.gz:

Publisher: publish.yml on MichailSemoglou/chromaspec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chromaspec-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: chromaspec-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 7.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for chromaspec-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ba41f80f02ff3f678315ad455d50e9f61345b99f3b2f9d63758b13af829fcdb9
MD5 5978213f51d9b335d3de912e26944973
BLAKE2b-256 5fe710b797d925a9b196e7f929efa9ecf2e8a80fb5b980fbd719548d5e1d7175

See more details on using hashes here.

Provenance

The following attestation bundles were made for chromaspec-1.2.0-py3-none-any.whl:

Publisher: publish.yml on MichailSemoglou/chromaspec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page