Skip to main content

No project description provided

Project description

imgcolorshine

Transform image colors using OKLCH color attractors - a physics-inspired tool that operates in perceptually uniform color space.

Python 3.9+ Test Coverage License

Table of Contents

Overview

imgcolorshine is a high-performance image color transformation tool that uses a physics-inspired model to transform images. It works by defining "attractor" colors that pull the image's colors toward them, similar to gravitational attraction. All operations are performed in the perceptually uniform OKLCH color space, ensuring natural and visually pleasing results.

What Makes imgcolorshine Special?

  1. Perceptually Uniform: Uses OKLCH color space for intuitive, natural-looking transformations
  2. Physics-Inspired: Gravitational model provides smooth, organic color transitions
  3. Blazing Fast: 100x+ faster than naive implementations through multiple optimization layers
  4. Production Ready: Comprehensive test suite, professional gamut mapping, memory efficient
  5. Flexible: Fine-grained control over color channels and transformation parameters

Key Features

Core Capabilities

  • โœจ Perceptually Uniform Color Space: All operations in OKLCH for natural results
  • ๐ŸŽจ Universal Color Support: Any CSS color format (hex, rgb, hsl, oklch, named colors, etc.)
  • ๐ŸŽฏ Multi-Attractor Blending: Combine multiple color influences seamlessly
  • ๐ŸŽ›๏ธ Channel Control: Transform lightness, chroma, and hue independently
  • ๐ŸŽ๏ธ Multiple Acceleration Modes: CPU, GPU, and LUT-based processing
  • ๐Ÿ“Š Professional Gamut Mapping: CSS Color Module 4 compliant
  • ๐Ÿ’พ Memory Efficient: Automatic tiling for images of any size

Performance Features

  • Numba JIT Compilation: 77-115x faster color space conversions
  • GPU Acceleration: 10-100x speedup with NVIDIA GPUs (CuPy)
  • 3D Color LUT: Pre-computed transformations with caching
  • Fused Kernels: All operations in a single pass, minimizing memory traffic
  • Spatial Acceleration: KD-tree based optimization for local color queries
  • Hierarchical Processing: Multi-resolution pyramid for large images

Installation

From PyPI (Recommended)

pip install imgcolorshine

From Source

git clone https://github.com/twardoch/imgcolorshine.git
cd imgcolorshine
pip install -e .

Optional Dependencies

For GPU acceleration:

pip install cupy-cuda11x  # For CUDA 11.x
# or
pip install cupy-cuda12x  # For CUDA 12.x

Quick Start

Basic Usage

Transform an image to have a warmer tone:

imgcolorshine shine photo.jpg "orange;50;75"

This command:

  • Loads photo.jpg
  • Creates an orange color attractor with 50% tolerance and 75% strength
  • Saves the result as photo_colorshine.jpg

Multiple Attractors

Create a sunset effect with multiple color influences:

imgcolorshine shine landscape.png \
  "oklch(80% 0.2 60);40;60" \
  "#ff6b35;30;80" \
  --output_image=sunset.png

Usage Guide

Command Structure

imgcolorshine shine INPUT_IMAGE ATTRACTOR1 [ATTRACTOR2 ...] [OPTIONS]

Attractor Format

Each attractor is specified as: "color;tolerance;strength"

  • color: Any CSS color

    • Named: "red", "blue", "forestgreen"
    • Hex: "#ff0000", "#00ff00"
    • RGB: "rgb(255, 0, 0)", "rgba(0, 255, 0, 0.5)"
    • HSL: "hsl(120, 100%, 50%)"
    • OKLCH: "oklch(70% 0.2 120)"
  • tolerance (0-100): Radius of influence

    • 0-20: Only very similar colors affected
    • 30-60: Moderate range of influence
    • 70-100: Broad influence across many colors
  • strength (0-200): Transformation intensity

    • 0-30: Subtle shifts, original color dominates
    • 40-70: Noticeable but natural transformations
    • 80-100: Strong pull toward attractor (fall-off still applies)
    • 100-200: Extended range โ€“ progressively flattens the fall-off curve

Command Options

