File size: 8,788 Bytes
532466c
 
 
 
 
 
 
 
 
8e53f1d
 
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
 
532466c
8e53f1d
 
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
532466c
8e53f1d
 
 
 
 
 
 
 
532466c
 
 
 
8e53f1d
532466c
 
 
 
 
 
8e53f1d
 
 
 
 
 
 
 
 
 
532466c
 
 
 
 
 
 
 
8e53f1d
 
532466c
 
 
 
 
8e53f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532466c
 
 
 
 
 
8e53f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
532466c
 
 
 
 
 
8e53f1d
532466c
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
"""Floor mask creation and morphological cleanup.

Functions
---------
clean_floor_mask      - morphological close/open + connected-component filtering
wall_subtract         - remove wall/reject pixels from a floor mask
build_floor_surface_mask - composite floor surface from segmentation, depth, and geometry
"""

import time

import cv2
import numpy as np

from config.runtime import ENABLE_FLOOR_MASK_CLEANUP
from state import (
    OCCLUDER_CLASSES,
    REJECT_SURFACE_CLASSES,
    SOFT_FLOOR_COVERING_CLASSES,
    class_ids,
)
from utils import seg_class_mask
from services.floor.edge_coverage import (
    improve_surface_edge_coverage,
    expand_surface_over_soft_floor_coverings,
)
from services.floor.geometry_filter import filter_surface_by_floor_geometry


def clean_floor_mask(mask: np.ndarray) -> np.ndarray:
    if not ENABLE_FLOOR_MASK_CLEANUP:
        return mask.astype(np.uint8, copy=False)

    if mask.dtype != np.uint8:
        mask = mask.astype(np.uint8)

    h, w = mask.shape[:2]
    min_side = max(3, min(h, w))
    close_size = max(5, int(round(min_side * 0.018))) | 1
    open_size = max(3, int(round(min_side * 0.006))) | 1
    closed = cv2.morphologyEx(
        mask,
        cv2.MORPH_CLOSE,
        cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size)),
    )
    cleaned = cv2.morphologyEx(
        closed,
        cv2.MORPH_OPEN,
        cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (open_size, open_size)),
    )

    count, labels, stats, _ = cv2.connectedComponentsWithStats(cleaned, connectivity=8)
    if count <= 1:
        return cleaned

    gravity_threshold = int(h * 0.60)
    min_area = max(1000, int(h * w * 0.01))
    result = np.zeros_like(cleaned)
    for component_id in range(1, count):
        area = stats[component_id, cv2.CC_STAT_AREA]
        if area < min_area:
            continue
        comp_bottom = stats[component_id, cv2.CC_STAT_TOP] + stats[component_id, cv2.CC_STAT_HEIGHT]
        if comp_bottom <= gravity_threshold:
            continue
        result[labels == component_id] = 1

    if result.any():
        return result
    largest = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
    return (labels == largest).astype(np.uint8)


def wall_subtract(mask: np.ndarray, seg_map: np.ndarray, dilation: int = 1) -> np.ndarray:
    reject_raw = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES))
    if dilation > 0:
        kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
        reject_raw = cv2.dilate(reject_raw, kern, iterations=dilation)
    result = mask.copy()
    result[reject_raw > 0] = 0
    return result


