File size: 4,651 Bytes
485bb51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""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