Option Type Default Description
--output_image PATH Auto Output file path
--luminance BOOL True Transform lightness channel
--saturation BOOL True Transform chroma channel
--hue BOOL True Transform hue channel
--verbose BOOL False Enable detailed logging
--tile_size INT 1024 Tile size for large images
--gpu BOOL True Use GPU if available
--lut_size INT 0 3D LUT size (0=disabled, 65=recommended)
--hierarchical BOOL False Multi-resolution processing
--spatial_accel BOOL True Spatial acceleration structures

Advanced Examples

Channel-Specific Transformation

Transform only the hue, preserving lightness and saturation:

imgcolorshine shine portrait.jpg "teal;60;80" \
  --luminance=False --saturation=False

High-Performance Processing

For maximum speed on repeated transformations:

# Build and cache a 3D LUT for fast processing
imgcolorshine shine photo.jpg "purple;50;70" --lut_size=65

# Use GPU acceleration
imgcolorshine shine photo.jpg "cyan;40;60" --gpu=True

# Combine optimizations
imgcolorshine shine large_image.jpg "red;45;65" \
  --gpu=True --lut_size=65 --hierarchical=True

Batch Processing

Process multiple images with the same transformation:

for img in *.jpg; do
  imgcolorshine shine "$img" "seagreen;55;75" \
    --output_image="processed/${img}"
done

How It Works

The Attraction Model: "Pull" vs "Replace"

imgcolorshine uses a "pull" model, not a "replace" model. Colors are gradually pulled toward attractors, creating natural, smooth transitions.

The Transformation Process

  1. Color Space: All operations happen in the perceptually uniform OKLCH color space.
  2. Attraction Model: Each attractor's influence is determined by:
    • Tolerance (0-100): This is a percentile. tolerance=50 means the attractor will influence the 50% of the image's pixels that are most similar to it. This makes the effect adaptive to each image's unique color palette.
    • Strength (0-200): This controls the intensity of the pull โ€“ and, beyond 100, how much the raised-cosine fall-off is overridden.
  3. Blending: Influences from multiple attractors are blended using a normalized, weighted average.
  4. Gamut Mapping: Any resulting colors that are outside the displayable sRGB gamut are carefully mapped back in, preserving the perceived color as much as possible.

Performance

The refactored codebase is optimized for correctness and maintainability. Performance is enhanced through:

  • Numba: Critical numerical loops are JIT-compiled to C-like speed.
  • Mypyc: Core modules are compiled into native C extensions, removing Python interpreter overhead.

A 2048x2048 image is processed in a few seconds on a modern machine.

Architecture

Module Overview

imgcolorshine/
โ”œโ”€โ”€ Core Modules
โ”‚   โ”œโ”€โ”€ color.py          # OKLCH color engine and attractor management
โ”‚   โ”œโ”€โ”€ transform.py      # Main transformation logic
โ”‚   โ”œโ”€โ”€ colorshine.py     # High-level API and orchestration
โ”‚   โ””โ”€โ”€ falloff.py        # Distance-based influence functions
โ”‚
โ”œโ”€โ”€ Performance Modules
โ”‚   โ”œโ”€โ”€ trans_numba.py    # Numba-optimized color conversions
โ”‚   โ”œโ”€โ”€ kernel.py         # Fused transformation kernels
โ”‚   โ”œโ”€โ”€ lut.py            # 3D lookup table implementation
โ”‚   โ”œโ”€โ”€ gpu.py            # GPU backend management
โ”‚   โ””โ”€โ”€ trans_gpu.py      # CuPy transformations
โ”‚
โ”œโ”€โ”€ Optimization Modules
โ”‚   โ”œโ”€โ”€ spatial.py        # Spatial acceleration structures
โ”‚   โ”œโ”€โ”€ hierar.py         # Hierarchical processing
โ”‚   โ””โ”€โ”€ numba_utils.py    # Additional optimized utilities
โ”‚
โ”œโ”€โ”€ Support Modules
โ”‚   โ”œโ”€โ”€ gamut.py          # CSS Color Module 4 gamut mapping
โ”‚   โ”œโ”€โ”€ io.py             # Optimized image I/O
โ”‚   โ”œโ”€โ”€ utils.py          # General utilities
โ”‚   โ””โ”€โ”€ cli.py            # Command-line interface

Key Design Principles

  1. Modular Architecture: Clear separation of concerns
  2. Performance First: Multiple optimization paths
  3. Fallback Chain: GPU โ†’ LUT โ†’ CPU Numba โ†’ Pure Python
  4. Type Safety: Comprehensive type hints
  5. Memory Efficiency: Streaming and tiling for large images
  6. Test Coverage: 50%+ coverage with comprehensive test suite

