File size: 13,424 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
"""Floor edge refinement: edges snap to the photo, run straight along walls, ship as alpha.

Run from apps/renderer:  python -m unittest test_surface_edges
No models needed: synthetic photos and segmentation maps only.
"""

import base64
import io
import json
import os
import tempfile
import unittest
import zipfile
from pathlib import Path
from unittest import mock

# The production profile, as test_wall_segments uses (config is read once per process).
os.environ.setdefault("VISUALIZER_CONFIG", "visualizer.gpu.toml")

import cv2  # noqa: E402
import numpy as np  # noqa: E402

from services.floor import edge_refinement  # noqa: E402
from services.floor.edge_refinement import ALPHA_FLOOR, guided_filter, refine_surface_edges  # noqa: E402
from services.geometry.multi_plane import geometry_point_maps  # noqa: E402
from services.geometry.uv_mapping import build_surface_uv_mapping  # noqa: E402
from services.image.polygons import straighten_polyline  # noqa: E402
from services.pipeline import packaging  # noqa: E402
from state import class_ids  # noqa: E402
from test_wall_segments import synthetic_room  # noqa: E402
from utils import mask_to_indices  # noqa: E402

HEIGHT, WIDTH = 900, 1200
WALL_LINE = 420  # the baseboard at the image centre: above is wall, below is floor
SLOPE = 0.04  # the baseboard is slightly tilted, as in a real photo
FLOOR_ID = class_ids({"floor"})[0]
WALL_ID = class_ids({"wall"})[0]
SOFA_ID = class_ids({"sofa"})[0]


def baseboard(xs: np.ndarray) -> np.ndarray:
    return WALL_LINE + SLOPE * (xs - WIDTH / 2)


def room_photo() -> np.ndarray:
    """Light wall over a darker, slightly grainy floor with a perfectly straight, anti-aliased join."""
    rng = np.random.default_rng(7)
    rows = np.arange(HEIGHT, dtype=np.float32)[:, None]
    floor_share = np.clip(rows + 0.5 - baseboard(np.arange(WIDTH))[None, :], 0, 1)[..., None]
    photo = (1 - floor_share) * np.array((225, 222, 216), np.float32) + floor_share * np.array((150, 118, 90), np.float32)
    photo += rng.normal(0, 4, photo.shape)
    return np.clip(photo, 0, 255).astype(np.uint8)


def wobbly_floor(amplitude: float, period: float, offset: float = 0.0) -> np.ndarray:
    """Floor mask whose top edge wobbles around the wall line, like an upsampled label map."""
    xs = np.arange(WIDTH)
    top = baseboard(xs) + offset + amplitude * np.sin(xs / period) + 0.6 * amplitude * np.sin(xs / (period * 0.37) + 1.0)
    rows = np.arange(HEIGHT)[:, None]
    return (rows >= np.round(top)[None, :]).astype(np.uint8)


def seg_for(floor: np.ndarray) -> np.ndarray:
    seg = np.full((HEIGHT, WIDTH), WALL_ID, np.uint8)
    seg[floor > 0] = FLOOR_ID
    return seg


MARGIN = WIDTH // 20  # columns where the filter meets the image border are ignored


def top_edge_rows(mask: np.ndarray) -> np.ndarray:
    """First floor row in each column."""
    return np.argmax(mask[:, MARGIN:-MARGIN] > 0, axis=0).astype(np.float32)


def baseboard_error(mask: np.ndarray) -> np.ndarray:
    """Distance from each column's first floor row to the baseboard's first (partly) floor row."""
    expected = np.floor(baseboard(np.arange(MARGIN, WIDTH - MARGIN)) + 0.5)
    return np.abs(top_edge_rows(mask) - expected)


class GuidedFilterTest(unittest.TestCase):
    def test_constant_source_is_unchanged(self):
        guide = room_photo().astype(np.float32) / 255.0
        ones = np.ones((HEIGHT, WIDTH), np.float32)
        np.testing.assert_allclose(guided_filter(guide, ones, 11, 2e-3), 1.0, atol=1e-3)


