|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +import math |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | + |
| 10 | +class RangeInput: |
| 11 | + """Represents a levels/range adjustment: input range [min, max] with |
| 12 | + optional midpoint (gamma control). |
| 13 | +
|
| 14 | + Generates a 1D LUT identical to GIMP's levels mapping: |
| 15 | + 1. Normalize input to [0, 1] using [min, max] |
| 16 | + 2. Apply gamma correction: pow(value, 1/gamma) |
| 17 | + 3. Clamp to [0, 1] |
| 18 | +
|
| 19 | + The midpoint field is a position in [0, 1] representing where the |
| 20 | + midtone falls within [min, max]. It maps to gamma via: |
| 21 | + gamma = -log2(midpoint) |
| 22 | + So midpoint=0.5 → gamma=1.0 (linear). |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, min_val: float, max_val: float, midpoint: float | None = None): |
| 26 | + self.min_val = min_val |
| 27 | + self.max_val = max_val |
| 28 | + self.midpoint = midpoint |
| 29 | + |
| 30 | + @staticmethod |
| 31 | + def from_raw(data) -> RangeInput: |
| 32 | + if isinstance(data, RangeInput): |
| 33 | + return data |
| 34 | + if isinstance(data, dict): |
| 35 | + return RangeInput( |
| 36 | + min_val=float(data.get("min", 0.0)), |
| 37 | + max_val=float(data.get("max", 1.0)), |
| 38 | + midpoint=float(data["midpoint"]) if data.get("midpoint") is not None else None, |
| 39 | + ) |
| 40 | + raise TypeError(f"Cannot convert {type(data)} to RangeInput") |
| 41 | + |
| 42 | + def to_lut(self, size: int = 256) -> np.ndarray: |
| 43 | + """Generate a float64 lookup table mapping [0, 1] input through this |
| 44 | + levels adjustment. |
| 45 | +
|
| 46 | + The LUT maps normalized input values (0..1) to output values (0..1), |
| 47 | + matching the GIMP levels formula. |
| 48 | + """ |
| 49 | + xs = np.linspace(0.0, 1.0, size, dtype=np.float64) |
| 50 | + |
| 51 | + in_range = self.max_val - self.min_val |
| 52 | + if abs(in_range) < 1e-10: |
| 53 | + return np.where(xs >= self.min_val, 1.0, 0.0).astype(np.float64) |
| 54 | + |
| 55 | + # Normalize: map [min, max] → [0, 1] |
| 56 | + result = (xs - self.min_val) / in_range |
| 57 | + result = np.clip(result, 0.0, 1.0) |
| 58 | + |
| 59 | + # Gamma correction from midpoint |
| 60 | + if self.midpoint is not None and self.midpoint > 0 and self.midpoint != 0.5: |
| 61 | + gamma = max(-math.log2(self.midpoint), 0.001) |
| 62 | + inv_gamma = 1.0 / gamma |
| 63 | + mask = result > 0 |
| 64 | + result[mask] = np.power(result[mask], inv_gamma) |
| 65 | + |
| 66 | + return result |
| 67 | + |
| 68 | + def __repr__(self) -> str: |
| 69 | + mid = f", midpoint={self.midpoint}" if self.midpoint is not None else "" |
| 70 | + return f"RangeInput(min={self.min_val}, max={self.max_val}{mid})" |
0 commit comments