File size: 7,252 Bytes
fbb8e8b
485bb51
fbb8e8b
 
 
485bb51
 
 
 
 
fbb8e8b
485bb51
 
 
 
 
 
 
 
 
 
bdc9170
485bb51
 
fbb8e8b
 
 
 
 
485bb51
 
fbb8e8b
 
 
 
 
 
485bb51
 
 
 
 
 
bdc9170
fbb8e8b
 
 
 
 
bdc9170
485bb51
bdc9170
fbb8e8b
bdc9170
 
fbb8e8b
bdc9170
 
 
 
 
 
fbb8e8b
 
 
 
bdc9170
485bb51
fbb8e8b
bdc9170
fbb8e8b
bdc9170
 
fbb8e8b
 
 
 
 
 
 
 
bdc9170
fbb8e8b
485bb51
bdc9170
fbb8e8b
 
bdc9170
fbb8e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdc9170
 
fbb8e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdc9170
 
 
fbb8e8b
bdc9170
 
fbb8e8b
 
 
 
bdc9170
fbb8e8b
bdc9170
fbb8e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""Advanced tile harmonization via lighting transfer + color adaptation.

Produces photorealistic results by transferring the room's lighting pattern,
color temperature, and local contrast onto the tile composite. No diffusion
model required — works on any hardware with zero extra VRAM.
"""

from __future__ import annotations

import time
import traceback

import cv2
import numpy as np


def generate_tile_inpaint(
    room_image: np.ndarray,
    mask: np.ndarray,
    tile_composite: np.ndarray,
    strength: float = 0.85,
    num_steps: int = 25,
    tile_reference: np.ndarray | None = None,
) -> dict:
    """Generate photorealistic tile rendering by lighting/color transfer.

    Applies the room's spatial lighting pattern, color temperature, and
    local contrast to the tile region, producing a result where tiles
    look naturally embedded in the room.

    Args:
        room_image: RGB uint8 — original room (before tiles).
        mask: uint8 — floor region (255 = tile area).
        tile_composite: RGB uint8 — shader-composited image.
        strength: Harmonization intensity (0.0-1.0).
        num_steps: unused, kept for API compat.
        tile_reference: unused, kept for API compat.

    Returns:
        Dict with "image" (RGB uint8), "mode", "elapsed_ms".
    """
    t0 = time.perf_counter()

    try:
        result = _harmonize_with_lighting_transfer(
            composite=tile_composite,
            original=room_image,
            mask=mask,
            strength=strength,
        )

        elapsed = (time.perf_counter() - t0) * 1000
        print(f"[DIFFUSION] Lighting transfer harmonization: {elapsed:.0f}ms", flush=True)

        return {
            "image": result,
            "mode": "generate",
            "elapsed_ms": round(elapsed, 1),
        }

    except Exception as exc:
        elapsed = (time.perf_counter() - t0) * 1000
        print(f"[DIFFUSION] Harmonization failed ({elapsed:.0f}ms): {exc}", flush=True)
        traceback.print_exc()
        from services.harmonization.harmonizer import harmonize_composite
        return harmonize_composite(tile_composite, mask, room_image, strength, "fast")


def _harmonize_with_lighting_transfer(
    composite: np.ndarray,
    original: np.ndarray,
    mask: np.ndarray,
    strength: float,
) -> np.ndarray:
    """Multi-stage harmonization pipeline.

    Stage 1: Extract room's spatial lighting map (low-frequency luminance)
    Stage 2: Transfer lighting map onto tile region
    Stage 3: Match color temperature (chrominance transfer in LAB)
    Stage 4: Match local contrast/texture characteristics
    Stage 5: Feather edges for seamless blending
    """
    h, w = composite.shape[:2]
    fg = mask > 127

    if not np.any(fg):
        return composite

    # Ensure original matches composite size
    if original.shape[:2] != (h, w):
        original = cv2.resize(original, (w, h))

    # --- STAGE 1: Extract room lighting map ---
    # Use a large gaussian blur to get the low-frequency lighting pattern
    # This captures gradients like "darker near walls, brighter in center"
    orig_lab = cv2.cvtColor(original, cv2.COLOR_RGB2LAB).astype(np.float64)
    comp_lab = cv2.cvtColor(composite, cv2.COLOR_RGB2LAB).astype(np.float64)

    # Compute lighting map at multiple scales for robust transfer
    blur_large = max(h, w) // 3 | 1   # Captures room-wide gradients
    blur_medium = max(h, w) // 8 | 1  # Captures local lighting variation
    orig_light_large = cv2.GaussianBlur(orig_lab[:, :, 0], (blur_large, blur_large), 0)
    orig_light_medium = cv2.GaussianBlur(orig_lab[:, :, 0], (blur_medium, blur_medium), 0)
    comp_light_large = cv2.GaussianBlur(comp_lab[:, :, 0], (blur_large, blur_large), 0)
    comp_light_medium = cv2.GaussianBlur(comp_lab[:, :, 0], (blur_medium, blur_medium), 0)

    # --- STAGE 2: Transfer spatial lighting pattern ---
    result_lab = comp_lab.copy()

    # Ratio-based lighting transfer at large scale (room gradient)
    safe_comp = np.maximum(comp_light_large, 1.0)
    light_ratio_large = orig_light_large / safe_comp
    light_ratio_large = np.clip(light_ratio_large, 0.5, 2.0)

    # Medium-scale local adjustment
    safe_comp_med = np.maximum(comp_light_medium, 1.0)
    light_ratio_medium = orig_light_medium / safe_comp_med
    light_ratio_medium = np.clip(light_ratio_medium, 0.6, 1.6)

    # Combine multi-scale ratios (large = 60%, medium = 40%)
    combined_ratio = light_ratio_large * 0.6 + light_ratio_medium * 0.4
    combined_ratio = np.clip(combined_ratio, 0.55, 1.8)

    # Apply to tile luminance
    result_lab[fg, 0] *= combined_ratio[fg]

    # --- STAGE 3: Color temperature transfer (LAB a/b channels) ---
    bg = ~fg

    for ch in [1, 2]:  # a and b channels
        fg_vals = comp_lab[fg, ch]
        bg_vals = orig_lab[bg, ch]

        if len(fg_vals) < 10 or len(bg_vals) < 10:
            continue

        fg_mean = fg_vals.mean()
        fg_std = max(fg_vals.std(), 0.5)
        bg_mean = bg_vals.mean()
        bg_std = max(bg_vals.std(), 0.5)

        # Reinhard color transfer on chrominance
        transferred = (fg_vals - fg_mean) * (bg_std / fg_std) + bg_mean

        # Moderate blending — enough to shift color temp, not destroy tile color
        blend = min(strength * 0.6, 0.5)
        result_lab[fg, ch] = fg_vals * (1.0 - blend) + transferred * blend

    # --- STAGE 4: Match luminance statistics ---
    fg_L = result_lab[fg, 0]
    bg_L = orig_lab[bg, 0]

    if len(fg_L) > 10 and len(bg_L) > 10:
        fg_mean_L = fg_L.mean()
        fg_std_L = max(fg_L.std(), 0.5)
        bg_mean_L = bg_L.mean()
        bg_std_L = max(bg_L.std(), 0.5)

        # Partially transfer luminance statistics (subtle, ~30% strength)
        stat_blend = min(strength * 0.35, 0.35)
        target_L = (fg_L - fg_mean_L) * (bg_std_L / fg_std_L) + bg_mean_L
        result_lab[fg, 0] = fg_L * (1.0 - stat_blend) + target_L * stat_blend

    # Clamp LAB to valid range
    result_lab[:, :, 0] = np.clip(result_lab[:, :, 0], 0, 255)
    result_lab[:, :, 1] = np.clip(result_lab[:, :, 1], 0, 255)
    result_lab[:, :, 2] = np.clip(result_lab[:, :, 2], 0, 255)
    result = cv2.cvtColor(result_lab.astype(np.uint8), cv2.COLOR_LAB2RGB)

    # --- STAGE 5: Edge feathering ---
    output = _feathered_blend(composite, result, mask, feather_px=10)

    # --- STAGE 6: Overall strength blending ---
    if strength < 1.0:
        output = cv2.addWeighted(
            composite, 1.0 - strength,
            output, strength,
            0,
        )

    return output


def _feathered_blend(
    original: np.ndarray,
    harmonized: np.ndarray,
    mask: np.ndarray,
    feather_px: int = 10,
) -> np.ndarray:
    """Blend harmonized result into original with feathered mask edges."""
    alpha = mask.astype(np.float32) / 255.0

    if feather_px > 0:
        ksize = feather_px * 2 + 1
        alpha = cv2.GaussianBlur(alpha, (ksize, ksize), 0)

    if alpha.shape[:2] != original.shape[:2]:
        alpha = cv2.resize(alpha, (original.shape[1], original.shape[0]))

    alpha3 = alpha[:, :, np.newaxis]
    blended = original.astype(np.float32) * (1.0 - alpha3) + harmonized.astype(np.float32) * alpha3
    return np.clip(blended, 0, 255).astype(np.uint8)