File size: 8,959 Bytes
c7a38a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Coverage repair, without AI: where each wallpaper layer is finally shown.

The editor's coverage misses wall in a few systematic places: a halo around doors,
windows and frames (protected classes are cut out with a margin), slivers behind
furniture, and holes between chair backs. The browser renders each layer a little
beyond its mask with the same frozen mapping (the support); here the original
photo decides which of those extra pixels are really this wall:

- never an object, ceiling, floor, skirting, door, window or frame (semantic class map),
- never a pixel of another surface of the room (selected or not),
- only pixels that still look like the bare wall (colour keyed against it),
- only gaps that touch the wall and are small; anything else stays the photo.

Ambiguous pixels (colour neither clearly wall nor clearly object) are left alone.
Floors are not repaired; their coverage is the editor's.
"""

from __future__ import annotations

from dataclasses import dataclass

import cv2
import numpy as np

from services.enhance.composite import stacked
from services.enhance.job_context import JobContext
from services.enhance.validate import Layer
from services.floor.edge_refinement import guided_filter
from services.wall.components import WALL_PROTECTED_CLASSES
from services.wall.edges import _bare_wall
from state import class_ids

# Never papered by a repair.
PROTECTED_CLASSES = WALL_PROTECTED_CLASSES | {
    "floor", "rug", "stairs", "windowpane", "sky", "light", "chandelier", "sconce",
    "television", "screen", "crt screen", "monitor", "poster", "clock", "radiator", "vase",
}
WALL_CLASSES = {"wall"}
# Colour keying against the bare wall (OpenCV Lab units), as in services/wall/edges.py.
CHROMA_FROM, CHROMA_TO = 6.0, 14.0
LIGHTNESS_FROM, LIGHTNESS_TO = 18.0, 34.0
# A pixel is wall below this objectness and an object above AMBIGUOUS_TO; between, it is left alone.
WALL_BELOW = 0.35
# A repaired gap must touch the wall and be no larger than this (fraction of the image).
MAX_GAP_AREA = 0.02
# Of a gap's own pixels (inside the support, not protected), this share must look like wall.
MIN_GAP_WALL_SHARE = 0.6
# Trimming the editor's bleed onto a protected object: at most this share of the coverage.
MAX_TRIM_SHARE = 0.03
TRIM_OBJECT_FROM = 0.75
EDGE_RADIUS_RATIO = 0.002  # guided-filter radius, of the short side


@dataclass
class RefinedLayer:
    layer: Layer
    alpha: np.ndarray  # float32 0..1: final coverage
    repaired: np.ndarray  # bool: pixels added by the repair
    trimmed: np.ndarray  # bool: editor pixels removed
    rejected_components: int


def _protected(context: JobContext) -> np.ndarray:
    if context.seg_map is None:
        return np.zeros(context.original.shape[:2], bool)
    return np.isin(context.seg_map, class_ids(PROTECTED_CLASSES))


def _objectness(photo_lab: np.ndarray, bare_lab: np.ndarray) -> np.ndarray:
    """0 (looks like the bare wall) .. 1 (clearly something else)."""
    chroma = np.hypot(photo_lab[..., 1] - bare_lab[..., 1], photo_lab[..., 2] - bare_lab[..., 2])
    lightness = np.abs(photo_lab[..., 0] - bare_lab[..., 0])
    score = np.maximum(
        np.clip((chroma - CHROMA_FROM) / (CHROMA_TO - CHROMA_FROM), 0.0, 1.0),
        np.clip((lightness - LIGHTNESS_FROM) / (LIGHTNESS_TO - LIGHTNESS_FROM), 0.0, 1.0),
    )
    return cv2.GaussianBlur(score.astype(np.float32), (0, 0), 0.7)


def refine_layers(layers: list[Layer], context: JobContext) -> list[RefinedLayer]:
    original = context.original
    height, width = original.shape[:2]
    photo_lab = cv2.cvtColor(original, cv2.COLOR_RGB2LAB).astype(np.float32)
    protected = _protected(context)
    is_wall_class = (
        np.isin(context.seg_map, class_ids(WALL_CLASSES)) if context.seg_map is not None else np.zeros((height, width), bool)
    )
    # Every surface of the room: a repair never crosses onto another one.
    surfaces = {segment_id: segment.mask for segment_id, segment in context.segments.items()}
    guide = original.astype(np.float32) / 255.0
    radius = max(1, round(EDGE_RADIUS_RATIO * min(height, width)))

    refined: list[RefinedLayer] = []
    for layer in layers:
        editor = layer.coverage
        core = editor > 0.5
        if layer.kind != "wall":
            refined.append(RefinedLayer(layer, editor.copy(), np.zeros_like(core), np.zeros_like(core), 0))
            continue
        segment_mask = context.segments[layer.segment_id].mask
        other_surfaces = np.zeros_like(core)
        for segment_id, mask in surfaces.items():
            if segment_id != layer.segment_id:
                other_surfaces |= mask
        other_layers = np.zeros_like(core)
        for other in layers:
            if other is not layer:
                other_layers |= other.support

        bare = _bare_wall(original, _typical_wall(photo_lab, core).astype(np.uint8))
        objectness = _objectness(photo_lab, bare)

        # Gaps: rendered by the browser, not shown by the editor, and not anything else.
        gap = layer.support & ~segment_mask & ~protected & ~other_surfaces & ~other_layers
        if context.seg_map is None:
            gap &= False  # without the class map nothing can be told apart: leave the photo
        looks_wall = objectness < WALL_BELOW
        candidates = gap & looks_wall
        repaired = np.zeros_like(core)
        rejected = 0
        count, labels, stats, _ = cv2.connectedComponentsWithStats(gap.astype(np.uint8), connectivity=8)
        if count > 1:
            accepted_count = np.bincount(labels.ravel(), weights=candidates.ravel().astype(np.float64), minlength=count)
            wall_class_count = np.bincount(labels.ravel(), weights=is_wall_class.ravel().astype(np.float64), minlength=count)
            touching = np.zeros(count, bool)
            touching[np.unique(labels[cv2.dilate(core.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool) & gap])] = True
            for i in range(1, count):
                area = stats[i, cv2.CC_STAT_AREA]
                share = accepted_count[i] / area
                if not touching[i] or area > MAX_GAP_AREA * core.size or share < MIN_GAP_WALL_SHARE:
                    rejected += 1
                    continue
                # Mostly not labelled wall: only the pixels that both look like wall and touch it.
                if wall_class_count[i] / area < 0.5 and share < 0.85:
                    rejected += 1
                    continue
                repaired |= (labels == i) & candidates
            # Only what stays connected to the wall: a patch of wall colour beyond a chair is not this wall.
            joined_count, joined = cv2.connectedComponents((core | repaired).astype(np.uint8), connectivity=8)
            keep = np.zeros(joined_count, bool)
            keep[np.unique(joined[core])] = True
            repaired &= keep[joined]

        # Bleed of the editor onto a protected object (a frame edge, a door casing); a larger
        # disagreement is the class map's doubt, not a bleed, and the editor's coverage stays.
        bleed = core & protected & (objectness >= TRIM_OBJECT_FROM)
        trimmed = bleed if bleed.sum() <= MAX_TRIM_SHARE * core.sum() else np.zeros_like(core)

        hard = (core & ~trimmed) | repaired
        alpha = editor.copy()
        alpha[trimmed] = 0.0
        if repaired.any():
            # Repaired pixels follow the photo's own edges (guided filter) and fade out where the
            # pixel starts to look like the object next to it; nothing outside them is touched.
            snapped = np.clip(guided_filter(guide, hard.astype(np.float32), radius, 1e-3), 0.0, 1.0)
            alpha[repaired] = np.minimum(np.maximum(snapped[repaired], 0.5), 1.0 - objectness[repaired])
        alpha = np.where(layer.support, alpha, 0.0).astype(np.float32)
        refined.append(RefinedLayer(layer, alpha, repaired, trimmed & core, rejected))

    # Overlapping layers stack like the editor draws them (later on top), so a pixel never mixes
    # two designs: each layer's effective alpha is what the layers above it leave visible.
    for item, visible in zip(refined, stacked([item.alpha for item in refined])):
        item.alpha = visible
    return refined


def _typical_wall(photo_lab: np.ndarray, core: np.ndarray) -> np.ndarray:
    """The wall's own pixels that look like its paint: a stain, a switch or a shadowed object
    inside the mask must not teach the bare-wall estimate that it is wall colour."""
    values = photo_lab[core]
    if len(values) < 50:
        return core
    median = np.median(values, axis=0)
    spread = np.median(np.abs(values - median), axis=0) + np.array([4.0, 2.0, 2.0], np.float32)
    chroma = np.hypot(photo_lab[..., 1] - median[1], photo_lab[..., 2] - median[2])
    typical = (chroma <= 4 * max(spread[1], spread[2])) & (np.abs(photo_lab[..., 0] - median[0]) <= 6 * spread[0])
    kept = core & typical
    return kept if kept.sum() >= 0.5 * core.sum() else core