
Construct a complete, production-ready, modular image proces...
Prompt
Construct a complete, production-ready, modular image processing and photographic emulation software suite from scratch in Python. The software must implement an end-to-end, high-precision image rendering pipeline that faithfully reproduces the combined photographic, optical, lighting, and chemical film characteristics specified below: on-camera direct hard flash illumination, mixed fluorescent/ambient practical lighting, wide-angle barrel distortion, low-angle perspective projection, optical diffusion filtering, specular highlight bloom, analog film halation, parametric S-curve contrast with crushed blacks, dual-zone teal-and-orange split toning, selective hue vibrance enhancement, and physically modeled 35mm film grain. Every module must operate in floating-point linear color space with strict gamut and boundary controls. The code must be production-ready, fully typed, documented, and free of placeholders, omissions, mock functions, or simplified stubs. --- ### 1. System Architecture & File Organization Construct the software with the following modular repository structure: ``` photo_stylizer/ ├── __init__.py ├── main.py ├── core/ │ ├── __init__.py │ ├── color_space.py │ └── pipeline.py ├── modules/ │ ├── __init__.py │ ├── optics.py │ ├── lighting.py │ ├── diffusion.py │ ├── halation.py │ ├── toning.py │ └── grain.py └── config/ ├── __init__.py └── presets.py ``` Each file must be completely implemented from beginning to end: 1. `core/color_space.py`: High-precision conversions between standard sRGB (gamma-encoded), Linear RGB (normalized $[0.0, 1.0]$), CIELAB ($L^*a^*b^*$), and HSL color models. Must include exact piecewise sRGB transfer functions and matrix transformations for CIE XYZ (D65 illuminant). 2. `core/pipeline.py`: The central execution graph (`ImageProcessingPipeline`) that accepts an input image (via file path or raw array), converts to Linear float32 representation, executes all processing stages sequentially in mathematically valid color spaces, manages intermediate buffers, and exports the final raster image at 8-bit or 16-bit depth. 3. `modules/optics.py`: Wide-angle lens barrel distortion using a radial polynomial model and low-angle perspective projection (homography/tilt transformation). 4. `modules/lighting.py`: Synthetic direct on-camera hard flash simulation with distance/depth-attenuated inverse-square falloff, cast drop-shadow generation on background planes, specular reflectance boosting, and mixed practical/ambient fluorescent lighting integration (adjustable cool-cyan/greenish white balance shift). 5. `modules/diffusion.py`: Optical diffusion filter emulation combining high-frequency detail preservation with dual-kernel Gaussian highlight dispersal, simulating physical micro-particle glass diffusion filters. 6. `modules/halation.py`: Analog film emulsion halation simulation modeling red-wavelength photon back-scattering against the film base, generating localized red-orange halos around overexposed boundaries. 7. `modules/toning.py`: Parametric S-curve tone mapping with crushed/inked black point clamping, teal-and-orange split toning (cyan-biased shadows and warm amber/orange midtones/highlights), and selective hue vibrance boosting targeting warm skin/hair tones and indigo/blue textiles. 8. `modules/grain.py`: Luminance-dependent, multi-octave 35mm film grain generation using procedural pseudo-random noise modulated by the tonal transfer curve of photographic emulsion. 9. `config/presets.py`: Dataclass-based configuration schemas and preset serializers (JSON/YAML) containing parameter values representing the specific urban flash aesthetic. 10. `main.py`: Full command-line interface (CLI) with argument parsing supporting single-image and batch-directory processing, multi-threading, logging, and custom parameter overrides. --- ### 2. Mathematical & Algorithmic Specifications #### A. Color Space Conversions (`core/color_space.py`) - Implement accurate forward and inverse conversions: $$\text{sRGB to Linear: } C_{\text{linear}} = \begin{cases} \frac{C_{\text{srgb}}}{12.92}, & C_{\text{srgb}} \le 0.04045 \\ \left(\frac{C_{\text{srgb}} + 0.055}{1.055}\right)^{2.4}, & C_{\text{srgb}} > 0.04045 \end{cases}$$ $$\text{Linear to sRGB: } C_{\text{srgb}} = \begin{cases} 12.92 \cdot C_{\text{linear}}, & C_{\text{linear}} \le 0.0031308 \\ 1.055 \cdot C_{\text{linear}}^{1/2.4} - 0.055, & C_{\text{linear}} > 0.0031308 \end{cases}$$ - Implement Linear RGB $\leftrightarrow$ CIE $XYZ \leftrightarrow$ CIELAB ($L^*a^*b^*$) with D65 reference white $(X_n, Y_n, Z_n) = (0.95047, 1.00000, 1.08883)$. - Implement fast vectorized RGB $\leftrightarrow$ HSL conversions for selective hue processing. #### B. Geometric Optics & Perspective (`modules/optics.py`) - **Wide-Angle Barrel Distortion:** Model a 20mm–28mm equivalent focal length using the Brown-Conrady radial model: $$r^2 = x_n^2 + y_n^2, \quad x_d = x_n(1 + k_1 r^2 + k_2 r^4), \quad y_d = y_n(1 + k_1 r^2 + k_2 r^4)$$ where $(x_n, y_n)$ are normalized sensor coordinates centered at $(0, 0)$. Implement backward coordinate mapping with bilinear interpolation. - **Low-Angle Perspective Projection:** Construct a $3 \times 3$ homography matrix simulating an upward-tilted camera view (pitch angle $\theta \in [5^\circ, 20^\circ]$) from a low camera position, producing subtle vertical keystone convergence while maintaining image plane bounds. #### C. Lighting Engine (`modules/lighting.py`) - **Direct On-Camera Hard Flash:** - Simulate a localized point-light source positioned at the camera optical center $(x_0, y_0)$. - Calculate radial distance attenuation: $I_{\text{flash}}(r) = I_0 \cdot \frac{1}{1 + \beta r^2}$, where $r$ is the normalized radius from the optical axis. - Implement a luminance-based pseudo-depth estimation to generate hard, sharp drop shadows cast behind foreground objects: calculate high-contrast edge gradients, offset the shadow mask along the flash parallax vector, and subtract luminance selectively on background regions. - Enhance specular skin reflections by detecting high-luminance smooth regions and applying an additive exponential specular term: $S_{\text{spec}} = k_s \cdot \max(0, \mathbf{N} \cdot \mathbf{H})^\alpha$. - **Mixed Practical Fluorescent Ambient:** - Model ambient grocery/store fluorescent lighting: calculate an ambient illumination layer shifted toward cool cyan-green (color temperature $\sim 4000\text{K} - 5000\text{K}$ with a $+G$ tint vector). - Blend flash light (neutral/slightly warm) additively with ambient practicals, ensuring foreground subject isolation over a dimmer, cooler background. #### D. Optical Diffusion & Highlight Bloom (`modules/diffusion.py`) - **Micro-Particle Optical Diffusion:** - Preserve low-frequency and high-frequency structural edges while dispersing mid-frequency contrast. - Compute a multi-scale Gaussian blur decomposition: $$I_{\text{diffuse}} = (1 - w) \cdot I_{\text{linear}} + w \cdot \left(\sum_{i=1}^N \alpha_i \cdot \mathcal{G}_{\sigma_i}(I_{\text{linear}})\right)$$ where $\sigma \in \{2, 8, 32\}$ pixels and $\sum \alpha_i = 1$. - **Highlight Bloom / Glow:** - Isolate highlights exceeding threshold $\tau_{\text{bloom}} \in [0.7, 0.9]$ with a smooth transition knee: $$M(x) = \frac{\max(0, x - \tau_{\text{bloom}} + \epsilon)^2}{x + \epsilon}$$ - Blur the extracted highlight mask with a large-radius Gaussian kernel ($\sigma_{\text{glow}}$) and additively combine it into the linear frame: $I_{\text{bloomed}} = I_{\text{linear}} + \gamma_{\text{bloom}} \cdot \mathcal{G}_{\sigma_{\text{glow}}}(M)$. #### E. Emulsion Halation Simulation (`modules/halation.py`) - Physically model light penetrating through the emulsion and scattering off the film backing: - Extract saturated highlights in the linear color buffer using a high-luminance threshold $\tau_{\text{hal}} \in [0.75, 0.95]$. - Generate a chromatic dispersion kernel with asymmetric channel propagation: - Red channel: broad dispersion radius ($\sigma_R$). - Green channel: narrow dispersion radius ($\sigma_G \approx 0.25 \sigma_R$). - Blue channel: zero dispersion ($\sigma_B = 0$). - Add the dispersed energy back into the image: $$\Delta R = \kappa_{\text{hal}} \cdot \mathcal{G}_{\sigma_R}(M_{\text{hal}}), \quad \Delta G = 0.3 \cdot \kappa_{\text{hal}} \cdot \mathcal{G}_{\sigma_G}(M_{\text{hal}})$$ $$I_{\text{hal}} = [R + \Delta R, G + \Delta G, B]$$ - Ensure halation respects edge boundaries and does not blow out non-highlight midtones. #### F. Tonal Mapping & Color Grading (`modules/toning.py`) - **Parametric S-Curve Contrast & Crushed Blacks:** - Implement a continuous S-shaped tone mapping function in Linear space or Perceptual Luminance ($L^*$): $$f(x) = \frac{1}{1 + e^{-k (x - x_0)}}$$ normalized so $f(0) = \text{black\_point}$ and $f(1) = 1.0$. - Implement black-crushing: remap values below threshold $\tau_{\text{black}}$ sharply to zero to produce deep inked shadows. - **Teal-and-Orange Split Toning:** - Segment the image by luminance into shadow, midtone, and highlight regions using smooth sigmoid weights $w_s(L) = 1 - \sigma(L)$ and $w_h(L) = \sigma(L)$. - Push shadows toward cool teal/cyan: vector offset $\Delta_{\text{shadow}} = [-0.15 \cdot s, +0.05 \cdot s, +0.20 \cdot s]$. - Push highlights and midtones toward warm golden amber/orange: vector offset $\Delta_{\text{high}} = [+0.20 \cdot s, +0.10 \cdot s, -0.15 \cdot s]$. - **Selective Hue Vibrance Boost:** - Convert to HSL. Identify target hue sectors: - Orange/Red (hair, skin tones): Hue $\in [10^\circ, 40^\circ]$. - Denim Blue (textiles): Hue $\in [190^\circ, 240^\circ]$. - Apply Gaussian hue weighting to scale saturation dynamically: $$S' = S \cdot \left(1.0 + v \cdot \exp\left(-\frac{(H - H_{\text{target}})^2}{2\sigma_H^2}\right)\right)$$ while preventing out-of-gamut clipping. #### G. Procedural 35mm Film Grain (`modules/grain.py`) - Generate non-periodic, multi-octave pseudo-random noise arrays. - Modulate grain amplitude according to optical density/luminance response of photographic film: grain is most visible in the midtones and attenuated in deep shadows (due to silver density) and peak highlights: $$W_{\text{grain}}(L) = 4.0 \cdot L \cdot (1.0 - L)$$ where $L \in [0.0, 1.0]$ is pixel luminance. - Synthesize correlated chromatic grain: blend $85\%$ monochromatic grain with $15\%$ per-channel chromatic noise to reproduce authentic organic color dye clouds. - Add grain additively in linear color space: $I_{\text{grain}} = \text{clip}(I + W_{\text{grain}}(L) \cdot N(\mu=0, \sigma=\sigma_{\text{grain}}), 0.0, 1.0)$. --- ### 3. Implementation Requirements & Constraints 1. **No External Black-Box Filter Libraries:** Do not rely on high-level pre-built artistic filter wrappers or preset libraries. All mathematical algorithms (barrel distortion, blur kernels, split toning, halation dispersion, procedural noise) must be implemented directly using standard scientific computing libraries (`numpy`, `scipy.ndimage`, `cv2` for low-level image operations). 2. **Precision:** All color computations, filtering, and blending operations must be executed in 32-bit floating-point precision (`numpy.float32`). Image inputs must be normalized to $[0.0, 1.0]$ immediately upon ingestion and clipped/converted to standard output depths only at the final export step. 3. **Preset Configuration:** In `config/presets.py`, define a default configuration object whose parameters precisely calibrate the pipeline to render: - Strong direct on-camera flash with sharp drop shadow. - Distinct fluorescent ambient background tint. - Noticeable wide-angle barrel curvature ($k_1 \approx -0.12$). - Soft highlight bloom and edge diffusion ($1/4$ strength equivalent). - Pronounced red-orange halation on specular peaks and high-contrast edges. - Steep S-curve with inked black levels. - Saturated orange-red and denim-blue tones against teal shadows. - Organic 35mm film grain structure. 4. **Complete, Unabridged Code:** Provide the entire, functional codebase spanning every file defined in the architecture. Every file must contain complete imports, explicit type annotations, docstrings, error handling, parameter bounds checking, and concrete implementation logic. No ellipses (`...`), no `# TODO`, and no omitted functions are permitted.
Response not available
Response not available