File size: 12,284 Bytes
d7b5c2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d2f042
 
 
 
 
 
 
 
d7b5c2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""Wall surface mask refinement β€” the wall counterpart to services/floor/mask.py.

Background
----------
Wall masks used to be authored entirely by 3D plane assignment inside
``wall_surface_components``: a pixel survived only if its back-projected normal
matched a fitted wall plane. Low-texture surfaces (marble, painted plaster)
produce smooth, ambiguous depth, so large organic patches were silently
discarded and nothing put them back. The result looked like torn paper.

The floor never had this problem, because for floors the geometry check is
*advisory*::

    surface = (surface & depth_keep).astype(np.uint8)
    surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1)

Geometry is allowed to refine the floor's edges but never to delete a pixel
segmentation was confident about. This module gives walls the same guarantee:
fill the holes back in, clamp to what segmentation actually called wall, and
never grow past a structural boundary.

Barriers vs reclaimables
------------------------
Not every object touching a wall should be treated the same way:

* **Barrier** β€” ceiling, floor, sky, doors, windows. These are where the wall
  *ends*. Growing into them is the "tile bleeding onto the ceiling" bug, so the
  mask must never cross them.
* **Reclaimable** β€” mirrors, paintings, televisions, curtains, and furniture
  standing in front of the wall. These sit *on* an otherwise continuous wall.
  The tile belongs behind them, and they are re-drawn on top via the segment's
  occlusion mask (the same trick the floor uses for furniture). Cutting them
  out of the mask instead is what produced the ragged holes around mirrors.
