File size: 4,937 Bytes
73828b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Blending SDXL's output back onto the composited tile.

Two strategies live here, both from the tuned reference script.

detail-recovery (default, and the one the reference script actually executes)
    Keep SDXL's result as the image, then add back the high- and mid-frequency
    detail that diffusion softened, taken from the pre-diffusion composite.
    SDXL supplies the photographic material response; the original projection
    supplies the product's actual grain and veining. Two scales matter
    separately: sigma 0.9 recovers surface texture, sigma 3.5 recovers the
    plank and vein structure that identifies the product.

realism-guide (alternative, defined in the reference script but not called)
    The inverse -- keep the projected tile as the image and transfer only
    SDXL's low-frequency illumination response and a clamped slice of its
    microdetail onto it, plus a small direct blend. More conservative: the
    product is mathematically almost untouched. Selectable through
    refine.blend_mode for materials where detail-recovery drifts too far.

Both write only inside the mask, and both are followed by a hard composite in
runner.py, so neither can alter a pixel the surface does not own.
"""

from __future__ import annotations

import cv2
import numpy as np
from PIL import Image

from services.refine.masks import mask_to_bool
from services.refine.profiles import detail_recovery_for


def recover_detail(
    generated: Image.Image,
    base: Image.Image,
    material_type: str | None,
) -> Image.Image:
    """Add the pre-diffusion composite's texture back onto SDXL's output."""
    generated_np = np.asarray(generated.convert("RGB")).astype(np.float32) / 255.0
    base_np = np.asarray(base.convert("RGB")).astype(np.float32) / 255.0

    fine_blur = cv2.GaussianBlur(base_np, (0, 0), sigmaX=0.9, sigmaY=0.9)
    fine_detail = base_np - fine_blur

    medium_blur = cv2.GaussianBlur(base_np, (0, 0), sigmaX=3.5, sigmaY=3.5)
    medium_detail = fine_blur - medium_blur

    strengths = detail_recovery_for(material_type)
    refined = (
        generated_np
        + fine_detail * strengths["fine"]
        + medium_detail * strengths["pattern"]
    )
    refined = np.clip(refined, 0.0, 1.0)
    return Image.fromarray((refined * 255.0).astype(np.uint8), mode="RGB")


def apply_diffusion_as_realism_guide(
    base_image: Image.Image,
    generated_image: Image.Image,
    mask,
    low_frequency_strength: float = 0.30,
    detail_strength: float = 0.60,
    direct_blend_strength: float = 0.12,
    low_blur_sigma: float = 18,
    detail_blur_sigma: float = 2.0,
    edge_guard: int = 8,
    feather_width: int = 16,
) -> Image.Image:
    """Transfer only SDXL's illumination response onto the projected tile."""
    if generated_image.size != base_image.size:
        generated_image = generated_image.resize(base_image.size, Image.Resampling.LANCZOS)

    base_u8 = np.asarray(base_image.convert("RGB"), dtype=np.uint8)
    generated_u8 = np.asarray(generated_image.convert("RGB"), dtype=np.uint8)
    base = base_u8.astype(np.float32) / 255.0
    generated = generated_u8.astype(np.float32) / 255.0

    inside = mask_to_bool(mask)

    # Feather in from the edge guard so the transition is gradual rather than
    # a step at exactly the distance SDXL was allowed to reach.
    distance = cv2.distanceTransform(inside.astype(np.uint8), cv2.DIST_L2, 5)
    blend_alpha = np.clip(
        (distance - float(edge_guard)) / float(max(feather_width, 1)), 0.0, 1.0
    ) * inside.astype(np.float32)

    def luma(image: np.ndarray) -> np.ndarray:
        return 0.2126 * image[..., 0] + 0.7152 * image[..., 1] + 0.0722 * image[..., 2]

    base_luma = luma(base)
    generated_luma = luma(generated)

    base_low = cv2.GaussianBlur(base_luma, (0, 0), sigmaX=low_blur_sigma, sigmaY=low_blur_sigma)
    generated_low = cv2.GaussianBlur(
        generated_luma, (0, 0), sigmaX=low_blur_sigma, sigmaY=low_blur_sigma
    )
    low_ratio = np.clip(generated_low / (base_low + 1e-5), 0.88, 1.12)
    low_ratio = 1.0 + (low_ratio - 1.0) * low_frequency_strength

    generated_detail_base = cv2.GaussianBlur(
        generated_luma, (0, 0), sigmaX=detail_blur_sigma, sigmaY=detail_blur_sigma
    )
    # Clamped tightly: unclamped, SDXL injects strong new veins and grain lines.
    detail_ratio = np.clip(generated_luma / (generated_detail_base + 1e-5), 0.92, 1.08)
    detail_ratio = 1.0 + (detail_ratio - 1.0) * detail_strength

    candidate = np.clip(base * low_ratio[..., None] * detail_ratio[..., None], 0.0, 1.0)
    candidate = np.clip(
        candidate * (1.0 - direct_blend_strength) + generated * direct_blend_strength, 0.0, 1.0
    )

    alpha = blend_alpha[..., None]
    output = np.clip(base * (1.0 - alpha) + candidate * alpha, 0.0, 1.0)
    output_u8 = (output * 255.0).astype(np.uint8)
    output_u8[~inside] = base_u8[~inside]
    return Image.fromarray(output_u8, mode="RGB")