def build_floor_surface_mask(
    floor_mask: np.ndarray,
    seg_map: np.ndarray,
    quad: np.ndarray | None,
    depth: np.ndarray | None,
    geometry: dict | None,
    plane: dict | None,
    *,
    geometry_maps: dict | None = None,
):
    total_started = time.perf_counter()
    phase_started = total_started
    h, w = floor_mask.shape[:2]
    kern_size = max(5, min(h, w) // 160) | 1
    kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size))
    occluder_mask = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES))
    soft_covering_mask = seg_class_mask(seg_map, class_ids(SOFT_FLOOR_COVERING_CLASSES))
    reject_mask = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES))
    hard_protected_mask = (occluder_mask > 0) | (reject_mask > 0)
    normal_edge_protected_mask = hard_protected_mask | (soft_covering_mask > 0)

    surface = floor_mask.copy()
    surface[reject_mask > 0] = 0
    surface[soft_covering_mask > 0] = 0
    if not surface.any():
        surface = floor_mask.copy()
        surface[soft_covering_mask > 0] = 0

    contours, _ = cv2.findContours(surface, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if contours:
        filled = np.zeros((h, w), dtype=np.uint8)
        cv2.drawContours(filled, contours, -1, 1, cv2.FILLED)
        filled[reject_mask > 0] = 0
        filled[soft_covering_mask > 0] = 0
        surface = filled

    if quad is not None and surface.any():
        plane_mask = np.zeros((h, w), dtype=np.uint8)
        cv2.fillConvexPoly(plane_mask, np.round(quad).astype(np.int32), 1)
        plane_mask[reject_mask > 0] = 0
        plane_mask[soft_covering_mask > 0] = 0
        near_floor = cv2.dilate(surface, kern, iterations=6)
        surface = cv2.bitwise_or(surface, cv2.bitwise_and(plane_mask, near_floor))
        surface[soft_covering_mask > 0] = 0

    surface[occluder_mask > 0] = 0
    surface[soft_covering_mask > 0] = 0
    if depth is not None and floor_mask.any():
        floor_depth = depth[(floor_mask > 0) & np.isfinite(depth)]
        if floor_depth.size == 0:
            floor_depth = None
    else:
        floor_depth = None
    if floor_depth is not None:
        lo, hi = float(np.percentile(floor_depth, 2)), float(np.percentile(floor_depth, 98))
        margin = max(0.08, (hi - lo) * 0.35)
        depth_keep = (depth >= lo - margin) & (depth <= hi + margin)
        surface = (surface & depth_keep.astype(np.uint8)).astype(np.uint8)
        surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1)
        surface[occluder_mask > 0] = 0
        surface[reject_mask > 0] = 0
        surface[soft_covering_mask > 0] = 0
    preparation_ms = (time.perf_counter() - phase_started) * 1000

    phase_started = time.perf_counter()
    surface, geometry_filter_metadata = filter_surface_by_floor_geometry(
        surface,
        geometry,
        plane,
        geometry_maps=geometry_maps,
    )
    initial_filter_ms = (time.perf_counter() - phase_started) * 1000
    surface[occluder_mask > 0] = 0
    surface[reject_mask > 0] = 0
    surface[soft_covering_mask > 0] = 0

    phase_started = time.perf_counter()
    surface = clean_floor_mask(surface)
    surface[occluder_mask > 0] = 0
    surface[reject_mask > 0] = 0
    surface[soft_covering_mask > 0] = 0

    surface, edge_metadata = improve_surface_edge_coverage(surface, normal_edge_protected_mask)
    cleanup_and_edge_ms = (time.perf_counter() - phase_started) * 1000

    phase_started = time.perf_counter()
    surface, post_edge_filter_metadata = filter_surface_by_floor_geometry(
        surface,
        geometry,
        plane,
        geometry_maps=geometry_maps,
    )
    post_edge_filter_ms = (time.perf_counter() - phase_started) * 1000
    surface[occluder_mask > 0] = 0
    surface[reject_mask > 0] = 0
    surface[soft_covering_mask > 0] = 0
    post_edge_filter_metadata = {
        f"postEdge{k[0].upper()}{k[1:]}": value
        for k, value in post_edge_filter_metadata.items()
    }

    phase_started = time.perf_counter()
    surface_before_soft_covering = surface
    surface, soft_covering_metadata = expand_surface_over_soft_floor_coverings(
        surface,
        soft_covering_mask,
        hard_protected_mask,
    )
    soft_covering_ms = (time.perf_counter() - phase_started) * 1000

    phase_started = time.perf_counter()
    if surface is surface_before_soft_covering or not soft_covering_metadata["softFloorCoveringExpansionApplied"]:
        post_soft_covering_filter_metadata = {
            "geometrySurfaceFilterApplied": False,
            "geometrySurfaceFilterReason": "soft-floor-surface-unchanged",
            "geometrySurfacePixelsBefore": int(surface.sum()),
            "geometrySurfacePixelsAfter": int(surface.sum()),
        }
    else:
        surface, post_soft_covering_filter_metadata = filter_surface_by_floor_geometry(
            surface,
            geometry,
            plane,
            geometry_maps=geometry_maps,
        )
    post_soft_filter_ms = (time.perf_counter() - phase_started) * 1000
    surface[occluder_mask > 0] = 0
    surface[reject_mask > 0] = 0
    post_soft_covering_filter_metadata = {
        f"postSoftFloorCovering{k[0].upper()}{k[1:]}": value
        for k, value in post_soft_covering_filter_metadata.items()
    }
    timing_ms = {
        "preparation": round(preparation_ms, 2),
        "initialGeometryFilter": round(initial_filter_ms, 2),
        "cleanupAndEdgeRepair": round(cleanup_and_edge_ms, 2),
        "postEdgeGeometryFilter": round(post_edge_filter_ms, 2),
        "softFloorExpansion": round(soft_covering_ms, 2),
        "postSoftFloorGeometryFilter": round(post_soft_filter_ms, 2),
        "total": round((time.perf_counter() - total_started) * 1000, 2),
    }
    print(
        "[SURFACE_MASKING_TIMING] "
        + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()),
        flush=True,
    )
    return surface, {
        **geometry_filter_metadata,
        **edge_metadata,
        **post_edge_filter_metadata,
        **soft_covering_metadata,
        **post_soft_covering_filter_metadata,
        "surfaceMaskingTimingMs": timing_ms,
    }