"""

from __future__ import annotations

import cv2
import numpy as np

from services.floor.edge_coverage import improve_surface_edge_coverage, scaled_odd_kernel_size
from services.image.edge_snap import snap_mask_to_image_edges
from state import class_ids
from utils import seg_class_mask

# Where a wall stops. The mask may never expand across these.
#
# Only barriers are enumerated. Everything else counts as reclaimable β€” see
# wall_region_masks for why listing the reclaimables instead does not work.
WALL_BARRIER_CLASSES = {"ceiling", "sky", "building", "floor", "door", "window"}


def contour_fill(mask: np.ndarray) -> np.ndarray:
    """Fill interior holes by re-drawing external contours solid.

    This is the single most important repair: the patches dropped by plane
    assignment are enclosed by surviving wall pixels, so refilling each external
    contour restores them without touching the component's true outline.
    """
    mask_u8 = mask.astype(np.uint8, copy=False)
    if not mask_u8.any():
        return mask_u8
    contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return mask_u8
    filled = np.zeros(mask_u8.shape[:2], dtype=np.uint8)
    cv2.drawContours(filled, contours, -1, 1, cv2.FILLED)
    return filled


def convex_hull_mask(mask: np.ndarray) -> np.ndarray:
    """Solid convex hull of a mask.

    Plane assignment erodes a component's *outer* boundary as well as punching
    interior holes, and contour_fill cannot repair an open edge. The hull spans
    the region the wall would occupy if the boundary were intact; clipping it to
    pixels segmentation actually called wall turns it into a safe repair.
    """
    mask_u8 = mask.astype(np.uint8, copy=False)
    if not mask_u8.any():
        return mask_u8
    points = cv2.findNonZero(mask_u8)
    if points is None or len(points) < 3:
        return mask_u8
    hull = cv2.convexHull(points).reshape(-1, 2).astype(np.int32)
    filled = np.zeros(mask_u8.shape[:2], dtype=np.uint8)
    cv2.fillConvexPoly(filled, hull, 1)
    return filled


def extend_vertically_within(mask: np.ndarray, allowed: np.ndarray, reach_px: int) -> np.ndarray:
    """Grow a mask up and down, but only across pixels that are `allowed`.

    A geodesic dilation restricted to the vertical axis. Walls run continuously
    from floor to ceiling, so extending a component vertically until it runs out
    of wall recovers the ceiling and skirting joins that plane assignment eats
    away β€” the ragged top edge that convex-hull repair cannot reach, because the
    hull can never extend above the highest surviving pixel.

    Vertical-only is what makes this safe: two walls meeting at a corner are
    side by side, so this can never merge them. `allowed` excludes barriers, so
    growth halts at the ceiling rather than bleeding onto it.
    """
    step = 9  # each pass reaches (step // 2) px further in both directions
    kernel = np.ones((step, 1), dtype=np.uint8)
    seed = mask.astype(np.uint8, copy=True)
    grown = seed.copy()
    allowed_u8 = allowed.astype(np.uint8)
    for _ in range(max(1, int(round(reach_px / (step // 2))))):
        previous = grown
        # Union the seed back in every pass. Intersecting alone would delete any
        # part of the seed lying outside the growth medium β€” which silently threw
        # away mirrors and other reclaimed objects, since those are not wall.
        grown = cv2.bitwise_or(
            cv2.bitwise_and(cv2.dilate(grown, kernel), allowed_u8),
            seed,
        )
        if np.array_equal(grown, previous):
            break
    return grown


def keep_connected_to(mask: np.ndarray, seed: np.ndarray) -> np.ndarray:
    """Drop islands of `mask` that do not touch `seed`.

    Hull repair spans a convex quad, so where a wall wraps around a doorway the
    hull reaches across the opening and picks up whatever wall lies beyond it β€”
    a different wall, at a different depth, needing its own transform. Requiring
    contiguity with the original component keeps the repair local.
    """
    mask_u8 = mask.astype(np.uint8, copy=False)
    seed_bool = seed.astype(bool)
    if not mask_u8.any() or not seed_bool.any():
        return mask_u8
    count, labels = cv2.connectedComponents(mask_u8, connectivity=8)
    if count <= 2:
        return mask_u8
    keep = np.unique(labels[seed_bool])
    keep = keep[keep > 0]
    if keep.size == 0:
        return mask_u8
    return np.isin(labels, keep).astype(np.uint8)


def wall_region_masks(seg_map: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Split the scene into (raw wall class, barriers, reclaimable objects).

    Reclaimable is defined by exclusion: anything that is neither wall nor a
    barrier. Enumerating the reclaimable classes instead looks tidier but loses
    quietly -- a wall-mounted television is often labelled `screen`, which was
    absent from OCCLUDER_CLASSES, so it fell into neither set and got clamped
    away, punching a TV-shaped hole through the middle of the wall.

    Defining it by exclusion cannot miss an object, and it is safe because
    `allowed` only ever preserves pixels that hole filling has already reached:
    hull repair and vertical growth are both clipped to the wall class itself,
    so nothing can run away into the room.
    """
    wall_raw = seg_class_mask(seg_map, class_ids({"wall"}))
    barrier = seg_class_mask(seg_map, class_ids(WALL_BARRIER_CLASSES))
    reclaimable = np.ones_like(wall_raw)
    reclaimable[barrier > 0] = 0   # barriers win, so the mask cannot leak through a door
    reclaimable[wall_raw > 0] = 0
    return wall_raw, barrier, reclaimable