class RefineSurfaceEdgesTest(unittest.TestCase):
    def test_wobbly_edge_snaps_to_the_baseboard(self):
        floor = wobbly_floor(amplitude=7, period=40, offset=3)
        before = baseboard_error(floor)
        mask, alpha, metadata = refine_surface_edges(room_photo(), floor, seg_for(floor))

        after = baseboard_error(mask)
        self.assertTrue(metadata["edgeRefinementApplied"], metadata)
        self.assertGreater(before.mean(), 3.0)
        self.assertLess(after.mean(), 1.0)
        self.assertLessEqual(after.max(), 2.0)

    def test_alpha_is_anti_aliased_and_mask_covers_it(self):
        floor = wobbly_floor(amplitude=5, period=60)
        mask, alpha, _ = refine_surface_edges(room_photo(), floor, seg_for(floor))

        self.assertTrue(((alpha >= ALPHA_FLOOR) == (mask > 0)).all())
        partial = (alpha > 0) & (alpha < 255)
        self.assertGreater(int(partial.sum()), WIDTH // 2)  # a soft edge exists...
        rows, cols = np.nonzero(partial)
        self.assertLess(np.percentile(np.abs(rows - baseboard(cols)), 95), 2)  # ...and only along the edge
        self.assertTrue((alpha[WALL_LINE + 60:] == 255).all())  # the interior is fully tiled

    def test_edge_along_a_wall_is_straight_even_without_a_photo_edge(self):
        flat = np.full((HEIGHT, WIDTH, 3), 180, np.uint8)  # nothing for the filter to snap to
        floor = wobbly_floor(amplitude=2.5, period=25)
        mask, _, metadata = refine_surface_edges(flat, floor, seg_for(floor))

        rows = top_edge_rows(mask)
        self.assertGreaterEqual(metadata["edgeStraightenedRuns"], 1)
        residual = rows - np.polyval(np.polyfit(np.arange(len(rows)), rows, 1), np.arange(len(rows)))
        self.assertLessEqual(np.abs(residual).max(), 1.0)

    def test_edge_against_furniture_is_not_straightened(self):
        floor = np.zeros((HEIGHT, WIDTH), np.uint8)
        floor[200:] = 1
        seg = np.full((HEIGHT, WIDTH), SOFA_ID, np.uint8)
        seg[floor > 0] = FLOOR_ID
        flat = np.full((HEIGHT, WIDTH, 3), 180, np.uint8)
        _, _, metadata = refine_surface_edges(flat, floor, seg)
        self.assertEqual(metadata["edgeStraightenedRuns"], 0)

    def test_speckled_carpet_next_to_a_light_wall_gets_no_holes(self):
        """Light carpet specks look like the wall to the filter; they must not punch holes in the tile."""
        photo = room_photo()
        rng = np.random.default_rng(3)
        rows, cols = np.nonzero(np.arange(HEIGHT)[:, None] >= baseboard(np.arange(WIDTH))[None, :] + 4)
        specks = rng.random(len(rows)) < 0.08
        photo[rows[specks], cols[specks]] = (225, 222, 216)  # the wall's colour
        photo = cv2.GaussianBlur(photo, (3, 3), 0)
        floor = wobbly_floor(amplitude=5, period=60)
        mask, alpha, _ = refine_surface_edges(photo, floor, seg_for(floor))

        holes = (alpha < 128).astype(np.uint8)
        count, labels = cv2.connectedComponents(holes, connectivity=4)
        enclosed = [label for label in range(1, count) if not (labels[0] == label).any()]  # not the wall region
        self.assertEqual(enclosed, [])
        self.assertTrue((alpha[WALL_LINE + 60:] == 255).all())

    def test_disabled_returns_the_mask_with_a_hard_edge(self):
        floor = wobbly_floor(amplitude=5, period=40)
        with mock.patch.object(edge_refinement, "ENABLE_SURFACE_EDGE_REFINEMENT", False):
            mask, alpha, metadata = refine_surface_edges(room_photo(), floor, seg_for(floor))
        self.assertFalse(metadata["edgeRefinementApplied"])
        np.testing.assert_array_equal(mask, floor)
        np.testing.assert_array_equal(alpha, floor * 255)

    def test_large_area_change_falls_back_to_the_input(self):
        floor = wobbly_floor(amplitude=5, period=40)
        with mock.patch.object(edge_refinement, "MAX_AREA_CHANGE", 0.0):
            mask, _, metadata = refine_surface_edges(room_photo(), floor, seg_for(floor))
        self.assertEqual(metadata["edgeRefinementReason"], "area-change-too-large")
        np.testing.assert_array_equal(mask, floor)


class EdgeUvTest(unittest.TestCase):
    """Depth is blurry where the floor meets a wall; refined edge pixels still get floor UVs."""

    @classmethod
    def setUpClass(cls):
        _, cls.geometry, labels = synthetic_room()
        cls.floor = (labels == 0).astype(np.uint8)
        cls.indices = mask_to_indices(cls.floor)
        # The 8 floor rows nearest the walls: their 3D points slide towards the wall.
        far_edge = cv2.dilate(1 - cls.floor, np.ones((17, 17), np.uint8)) & cls.floor
        cls.blurry = far_edge.astype(bool)
        blurred = dict(cls.geometry)
        blurred["points"] = cls.geometry["points"].copy()
        blurred["points"][cls.blurry] *= 1.15
        cls.blurred_maps = geometry_point_maps(cls.floor, blurred)
        cls.blurred_geometry = blurred

    def test_blurry_edge_pixels_lose_their_uv_without_the_fill(self):
        mapping = build_surface_uv_mapping(self.floor, self.indices, self.blurred_geometry, geometry_maps=self.blurred_maps)
        self.assertLess(mapping["metadata"]["surfaceUvCoverage"], 0.995)

    def test_refined_edge_pixels_get_their_uv_from_the_floor_plane(self):
        mapping = build_surface_uv_mapping(
            self.floor, self.indices, self.blurred_geometry, geometry_maps=self.blurred_maps, ray_fill_mask=self.blurry,
        )
        metadata = mapping["metadata"]
        self.assertGreater(metadata["surfaceUvRayFilledPixels"], 0)
        self.assertGreaterEqual(metadata["surfaceUvCoverage"], 0.999)
        # The true floor points, in this mapping's own plane coordinates.
        plane = mapping["planes"][0]
        filled = self.blurry.ravel()[self.indices]
        true_points = self.geometry["points"].reshape(-1, 3)[self.indices[filled]]
        delta = true_points - np.asarray(plane["origin"], np.float32)
        expected = np.column_stack((delta @ np.asarray(plane["uAxis"]), delta @ np.asarray(plane["vAxis"])))
        np.testing.assert_allclose(mapping["uv"][filled], expected, atol=0.005)


class EdgeSmearTest(unittest.TestCase):
    """Edge pixels carrying a wrong but on-plane 3D point (a furniture foot) must not smear the tile."""

    def test_edge_band_follows_the_floor_plane(self):
        from services.geometry import uv_mapping

        _, geometry, labels = synthetic_room()
        floor = (labels == 0).astype(np.uint8)
        indices = mask_to_indices(floor)
        edge = (cv2.dilate(1 - floor, np.ones((9, 9), np.uint8)) & floor).astype(bool)
        smeared = dict(geometry)
        smeared["points"] = geometry["points"].copy()
        ys, xs = np.nonzero(edge)
        # Each edge pixel reports the floor point 10 rows nearer the camera: on the plane, wrong place.
        smeared["points"][ys, xs] = geometry["points"][np.minimum(ys + 10, floor.shape[0] - 1), xs]
        maps = geometry_point_maps(floor, smeared)

        def edge_error(mapping):
            plane = mapping["planes"][0]
            on_edge = edge.ravel()[indices]
            delta = geometry["points"].reshape(-1, 3)[indices[on_edge]] - np.asarray(plane["origin"], np.float32)
            expected = np.column_stack((delta @ np.asarray(plane["uAxis"]), delta @ np.asarray(plane["vAxis"])))
            return np.abs(mapping["uv"][on_edge] - expected).max(axis=1)

        with mock.patch.object(uv_mapping, "SURFACE_UV_EDGE_BAND_RATIO", 0.0):
            unblended = edge_error(build_surface_uv_mapping(floor, indices, smeared, geometry_maps=maps))
        blended = edge_error(build_surface_uv_mapping(floor, indices, smeared, geometry_maps=maps))
        self.assertGreater(np.percentile(unblended, 50), 0.02)  # the smear is real without the band...
        self.assertLess(np.percentile(blended, 50), 0.005)  # ...and gone with it


class StraightenPolylineTest(unittest.TestCase):
    def test_noisy_line_becomes_one_segment(self):
        xs = np.arange(0, 300)
        ys = 100 + np.round(1.5 * np.sin(xs / 7.0))
        line = straighten_polyline(np.stack([xs, ys], axis=1), tolerance=4)
        self.assertEqual(len(line), 2)
        np.testing.assert_allclose(line[:, 1], 100, atol=0.5)

    def test_real_corner_is_kept(self):
        down = np.stack([np.zeros(100), np.arange(100)], axis=1)
        across = np.stack([np.arange(1, 100), np.full(99, 99)], axis=1)
        corner = straighten_polyline(np.concatenate([down, across]), tolerance=3)
        self.assertEqual(len(corner), 3)
        np.testing.assert_allclose(corner[1], (0, 99), atol=1.0)


class PackagingTest(unittest.TestCase):
    def test_edge_alpha_ships_as_a_lazy_asset(self):
        w, h = 40, 30
        indices = np.arange(200, 500, dtype=np.uint32)
        alpha = np.linspace(0, 255, len(indices)).astype(np.uint8)
        bundle = {
            "width": w,
            "height": h,
            "pixels": None,
            "segments": [{"id": 0, "mask": base64.b64encode(indices.tobytes()).decode(), "edgeAlpha": alpha}],
        }
        with tempfile.TemporaryDirectory() as tmp, mock.patch.object(packaging, "JOB_DIR", Path(tmp)):
            data = packaging.build_manifest_segmentation_bundle(bundle, "job")
        archive = zipfile.ZipFile(io.BytesIO(data))
        metadata = json.loads(archive.read("metadata.json"))
        ref = metadata["segments"][0]["edgeAlpha"]
        self.assertEqual(ref["path"], "segments/0/edge-alpha.u8")
        self.assertEqual(archive.read(ref["path"]), alpha.tobytes())

    def test_occlusion_never_covers_the_surface(self):
        seg = np.full((60, 80), FLOOR_ID, np.uint8)
        seg[:20] = SOFA_ID
        surface = np.zeros((60, 80), np.uint8)
        surface[18:] = 1  # the soft edge reaches two rows into the sofa label
        occlusion = packaging.foreground_occlusion_mask(surface, seg)
        self.assertTrue(occlusion[:18].any())
        self.assertFalse((occlusion & surface).any())


if __name__ == "__main__":
    unittest.main()