File size: 13,753 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""Wall discovery: split the semantic wall mask into one region per physical wall.

Functions
---------
discover_wall_components - wall regions (full-res masks + fitted planes) for a room

Splitting and plane fitting run on a strided copy of the segmentation and
geometry maps (long side <= WALL_WORK_MAX_DIMENSION). Each wall's final
outline, like the floor's, comes from the full-resolution segmentation; the
low-resolution pieces only decide which wall owns each pixel. Walls use their
own plane budget (WALL_MAX_PLANES), so the floor's `max_planes` is never touched.
"""

from __future__ import annotations

import math
from dataclasses import dataclass

import cv2
import numpy as np

from config.models import DEPTH_MODEL_NAME
from config.surface import (
    SURFACE_MIN_PLANE_PIXELS,
    SURFACE_NORMAL_SMOOTHING_KERNEL,
    WALL_COPLANAR_ANGLE_DEGREES,
    WALL_COPLANAR_OFFSET_METERS,
    WALL_EDGE_STRAIGHTEN_RATIO,
    WALL_MAX_NORMAL_Y,
    WALL_MAX_PLANES,
    WALL_MAX_SEGMENTS,
    WALL_WORK_MAX_DIMENSION,
)
from services.geometry.camera import backproject_depth, pixel_intrinsics_from_model
from services.geometry.multi_plane import assign_points_to_surface_planes, fit_multi_surface_planes
from services.geometry.normals import compute_normals_from_points, normalize_vectors, smooth_normal_map
from services.geometry.plane_fitting import refine_plane
from services.image.polygons import straighten_mask_edges
from state import OCCLUDER_CLASSES, PRIMARY_FLOOR_CLASSES, class_ids
from utils import seg_class_mask

# Classes cut out of walls before splitting; they bridge physically separate walls.
WALL_PROTECTED_CLASSES = OCCLUDER_CLASSES | {
    "door", "window", "column", "base", "railing", "ceiling",
    "building", "painting", "mirror", "curtain",
}
# Morphology radius as a fraction of the short image side (matches the old full-res value).
# Only used to separate walls at working resolution, never to cut the final outline.
PROTECTED_DILATION_RATIO = 0.006
# Light speck cleanup of the full-resolution outline (fraction of the short side).
OUTLINE_CLEANUP_RATIO = 0.002
# Wall ownership is taken from pieces blurred by this many working-res pixels per
# dilation radius, so the separation margin is filled and wall seams are smooth.
OWNERSHIP_SIGMA_SCALE = 1.5
OWNERSHIP_MIN_WEIGHT = 0.02
# Points sampled when refitting each wall's final plane.
PLANE_REFIT_SAMPLES = 20000
MIN_DEPTH_METERS = 0.05


@dataclass(frozen=True)
class WallPlane:
    origin: np.ndarray
    normal: np.ndarray


@dataclass
class WallComponent:
    mask: np.ndarray        # full-resolution uint8 mask
    work_mask: np.ndarray   # same wall at working resolution
    plane: WallPlane | None
    area: int               # full-resolution pixel count


@dataclass
class WallDiscovery:
    components: list[WallComponent]
    vertical: np.ndarray     # unit "up" direction (camera +Y hemisphere) from the floor
    stride: int
    geometry_used: bool


def discover_wall_components(seg_map: np.ndarray, geometry: dict | None, min_area: int) -> WallDiscovery:
    """Find up to WALL_MAX_SEGMENTS walls, ordered left to right."""
    full_h, full_w = seg_map.shape[:2]
    stride = max(1, math.ceil(max(full_h, full_w) / WALL_WORK_MAX_DIMENSION))
    seg_low = seg_map[::stride, ::stride]
    min_area_low = max(1, min_area // (stride * stride))

    wall_low = _clean_wall_mask(seg_low)
    point_maps = _working_point_maps(geometry, stride, full_w, full_h)
    vertical = _vertical_reference(seg_low, point_maps)

    pieces: list[tuple[np.ndarray, WallPlane | None]] = []
    count, labels, stats, _ = cv2.connectedComponentsWithStats(wall_low, connectivity=8)
    for region_id in range(1, count):
        if int(stats[region_id, cv2.CC_STAT_AREA]) < min_area_low:
            continue
        region = labels == region_id
        pieces.extend(_split_region(region, point_maps, min_area_low))

    pieces.sort(key=lambda piece: int(piece[0].sum()), reverse=True)
    pieces = pieces[:WALL_MAX_SEGMENTS]
    pieces.sort(key=lambda piece: float(np.nonzero(piece[0])[1].mean()))

    wall_full = _full_resolution_wall_mask(seg_map)
    owner = _wall_owner_map([piece for piece, _ in pieces], seg_low.shape, full_w, full_h)
    tolerance = WALL_EDGE_STRAIGHTEN_RATIO * min(full_h, full_w)
    claimed = np.zeros((full_h, full_w), dtype=bool)
    components = []
    for index, (work_mask, plane) in enumerate(pieces):
        mask = ((owner == index) & wall_full).astype(np.uint8)
        # Architectural edges are straight: redraw the outline as lines. Where two
        # straightened walls overlap at a corner, the earlier wall keeps the pixels.
        mask = straighten_mask_edges(mask, tolerance, min_area=(2.0 * tolerance) ** 2)
        mask[claimed] = 0
        area = int(mask.sum())
        if area < min_area:
            continue
        claimed |= mask > 0
        components.append(WallComponent(mask=mask, work_mask=work_mask.astype(np.uint8), plane=plane, area=area))

    return WallDiscovery(
        components=components,
        vertical=vertical,
        stride=stride,
        geometry_used=point_maps is not None,
    )


def _clean_wall_mask(seg_low: np.ndarray) -> np.ndarray:
    """Working-res wall mask with protected classes cut out (with a margin, so
    walls touching only across a door or column separate)."""
    wall = seg_class_mask(seg_low, class_ids({"wall"}))
    protected = seg_class_mask(seg_low, class_ids(WALL_PROTECTED_CLASSES))
    radius = max(1, int(round(min(seg_low.shape[:2]) * PROTECTED_DILATION_RATIO)))
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
    protected = cv2.dilate(protected, kernel, iterations=1)
    wall[protected > 0] = 0
    wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel)
    wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
    wall[protected > 0] = 0
    return wall


def _working_point_maps(geometry: dict | None, stride: int, full_w: int, full_h: int):
    """Strided (points, normals, valid) maps, or None when there is no metric geometry."""
    if geometry is None:
        return None
    points = geometry.get("points")
    if points is not None:
        points = points[::stride, ::stride].astype(np.float32, copy=False)
        valid = geometry.get("validMask")
        valid = valid[::stride, ::stride].astype(bool) if valid is not None else np.ones(points.shape[:2], bool)
    else:
        depth = geometry.get("depth")
        provider = str(geometry.get("provider") or "")
        if depth is None or ("metric" not in DEPTH_MODEL_NAME.lower() and "metric" not in provider.lower()):
            return None
        depth = depth[::stride, ::stride].astype(np.float32)
        intrinsics = pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h).copy()
        intrinsics[:2, :] /= stride
        points = backproject_depth(depth, intrinsics)
        valid = np.ones(depth.shape, bool)

    valid &= np.isfinite(points).all(axis=2) & (points[:, :, 2] > MIN_DEPTH_METERS)
    if not valid.any():
        return None

    normals = geometry.get("normals")
    if normals is not None and normals.shape[:2] == (full_h, full_w):
        normals = smooth_normal_map(normals[::stride, ::stride], SURFACE_NORMAL_SMOOTHING_KERNEL)
    else:
        normals = compute_normals_from_points(points, valid, SURFACE_NORMAL_SMOOTHING_KERNEL)
    valid &= np.linalg.norm(normals, axis=2) > 1e-4
    return points, normals, valid


def _vertical_reference(seg_low: np.ndarray, point_maps) -> np.ndarray:
    """Room "up" axis from floor normals, oriented like camera +Y (the renderer's v)."""
    fallback = np.array([0.0, 1.0, 0.0], dtype=np.float32)
    if point_maps is None:
        return fallback
    _, normals, valid = point_maps
    floor = (seg_class_mask(seg_low, class_ids(PRIMARY_FLOOR_CLASSES)) > 0) & valid
    if int(floor.sum()) < SURFACE_MIN_PLANE_PIXELS // 4:
        return fallback
    up = np.median(normals[floor], axis=0).astype(np.float32)
    length = float(np.linalg.norm(up))
    if length < 1e-4:
        return fallback
    up /= length
    return up if up[1] >= 0 else -up


def _split_region(region: np.ndarray, point_maps, min_area_low: int) -> list[tuple[np.ndarray, WallPlane | None]]:
    """Split one connected wall region into per-plane pieces."""
    if point_maps is None:
        return [(region, None)]
    points_map, normals_map, valid_map = point_maps
    valid = region & valid_map
    ys, xs = np.nonzero(valid)
    if len(ys) < SURFACE_MIN_PLANE_PIXELS:
        return [(region, None)]
    points = points_map[ys, xs]
    normals = normalize_vectors(normals_map[ys, xs])

    planes = fit_multi_surface_planes(points, normals, True, max_planes=WALL_MAX_PLANES)
    planes = _merge_coplanar([p for p in planes if abs(float(p["normal"][1])) <= WALL_MAX_NORMAL_Y])
    if len(planes) <= 1:
        return [(region, _refit_plane(points, normals))]

    assignment = assign_points_to_surface_planes(points, normals, planes, True)
    labels = np.full(region.shape, -1, dtype=np.int32)
    labels[ys, xs] = assignment
    _fill_unassigned(labels, region)

    pieces = []
    for plane_index in range(len(planes)):
        count, components, stats, _ = cv2.connectedComponentsWithStats(
            (labels == plane_index).astype(np.uint8), connectivity=8,
        )
        for component_id in range(1, count):
            if int(stats[component_id, cv2.CC_STAT_AREA]) < min_area_low:
                continue
            piece = components == component_id
            piece_valid = piece & valid_map
            pieces.append((piece, _refit_plane(points_map[piece_valid], normals_map[piece_valid])))
    return pieces or [(region, _refit_plane(points, normals))]


def _merge_coplanar(planes: list[dict]) -> list[dict]:
    """Drop planes that describe the same flat wall as a larger plane already kept."""
    min_cos = float(np.cos(np.deg2rad(WALL_COPLANAR_ANGLE_DEGREES)))
    kept: list[dict] = []
    for plane in sorted(planes, key=lambda p: p["inlierCount"], reverse=True):
        normal = np.asarray(plane["normal"], dtype=np.float32)
        origin = np.asarray(plane["origin"], dtype=np.float32)
        duplicate = any(
            abs(float(normal @ k["normal"])) >= min_cos
            and abs(float((origin - k["origin"]) @ k["normal"])) <= WALL_COPLANAR_OFFSET_METERS
            for k in kept
        )
        if not duplicate:
            kept.append(plane)
    return kept


def _fill_unassigned(labels: np.ndarray, region: np.ndarray) -> None:
    """Give region pixels without valid geometry the label of their nearest labelled neighbour."""
    kernel = np.ones((3, 3), np.uint8)
    unassigned = region & (labels < 0)
    while unassigned.any():
        grown = False
        for label in np.unique(labels[labels >= 0]):
            reach = cv2.dilate((labels == label).astype(np.uint8), kernel) > 0
            take = reach & unassigned
            if take.any():
                labels[take] = label
                unassigned &= ~take
                grown = True
        if not grown:
            break


def _refit_plane(points: np.ndarray, normals: np.ndarray) -> WallPlane | None:
    """Least-squares plane over a wall's own points (subsampled), or None if not wall-like."""
    finite = np.isfinite(points).all(axis=1)
    points, normals = points[finite], normals[finite]
    if len(points) < SURFACE_MIN_PLANE_PIXELS // 4:
        return None
    if len(points) > PLANE_REFIT_SAMPLES:
        step = len(points) // PLANE_REFIT_SAMPLES
        points, normals = points[::step], normals[::step]
    origin, normal = refine_plane(points, normals)
    if abs(float(normal[1])) > WALL_MAX_NORMAL_Y:
        return None
    return WallPlane(origin=origin.astype(np.float32), normal=normal.astype(np.float32))


def _full_resolution_wall_mask(seg_map: np.ndarray) -> np.ndarray:
    """Wall pixels at full resolution with protected classes cut out exactly.

    Mirrors the floor: the outline follows the (smoothly upsampled) semantic
    boundary, with only light speck cleanup and no widened margin around
    doors, ceilings or furniture.
    """
    wall = seg_class_mask(seg_map, class_ids({"wall"}))
    protected = seg_class_mask(seg_map, class_ids(WALL_PROTECTED_CLASSES)) > 0
    wall[protected] = 0
    radius = max(1, int(round(min(seg_map.shape[:2]) * OUTLINE_CLEANUP_RATIO)))
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
    wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
    wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel)
    wall[protected] = 0
    return wall > 0


def _wall_owner_map(
    pieces: list[np.ndarray],
    work_shape: tuple[int, int],
    full_w: int,
    full_h: int,
) -> np.ndarray:
    """Full-resolution index of the wall piece each pixel belongs to (-1 for none).

    Each piece is blurred at working resolution so its influence reaches across
    the separation margin cut around doors; the argmax then places seams
    between neighbouring walls midway and, after linear upscaling, smoothly.
    """
    owner = np.full((full_h, full_w), -1, dtype=np.int8)
    if not pieces:
        return owner
    radius = max(1, int(round(min(work_shape) * PROTECTED_DILATION_RATIO)))
    sigma = max(1.0, radius * OWNERSHIP_SIGMA_SCALE)
    best = np.full((full_h, full_w), OWNERSHIP_MIN_WEIGHT, dtype=np.float32)
    for index, piece in enumerate(pieces):
        weight = cv2.GaussianBlur(piece.astype(np.float32), (0, 0), sigmaX=sigma, sigmaY=sigma)
        weight = cv2.resize(weight, (full_w, full_h), interpolation=cv2.INTER_LINEAR)
        wins = weight > best
        best[wins] = weight[wins]
        owner[wins] = index
    return owner