def refine_wall_component_mask(
    component_mask: np.ndarray,
    wall_class_mask: np.ndarray,
    reclaimable_mask: np.ndarray,
    barrier_mask: np.ndarray,
    image_rgb: np.ndarray | None = None,
) -> tuple[np.ndarray, dict]:
    """Repair one wall component: fill holes, close gaps, clamp to the wall.

    Parameters
    ----------
    component_mask
        Raw component straight out of plane assignment / connected components.
    wall_class_mask
        Pixels segmentation called wall. This is the medium vertical growth
        travels through β€” deliberately *not* the reclaimables, because a sofa or
        cabinet standing against the wall reaches the floor, and growing through
        it would let one wall swallow half the room.
    reclaimable_mask
        Objects mounted on / standing in front of the wall. The component may
        occupy these (tile is drawn behind them) but only where hole filling
        reaches them, never by unbounded growth.
    barrier_mask
        Pixels the component may never occupy (ceiling, floor, doors, windows).
        Also passed to the edge-repair dilation so it cannot bleed.
    """
    wall_only = wall_class_mask.astype(bool)
    allowed = wall_only | reclaimable_mask.astype(bool)
    barrier = barrier_mask.astype(bool)
    seed = component_mask.astype(bool)
    before = int(component_mask.sum())

    h, w = component_mask.shape[:2]
    close_size = scaled_odd_kernel_size(h, w, 0.008, minimum=3)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size))

    # Bridge hairline cracks first so contour fill sees one region, not many.
    refined = cv2.morphologyEx(component_mask.astype(np.uint8), cv2.MORPH_CLOSE, kernel)
    refined = contour_fill(refined)
    refined = _clamp(refined, allowed, barrier)

    # Recover the eroded outer boundary. contour_fill only closes holes that are
    # enclosed by surviving pixels; where plane assignment ate into the edge of
    # the wall (typically the ceiling join and around door frames) the gap is
    # open, so filling contours cannot reach it. The convex hull spans the intact
    # wall.
    #
    # Clipped to wall pixels only, never to `allowed`. The hull of a wall spans a
    # large quad, and intersecting that with furniture-inclusive `allowed` swept
    # in the TV cabinet, speakers and coffee table β€” 265k px of wall became 612k.
    # Objects are reclaimed by contour_fill above, which requires them to be
    # genuinely enclosed by wall, and that is the conservative behaviour we want.
    hull = convex_hull_mask(refined)
    refined = ((refined.astype(bool)) | (hull.astype(bool) & wall_only)).astype(np.uint8)
    refined = _clamp(refined, allowed, barrier)
    refined = keep_connected_to(refined, seed)

    # The hull cannot reach above the highest surviving pixel, so the ceiling and
    # skirting joins are still short. Grow vertically to walk the rest of the
    # way β€” through wall pixels only, and only far enough to cross a ragged
    # edge. An earlier version grew through `allowed` with a 25% reach and one
    # wall swallowed the room: it travelled down through the TV cabinet, absorbed
    # the neighbouring wall, and confidence fell from 0.91 to 0.70.
    reach = max(8, int(round(min(h, w) * 0.08)))
    refined = extend_vertically_within(refined, wall_only, reach)
    refined = _clamp(refined, allowed, barrier)
    refined = keep_connected_to(refined, seed)

    refined, edge_metadata = improve_surface_edge_coverage(refined, barrier)
    refined = _clamp(refined, allowed, barrier)
    refined = keep_connected_to(refined, seed)

    # Everything above is ellipse morphology, which scallops a straight
    # architectural line. Snap the boundary back onto the edge the photo
    # actually shows, then re-apply the semantic clamp -- the filter knows about
    # image edges, not about classes, so on its own it would happily drift a few
    # pixels onto the ceiling.
    # Skip the guided filter for small walls β€” the 7 box filters on the full
    # image cost ~200-500ms per wall and small walls don't benefit much.
    if int(refined.sum()) >= 50000:
        snapped = snap_mask_to_image_edges(refined, image_rgb)
        snapped = _clamp(snapped, allowed, barrier)
        snapped = keep_connected_to(snapped, seed)
        if snapped.any():
            refined = snapped

    after = int(refined.sum())
    metadata = {
        f"wallEdge{key[0].upper()}{key[1:]}": value
        for key, value in edge_metadata.items()
    }
    metadata.update({
        "wallMaskPixelsBefore": before,
        "wallMaskPixelsAfter": after,
        "wallMaskPixelsRecovered": after - before,
    })
    return refined, metadata


def _clamp(mask: np.ndarray, allowed: np.ndarray, barrier: np.ndarray) -> np.ndarray:
    clamped = (mask.astype(bool) & allowed).astype(np.uint8)
    clamped[barrier] = 0
    return clamped