"""Compositing the frozen wallpaper layers over the original photo, in linear light. result = original * (1 - Σ alpha) + Σ alpha_l * layer_l * gain_l * tint_l Outside every layer's alpha the result is the original photo's bytes, exactly. """ from __future__ import annotations import io import numpy as np from PIL import Image _SRGB_TO_LINEAR = np.array( [((v / 255.0) / 12.92) if v / 255.0 <= 0.04045 else (((v / 255.0) + 0.055) / 1.055) ** 2.4 for v in range(256)], np.float32, ) LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32) def to_linear(rgb: np.ndarray) -> np.ndarray: return _SRGB_TO_LINEAR[rgb] def to_srgb(linear: np.ndarray) -> np.ndarray: linear = np.clip(linear, 0.0, 1.0) srgb = np.where(linear <= 0.0031308, linear * 12.92, 1.055 * np.power(linear, 1 / 2.4) - 0.055) return np.clip(np.rint(srgb * 255.0), 0, 255).astype(np.uint8) def stacked(alphas: list[np.ndarray]) -> list[np.ndarray]: """Alphas in drawing order (bottom first) -> what each one shows once the later ones cover it.""" above = np.zeros(alphas[0].shape, np.float32) if alphas else None visible: list[np.ndarray] = [] for alpha in reversed(alphas): shown = (alpha * (1.0 - above)).astype(np.float32) visible.append(shown) above = above + shown return visible[::-1] def composite( original: np.ndarray, layers: list[np.ndarray], alphas: list[np.ndarray], gains: list[np.ndarray] | None = None, tints: list[np.ndarray] | None = None, ) -> np.ndarray: """uint8 RGB. `gains` are per-pixel multipliers (H, W), `tints` per-channel multipliers (3,).""" total = np.zeros(original.shape[:2], np.float32) for alpha in alphas: total += alpha total = np.minimum(total, 1.0) touched = total > 0 out = original.copy() if not touched.any(): return out rows, cols = np.nonzero(touched) base = to_linear(original[rows, cols]) * (1.0 - total[rows, cols])[:, None] for index, (layer, alpha) in enumerate(zip(layers, alphas)): a = alpha[rows, cols] if not a.any(): continue colour = to_linear(layer[rows, cols]) if gains is not None: colour = colour * gains[index][rows, cols][:, None] if tints is not None: colour = colour * tints[index][None, :] base += colour * a[:, None] out[rows, cols] = to_srgb(base) return out def encode_jpeg(image: np.ndarray, quality: int = 95) -> bytes: buffer = io.BytesIO() Image.fromarray(image).save(buffer, format="JPEG", quality=quality, subsampling=0) return buffer.getvalue()