"""Fast color-statistics harmonization using Lab color space transfer. Matches the foreground (tile composite) region's color distribution to the background (room) region. This is a zero-model, pure-numpy approach that runs in <20ms and handles the most visible artifact: color temperature mismatch between pasted tiles and the room's ambient lighting. Based on Reinhard et al. "Color Transfer between Images" (2001), adapted for masked foreground/background regions. """ from __future__ import annotations import cv2 import numpy as np def _rgb_to_lab(img: np.ndarray) -> np.ndarray: """Convert uint8 RGB to float32 Lab.""" bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) return cv2.cvtColor(bgr, cv2.COLOR_BGR2Lab).astype(np.float32) def _lab_to_rgb(lab: np.ndarray) -> np.ndarray: """Convert float32 Lab to uint8 RGB.""" lab_u8 = np.clip(lab, 0, 255).astype(np.uint8) bgr = cv2.cvtColor(lab_u8, cv2.COLOR_Lab2BGR) return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) def harmonize_color_transfer( composite: np.ndarray, mask: np.ndarray, strength: float = 0.7, ) -> np.ndarray: """Harmonize foreground region to match background color distribution. Args: composite: RGB uint8 image with tile already composited. mask: uint8 mask — 255 = tile region, 0 = background. strength: Blend strength (0 = no change, 1 = full transfer). Returns: Harmonized RGB uint8 image. """ if strength <= 0: return composite fg_mask = mask > 127 bg_mask = ~fg_mask if fg_mask.sum() < 100 or bg_mask.sum() < 100: return composite lab = _rgb_to_lab(composite) # Compute mean/std for each channel in foreground and background fg_pixels = lab[fg_mask] # (N, 3) bg_pixels = lab[bg_mask] # (M, 3) fg_mean = fg_pixels.mean(axis=0) fg_std = fg_pixels.std(axis=0) + 1e-6 bg_mean = bg_pixels.mean(axis=0) bg_std = bg_pixels.std(axis=0) + 1e-6 # Transfer: shift and scale foreground to match background stats # Only transfer chromatic channels (a, b) fully; attenuate lightness transfer # to preserve tile's intended brightness while matching color temperature. result = lab.copy() for c in range(3): channel = lab[:, :, c] transferred = (channel[fg_mask] - fg_mean[c]) * (bg_std[c] / fg_std[c]) + bg_mean[c] # For lightness (L channel), reduce transfer strength to preserve tile brightness channel_strength = strength * (0.3 if c == 0 else 1.0) result[:, :, c][fg_mask] = channel[fg_mask] * (1 - channel_strength) + transferred * channel_strength return _lab_to_rgb(result) def harmonize_with_local_lighting( composite: np.ndarray, original: np.ndarray, mask: np.ndarray, strength: float = 0.7, ) -> np.ndarray: """Enhanced harmonization: color transfer + local lighting adaptation. Uses the original room image to extract local lighting patterns and applies them to the tile region for more natural integration. Args: composite: RGB uint8 image with tile composited. original: RGB uint8 original room image (before tile). mask: uint8 mask — 255 = tile region, 0 = background. strength: Blend strength. Returns: Harmonized RGB uint8 image. """ # Step 1: Basic color transfer result = harmonize_color_transfer(composite, mask, strength) if original is None or strength <= 0: return result fg_mask = mask > 127 if fg_mask.sum() < 100: return result # Step 2: Extract local color cast from original room image # Blur original to get smooth lighting field sigma = max(15, min(original.shape[:2]) // 20) ksize = sigma * 2 + 1 original_blur = cv2.GaussianBlur( original.astype(np.float32), (ksize, ksize), sigma ) composite_blur = cv2.GaussianBlur( result.astype(np.float32), (ksize, ksize), sigma ) # Ratio of original-to-composite lighting in the tile region # This captures local color gradients (e.g., warmer near downlights) ratio = np.ones_like(original_blur) valid = composite_blur > 5 ratio[valid] = original_blur[valid] / composite_blur[valid] ratio = np.clip(ratio, 0.5, 2.0) # Apply local lighting ratio only in foreground result_f = result.astype(np.float32) local_strength = strength * 0.4 # Subtle local lighting adaptation adjusted = result_f * (1.0 + (ratio - 1.0) * local_strength) adjusted = np.clip(adjusted, 0, 255) output = result.copy() output[fg_mask] = adjusted[fg_mask].astype(np.uint8) return output