Development

Setting Up Development Environment

# Clone the repository
git clone https://github.com/twardoch/imgcolorshine.git
cd imgcolorshine

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode with test dependencies
pip install -e ".[dev,test]"

Running Tests

# Run all tests
python -m pytest

# Run with coverage
python -m pytest --cov=src/imgcolorshine --cov-report=html

# Run specific test file
python -m pytest tests/test_color.py -v

# Run benchmarks
python -m pytest tests/test_performance.py -v

Code Quality

# Format code
ruff format src tests

# Lint code
ruff check src tests

# Type checking
mypy src/imgcolorshine

Building Documentation

# Install documentation dependencies
pip install -e ".[docs]"

# Build HTML documentation
cd docs
make html

API Reference

Python API

from imgcolorshine import process_image

# Basic transformation
process_image(
    input_image="photo.jpg",
    attractors=["red;50;75", "blue;30;60"],
    output_image="result.jpg"
)

# Advanced options
from imgcolorshine import OKLCHEngine, ColorTransformer

# Create color engine
engine = OKLCHEngine()

# Create attractors
attractor1 = engine.create_attractor("oklch(70% 0.2 30)", tolerance=50, strength=80)
attractor2 = engine.create_attractor("#ff6b35", tolerance=40, strength=60)

# Create transformer
transformer = ColorTransformer(
    engine,
    transform_lightness=True,
    transform_chroma=True,
    transform_hue=True
)

# Load and transform image
import numpy as np
from imgcolorshine.io import ImageProcessor

processor = ImageProcessor()
image = processor.load_image("input.jpg")

# Transform with specific channels
transformed = transformer.transform_image(
    image, 
    [attractor1, attractor2],
    {"luminance": True, "saturation": True, "hue": False}
)

processor.save_image(transformed, "output.jpg")

Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Areas for Contribution

  • ๐Ÿงช Testing: Improve test coverage (target: 80%+)
  • ๐Ÿ“š Documentation: Tutorials, examples, API docs
  • ๐Ÿš€ Performance: New optimization strategies
  • ๐ŸŽจ Features: Additional color spaces, effects
  • ๐Ÿ› Bug Fixes: Issue resolution
  • ๐ŸŒ Localization: Multi-language support

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Developed by Adam Twardoch with assistance from Anthropic's Claude
  • Inspired by color science research and perceptual uniformity principles
  • Built on the shoulders of giants: NumPy, Numba, ColorAide, OpenCV
  • Special thanks to the OKLCH color space creators for enabling intuitive color manipulation

Citation

If you use imgcolorshine in your research or projects, please cite:

@software{imgcolorshine,
  author = {Twardoch, Adam},
  title = {imgcolorshine: Perceptually Uniform Color Transformation},
  year = {2025},
  url = {https://github.com/twardoch/imgcolorshine}
}

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

imgcolorshine-3.2.1.tar.gz (10.9 kB view details)

Uploaded Source

Built Distribution

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

imgcolorshine-3.2.1-py3-none-any.whl (33.3 kB view details)

Uploaded Python 3

File details

Details for the file imgcolorshine-3.2.1.tar.gz.

File metadata

  • Download URL: imgcolorshine-3.2.1.tar.gz
  • Upload date:
  • Size: 10.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.28.1

File hashes

Hashes for imgcolorshine-3.2.1.tar.gz
Algorithm Hash digest
SHA256 b072e3915ce0722eca77948315f43cd06aa3255bb446995ab37d5bbdab9a888f
MD5 841631f4e71c99dc9a0b46dcb66dfc62
BLAKE2b-256 9b52d7b8ff16284b825977ece120e6037305fe3ea55d682bc5573d00e36664ea

See more details on using hashes here.

File details

Details for the file imgcolorshine-3.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for imgcolorshine-3.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b5ea14b30175085bc6d8040e86f9041c771c4b270348e20968ec2a5bb0a09918
MD5 54b74849d6d8fb9b735cc3df7b7c67b8
BLAKE2b-256 d69756b2ced7c1bf10c08e0d0ba73662b1e028c7e142eb62d81bf9a1dd1e9dd6

See more details on using hashes here.

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