github-actions[bot] commited on
Commit ·
d7b5c2a
1
Parent(s): bab0e3a
Automated Deploy: b0a2a3cb7961b9cc25cc3123b04a509844bc9a4b
Browse files- config/runtime.py +1 -1
- config/surface.py +9 -0
- frontend/viz2d-demo/e2e/helpers.ts +80 -0
- frontend/viz2d-demo/e2e/wall-tile-controls.spec.ts +67 -0
- frontend/viz2d-demo/e2e/wall-tile-orientation.spec.ts +40 -0
- scripts/test_wall_mask.py +331 -0
- scripts/wall_smoke_test.py +128 -0
- services/wall/components.py +162 -50
- services/wall/corner.py +214 -0
- services/wall/mask.py +266 -0
- services/wall/plane.py +39 -3
- test_wall_corner_split.py +159 -0
- test_wall_plane_basis.py +202 -0
- test_wall_plane_extents.py +99 -0
- visualizer.gpu.toml +2 -2
- visualizer.hf.toml +2 -2
- visualizer.local.toml +1 -1
config/runtime.py
CHANGED
|
@@ -6,7 +6,7 @@ ENABLE_FLOOR_MASK_CLEANUP = config_bool("ENABLE_FLOOR_MASK_CLEANUP", "runtime",
|
|
| 6 |
ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1")
|
| 7 |
ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1")
|
| 8 |
ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1")
|
| 9 |
-
ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "
|
| 10 |
ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0")
|
| 11 |
ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
|
| 12 |
ENABLE_FAST_SHADOW_TRANSFER = config_bool(
|
|
|
|
| 6 |
ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1")
|
| 7 |
ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1")
|
| 8 |
ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1")
|
| 9 |
+
ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "1")
|
| 10 |
ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0")
|
| 11 |
ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
|
| 12 |
ENABLE_FAST_SHADOW_TRANSFER = config_bool(
|
config/surface.py
CHANGED
|
@@ -51,6 +51,15 @@ SURFACE_UV_MIN_COVERAGE = float(config_value(
|
|
| 51 |
"SURFACE_UV_MIN_COVERAGE", "surface_mapping", "uv_min_coverage", "0.995",
|
| 52 |
))
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO = float(config_value(
|
| 55 |
"SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO", "surface_mapping", "uv_max_bad_neighbor_ratio", "0.035",
|
| 56 |
))
|
|
|
|
| 51 |
"SURFACE_UV_MIN_COVERAGE", "surface_mapping", "uv_min_coverage", "0.995",
|
| 52 |
))
|
| 53 |
|
| 54 |
+
# Walls tile *behind* mounted objects, so a wall surface legitimately
|
| 55 |
+
# contains pixels with no valid wall geometry (a TV, a mirror, a cabinet).
|
| 56 |
+
# Holding walls to the floor's 0.995 makes every wall fail the gate as
|
| 57 |
+
# 'incomplete-surface-uv'. The shortfall is exactly the occluded pixels,
|
| 58 |
+
# which the occlusion mask repaints anyway, so it is not a defect.
|
| 59 |
+
SURFACE_UV_WALL_MIN_COVERAGE = float(config_value(
|
| 60 |
+
"SURFACE_UV_WALL_MIN_COVERAGE", "surface_mapping", "uv_wall_min_coverage", "0.90",
|
| 61 |
+
))
|
| 62 |
+
|
| 63 |
SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO = float(config_value(
|
| 64 |
"SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO", "surface_mapping", "uv_max_bad_neighbor_ratio", "0.035",
|
| 65 |
))
|
frontend/viz2d-demo/e2e/helpers.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { fileURLToPath } from "node:url";
|
| 3 |
+
import { expect, type Page } from "@playwright/test";
|
| 4 |
+
|
| 5 |
+
// The package is ESM ("type": "module"), so there is no __dirname.
|
| 6 |
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
| 7 |
+
|
| 8 |
+
export const ROOM_PHOTO = path.resolve(here, "../test-images/Image 1.jpeg");
|
| 9 |
+
|
| 10 |
+
/** A material with a hard grid, so a tilted or mis-scaled basis is visible. */
|
| 11 |
+
export const GRID_TEXTURE = "Grey Checkerboard";
|
| 12 |
+
|
| 13 |
+
/**
|
| 14 |
+
* Upload a room photo and wait for the backend to finish detecting surfaces.
|
| 15 |
+
*
|
| 16 |
+
* The CPU pipeline takes roughly 20s, and the bundle download follows it, so
|
| 17 |
+
* this waits on a wall card rather than on the editor shell.
|
| 18 |
+
*/
|
| 19 |
+
export async function openEditorWithRoomPhoto(page: Page) {
|
| 20 |
+
await page.goto("/");
|
| 21 |
+
await page.setInputFiles('[data-testid="room-file-input"]', ROOM_PHOTO);
|
| 22 |
+
// The editor only mounts once the pipeline returns a bundle, so both of
|
| 23 |
+
// these wait out a full CPU detection run rather than the default timeout.
|
| 24 |
+
await expect(page.getByTestId("visualizer-editor")).toBeVisible({ timeout: 150_000 });
|
| 25 |
+
await expect(page.locator('[data-testid="surface-card"][data-surface-class="wall"]')).toBeVisible({
|
| 26 |
+
timeout: 150_000,
|
| 27 |
+
});
|
| 28 |
+
await expect(page.getByTestId("blocking-overlay")).toHaveCount(0, { timeout: 60_000 });
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
/**
|
| 32 |
+
* Select a wall by clicking the canvas where its label sits.
|
| 33 |
+
*
|
| 34 |
+
* The label is positioned at an anchor inside the wall's own mask, so this is
|
| 35 |
+
* a stable way to hit a specific wall. The label itself is pointer-events-none,
|
| 36 |
+
* so the click lands on the canvas underneath it.
|
| 37 |
+
*
|
| 38 |
+
* Returns the wall's label text, e.g. "Wall 1".
|
| 39 |
+
*/
|
| 40 |
+
export async function selectWallOnCanvas(page: Page, index = 0) {
|
| 41 |
+
const label = page.locator('[data-testid="surface-label"][data-surface-class="wall"]').nth(index);
|
| 42 |
+
await expect(label).toBeVisible();
|
| 43 |
+
const text = (await label.innerText()).trim();
|
| 44 |
+
const box = await label.boundingBox();
|
| 45 |
+
if (!box) throw new Error(`wall label ${index} has no box`);
|
| 46 |
+
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
|
| 47 |
+
return text;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/** Apply a catalog texture through the selector that a surface click opens. */
|
| 51 |
+
export async function applyTexture(page: Page, name = GRID_TEXTURE) {
|
| 52 |
+
const selector = page.getByTestId("texture-selector");
|
| 53 |
+
await expect(selector).toBeVisible();
|
| 54 |
+
await selector.locator(`[data-testid="texture-card"][data-texture-name="${name}"]`).click();
|
| 55 |
+
await expect(page.getByTestId("blocking-overlay")).toHaveCount(0, { timeout: 60_000 });
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
/**
|
| 59 |
+
* Upload a room photo and wait for detection, at a phone viewport.
|
| 60 |
+
*
|
| 61 |
+
* Separate from openEditorWithRoomPhoto because that one waits on a wall
|
| 62 |
+
* surface-card, which on mobile lives inside a sheet that has not been opened
|
| 63 |
+
* yet and so is not in the DOM at all. The Surfaces trigger is the mobile
|
| 64 |
+
* equivalent: it enables only once a bundle has loaded.
|
| 65 |
+
*/
|
| 66 |
+
export async function openEditorOnMobile(page: Page) {
|
| 67 |
+
await page.goto("/");
|
| 68 |
+
await page.setInputFiles('[data-testid="room-file-input"]', ROOM_PHOTO);
|
| 69 |
+
await expect(page.getByTestId("visualizer-editor")).toBeVisible({ timeout: 150_000 });
|
| 70 |
+
await expect(page.getByTestId("mobile-surfaces-trigger")).toBeEnabled({ timeout: 150_000 });
|
| 71 |
+
await expect(page.getByTestId("blocking-overlay")).toHaveCount(0, { timeout: 60_000 });
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/** Open the mobile surfaces sheet and return it. */
|
| 75 |
+
export async function openSurfacesSheet(page: Page) {
|
| 76 |
+
await page.getByTestId("mobile-surfaces-trigger").click();
|
| 77 |
+
const sheet = page.getByTestId("mobile-surfaces-sheet");
|
| 78 |
+
await expect(sheet).toBeVisible();
|
| 79 |
+
return sheet;
|
| 80 |
+
}
|
frontend/viz2d-demo/e2e/wall-tile-controls.spec.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, test } from "@playwright/test";
|
| 2 |
+
|
| 3 |
+
import { applyTexture, openEditorWithRoomPhoto, selectWallOnCanvas } from "./helpers";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Walls used to be routed around the per-segment card list, so they never got
|
| 7 |
+
* the Tile size / Rotation sliders the floor has. A wall whose material has a
|
| 8 |
+
* hard grid needs them most: nothing else can correct a grid that lands tilted
|
| 9 |
+
* or at the wrong pitch.
|
| 10 |
+
*
|
| 11 |
+
* The controls are shared across walls by default -- tiles are normally the
|
| 12 |
+
* same product on every wall -- with a per-wall override for the selected wall.
|
| 13 |
+
*/
|
| 14 |
+
test.describe("wall tile controls", () => {
|
| 15 |
+
test("a textured wall exposes shared tile size and rotation", async ({ page }) => {
|
| 16 |
+
await openEditorWithRoomPhoto(page);
|
| 17 |
+
await selectWallOnCanvas(page);
|
| 18 |
+
await applyTexture(page);
|
| 19 |
+
|
| 20 |
+
const shared = page.getByTestId("wall-shared-adjustments");
|
| 21 |
+
|
| 22 |
+
await expect(shared).toBeVisible();
|
| 23 |
+
await expect(shared.getByTestId("texture-adjust-scale")).toBeVisible();
|
| 24 |
+
await expect(shared.getByTestId("texture-adjust-rotation")).toBeVisible();
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
test("the shared tile size drives every textured wall", async ({ page }) => {
|
| 28 |
+
await openEditorWithRoomPhoto(page);
|
| 29 |
+
await selectWallOnCanvas(page);
|
| 30 |
+
await applyTexture(page);
|
| 31 |
+
|
| 32 |
+
const scale = page.getByTestId("wall-shared-adjustments").getByTestId("texture-adjust-scale");
|
| 33 |
+
await scale.fill("2");
|
| 34 |
+
await expect(page.getByTestId("blocking-overlay")).toHaveCount(0, { timeout: 60_000 });
|
| 35 |
+
|
| 36 |
+
// Every wall carrying a texture reports the shared value back.
|
| 37 |
+
const overrides = page.locator('[data-testid="wall-override-card"]');
|
| 38 |
+
for (let i = 0; i < (await overrides.count()); i += 1) {
|
| 39 |
+
await expect(overrides.nth(i).getByTestId("texture-adjust-scale")).toHaveValue("2");
|
| 40 |
+
}
|
| 41 |
+
await expect(scale).toHaveValue("2");
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
test("the override card names the wall that was clicked", async ({ page }) => {
|
| 45 |
+
// `filteredSegments` sorts textured surfaces to the front, so numbering
|
| 46 |
+
// walls by their position in that list renamed a wall the instant its tile
|
| 47 |
+
// landed: you click Wall 2 and get a card that claims to adjust Wall 1.
|
| 48 |
+
// Texturing only the second wall is what makes the reorder observable.
|
| 49 |
+
await openEditorWithRoomPhoto(page);
|
| 50 |
+
const label = await selectWallOnCanvas(page, 1);
|
| 51 |
+
await applyTexture(page);
|
| 52 |
+
|
| 53 |
+
await expect(page.locator('[data-testid="wall-override-card"]')).toContainText(label);
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
test("selecting a wall reveals controls for just that wall", async ({ page }) => {
|
| 57 |
+
await openEditorWithRoomPhoto(page);
|
| 58 |
+
const wallLabel = await selectWallOnCanvas(page);
|
| 59 |
+
await applyTexture(page);
|
| 60 |
+
|
| 61 |
+
const override = page.locator('[data-testid="wall-override-card"]');
|
| 62 |
+
|
| 63 |
+
await expect(override).toBeVisible();
|
| 64 |
+
await expect(override).toContainText(wallLabel);
|
| 65 |
+
await expect(override.getByTestId("texture-adjust-rotation")).toBeVisible();
|
| 66 |
+
});
|
| 67 |
+
});
|
frontend/viz2d-demo/e2e/wall-tile-orientation.spec.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, test } from "@playwright/test";
|
| 2 |
+
|
| 3 |
+
import { applyTexture, openEditorWithRoomPhoto, selectWallOnCanvas } from "./helpers";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Every wall's tile grid must start plumb.
|
| 7 |
+
*
|
| 8 |
+
* When a wall has no per-pixel UV -- which is every wall on a CPU profile,
|
| 9 |
+
* where depth estimation is off -- the auto-rotation fell through to the angle
|
| 10 |
+
* of the mask's top edge. On a wall seen in perspective that edge is the
|
| 11 |
+
* slanted ceiling line, so the grid opened pre-tilted by that slant.
|
| 12 |
+
*
|
| 13 |
+
* The homography already carries the wall's perspective, so the correct
|
| 14 |
+
* starting rotation is zero and the user's slider moves away from there.
|
| 15 |
+
*
|
| 16 |
+
* This asserts on *every* wall on purpose. The first wall in this photo has an
|
| 17 |
+
* axis-aligned quad, so its fallback angle is 0 by accident and it cannot
|
| 18 |
+
* detect the bug; the second wall's quad is genuinely slanted.
|
| 19 |
+
*/
|
| 20 |
+
test.describe("wall tile orientation", () => {
|
| 21 |
+
test("every wall's tile grid starts unrotated", async ({ page }) => {
|
| 22 |
+
await openEditorWithRoomPhoto(page);
|
| 23 |
+
|
| 24 |
+
const walls = page.locator('[data-testid="surface-label"][data-surface-class="wall"]');
|
| 25 |
+
const wallCount = await walls.count();
|
| 26 |
+
expect(wallCount, "this photo should detect more than one wall").toBeGreaterThan(1);
|
| 27 |
+
|
| 28 |
+
for (let index = 0; index < wallCount; index += 1) {
|
| 29 |
+
const label = await selectWallOnCanvas(page, index);
|
| 30 |
+
await applyTexture(page);
|
| 31 |
+
|
| 32 |
+
const override = page.locator('[data-testid="wall-override-card"]');
|
| 33 |
+
await expect(override, `${label} should be the selected wall`).toContainText(label);
|
| 34 |
+
await expect(
|
| 35 |
+
override.getByTestId("texture-adjust-rotation"),
|
| 36 |
+
`${label} opened with a rotated tile grid`,
|
| 37 |
+
).toHaveValue("0");
|
| 38 |
+
}
|
| 39 |
+
});
|
| 40 |
+
});
|
scripts/test_wall_mask.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic checks for wall mask refinement.
|
| 2 |
+
|
| 3 |
+
No model downloads, no server — pure numpy, runs in under a second.
|
| 4 |
+
|
| 5 |
+
python scripts/test_wall_mask.py
|
| 6 |
+
|
| 7 |
+
Builds a toy room (ceiling band on top, wall band in the middle, floor below,
|
| 8 |
+
a mirror hanging on the wall), punches the kind of holes that 3D plane
|
| 9 |
+
assignment leaves behind, and asserts the refinement puts them back without
|
| 10 |
+
leaking into the ceiling.
|
| 11 |
+
|
| 12 |
+
The three "regression" sections each pin a bug found while developing this.
|
| 13 |
+
All of them produced plausible-looking output that was wrong, which is exactly
|
| 14 |
+
why they are worth keeping.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import pathlib
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
from services.geometry.multi_plane import merge_planes_by_point_consistency
|
| 27 |
+
from services.image.edge_snap import snap_mask_to_image_edges
|
| 28 |
+
from services.wall.components import wall_surface_components
|
| 29 |
+
from services.wall.mask import contour_fill, refine_wall_component_mask, wall_region_masks
|
| 30 |
+
from state import ADE20K_CLASSES
|
| 31 |
+
|
| 32 |
+
H, W = 400, 600
|
| 33 |
+
CEILING_ROWS = slice(0, 80)
|
| 34 |
+
WALL_ROWS = slice(80, 300)
|
| 35 |
+
FLOOR_ROWS = slice(300, 400)
|
| 36 |
+
MIRROR = (slice(120, 200), slice(100, 220))
|
| 37 |
+
HOLE_A = (slice(150, 210), slice(300, 380)) # interior hole, like a marble patch
|
| 38 |
+
HOLE_B = (slice(230, 260), slice(420, 470)) # second interior hole
|
| 39 |
+
|
| 40 |
+
failures: list[str] = []
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def check(label: str, condition: bool, detail: str = "") -> None:
|
| 44 |
+
if condition:
|
| 45 |
+
print(f" PASS {label}")
|
| 46 |
+
else:
|
| 47 |
+
failures.append(label)
|
| 48 |
+
print(f" FAIL {label}" + (f" ({detail})" if detail else ""))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def class_index(name: str) -> int:
|
| 52 |
+
return ADE20K_CLASSES.index(name)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def build_seg_map() -> np.ndarray:
|
| 56 |
+
seg = np.zeros((H, W), dtype=np.int32)
|
| 57 |
+
seg[CEILING_ROWS, :] = class_index("ceiling")
|
| 58 |
+
seg[WALL_ROWS, :] = class_index("wall")
|
| 59 |
+
seg[FLOOR_ROWS, :] = class_index("floor")
|
| 60 |
+
seg[MIRROR] = class_index("mirror")
|
| 61 |
+
return seg
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def main() -> int:
|
| 65 |
+
seg_map = build_seg_map()
|
| 66 |
+
wall_raw, barrier, reclaimable = wall_region_masks(seg_map)
|
| 67 |
+
|
| 68 |
+
print("\nwall_region_masks:")
|
| 69 |
+
check("wall class found", wall_raw.sum() > 0)
|
| 70 |
+
check("mirror is NOT part of the raw wall class", wall_raw[MIRROR].sum() == 0)
|
| 71 |
+
check("ceiling is a barrier", barrier[CEILING_ROWS, :].all())
|
| 72 |
+
check("floor is a barrier", barrier[FLOOR_ROWS, :].all())
|
| 73 |
+
check("mirror is reclaimable", reclaimable[MIRROR].all())
|
| 74 |
+
check("ceiling is not reclaimable", reclaimable[CEILING_ROWS, :].sum() == 0)
|
| 75 |
+
|
| 76 |
+
print("\ncontour_fill:")
|
| 77 |
+
holed = np.zeros((H, W), dtype=np.uint8)
|
| 78 |
+
holed[WALL_ROWS, :] = 1
|
| 79 |
+
holed[HOLE_A] = 0
|
| 80 |
+
filled = contour_fill(holed)
|
| 81 |
+
check("interior hole is filled", filled[HOLE_A].all())
|
| 82 |
+
check("does not grow past the original outline",
|
| 83 |
+
filled[CEILING_ROWS, :].sum() == 0)
|
| 84 |
+
check("empty mask stays empty", contour_fill(np.zeros((H, W), np.uint8)).sum() == 0)
|
| 85 |
+
|
| 86 |
+
print("\nrefine_wall_component_mask:")
|
| 87 |
+
# What plane assignment realistically hands over: the wall, minus the mirror
|
| 88 |
+
# (stripped as protected), minus a couple of patches dropped for noisy normals.
|
| 89 |
+
component = np.zeros((H, W), dtype=np.uint8)
|
| 90 |
+
component[WALL_ROWS, :] = 1
|
| 91 |
+
component[MIRROR] = 0
|
| 92 |
+
component[HOLE_A] = 0
|
| 93 |
+
component[HOLE_B] = 0
|
| 94 |
+
|
| 95 |
+
refined, metadata = refine_wall_component_mask(component, wall_raw, reclaimable, barrier)
|
| 96 |
+
|
| 97 |
+
check("dropped patch A recovered", refined[HOLE_A].all())
|
| 98 |
+
check("dropped patch B recovered", refined[HOLE_B].all())
|
| 99 |
+
check("mirror reclaimed (tile drawn behind it)", refined[MIRROR].all())
|
| 100 |
+
check("no bleed into ceiling", refined[CEILING_ROWS, :].sum() == 0,
|
| 101 |
+
f"{int(refined[CEILING_ROWS, :].sum())} px leaked")
|
| 102 |
+
check("no bleed into floor", refined[FLOOR_ROWS, :].sum() == 0,
|
| 103 |
+
f"{int(refined[FLOOR_ROWS, :].sum())} px leaked")
|
| 104 |
+
check("recovered more than it started with",
|
| 105 |
+
metadata["wallMaskPixelsAfter"] > metadata["wallMaskPixelsBefore"])
|
| 106 |
+
check("whole wall band is covered",
|
| 107 |
+
refined[WALL_ROWS, :].all(),
|
| 108 |
+
f"{int((refined[WALL_ROWS, :] == 0).sum())} px still missing")
|
| 109 |
+
|
| 110 |
+
print("\neroded outer boundary (the ragged ceiling join):")
|
| 111 |
+
# Plane assignment does not only punch interior holes; it chews a wavy edge
|
| 112 |
+
# into the top of the wall where it meets the ceiling. That gap is open, so
|
| 113 |
+
# contour fill alone cannot reach it.
|
| 114 |
+
eroded = np.zeros((H, W), dtype=np.uint8)
|
| 115 |
+
eroded[WALL_ROWS, :] = 1
|
| 116 |
+
rng = np.random.default_rng(0)
|
| 117 |
+
for x in range(0, W, 10):
|
| 118 |
+
bite = int(rng.integers(6, 34))
|
| 119 |
+
eroded[80:80 + bite, x:x + 10] = 0 # wavy bite out of the top
|
| 120 |
+
bite = int(rng.integers(6, 26))
|
| 121 |
+
eroded[300 - bite:300, x:x + 10] = 0 # and the bottom
|
| 122 |
+
eroded_refined, _ = refine_wall_component_mask(eroded, wall_raw, reclaimable, barrier)
|
| 123 |
+
|
| 124 |
+
before_cover = eroded[WALL_ROWS, :].mean()
|
| 125 |
+
after_cover = eroded_refined[WALL_ROWS, :].mean()
|
| 126 |
+
check("wall band coverage substantially restored",
|
| 127 |
+
after_cover > 0.97,
|
| 128 |
+
f"{before_cover:.1%} -> {after_cover:.1%}")
|
| 129 |
+
check("coverage strictly improved", after_cover > before_cover,
|
| 130 |
+
f"{before_cover:.1%} -> {after_cover:.1%}")
|
| 131 |
+
check("deep bites filled (row 100)", eroded_refined[100, :].mean() > 0.98,
|
| 132 |
+
f"{eroded_refined[100, :].mean():.0%}")
|
| 133 |
+
check("still no ceiling bleed after hull expansion",
|
| 134 |
+
eroded_refined[CEILING_ROWS, :].sum() == 0,
|
| 135 |
+
f"{int(eroded_refined[CEILING_ROWS, :].sum())} px leaked")
|
| 136 |
+
|
| 137 |
+
print("\nregression — a doorway must keep two walls apart:")
|
| 138 |
+
# Growing vertically through `allowed` (wall + furniture) with a generous
|
| 139 |
+
# reach let one wall travel down through a TV cabinet and absorb the wall
|
| 140 |
+
# beyond a doorway — two segments collapsed into one and geometry confidence
|
| 141 |
+
# fell from 0.91 to 0.70. Growth now travels through wall pixels only.
|
| 142 |
+
seg_two = np.zeros((H, W), dtype=np.int32)
|
| 143 |
+
seg_two[CEILING_ROWS, :] = class_index("ceiling")
|
| 144 |
+
seg_two[WALL_ROWS, :] = class_index("wall")
|
| 145 |
+
seg_two[FLOOR_ROWS, :] = class_index("floor")
|
| 146 |
+
seg_two[WALL_ROWS, 250:350] = class_index("door")
|
| 147 |
+
seg_two[250:300, 0:120] = class_index("cabinet") # furniture against the wall
|
| 148 |
+
wall_two, barrier_two, reclaim_two = wall_region_masks(seg_two)
|
| 149 |
+
|
| 150 |
+
near_wall = np.zeros((H, W), dtype=np.uint8)
|
| 151 |
+
near_wall[WALL_ROWS, 0:250] = 1
|
| 152 |
+
near_wall[seg_two == class_index("door")] = 0
|
| 153 |
+
near_wall[seg_two == class_index("cabinet")] = 0
|
| 154 |
+
near_wall[120:180, 60:200] = 0 # hole needing repair
|
| 155 |
+
near_refined, _ = refine_wall_component_mask(near_wall, wall_two, reclaim_two, barrier_two)
|
| 156 |
+
|
| 157 |
+
check("hole in the near wall still repaired", near_refined[120:180, 60:200].all())
|
| 158 |
+
check("does not cross the doorway to the far wall",
|
| 159 |
+
near_refined[WALL_ROWS, 350:].sum() == 0,
|
| 160 |
+
f"{int(near_refined[WALL_ROWS, 350:].sum())} px crossed")
|
| 161 |
+
check("does not tile the doorway opening itself",
|
| 162 |
+
near_refined[WALL_ROWS, 250:350].sum() == 0,
|
| 163 |
+
f"{int(near_refined[WALL_ROWS, 250:350].sum())} px in the doorway")
|
| 164 |
+
# Reclaimable is now "everything that is not wall or barrier", so bounding
|
| 165 |
+
# against it is vacuous. Bound against the near wall's own extent instead.
|
| 166 |
+
check("does not run away past its own wall",
|
| 167 |
+
int(near_refined[:, 300:].sum()) == 0,
|
| 168 |
+
f"{int(near_refined[:, 300:].sum())} px past the doorway")
|
| 169 |
+
|
| 170 |
+
print("\nregression — hull must not jump an opening to a disconnected wall:")
|
| 171 |
+
# In the living-room photo the wall wraps above a doorway, so its convex hull
|
| 172 |
+
# reached across the opening and swallowed the hallway wall beyond it. Two
|
| 173 |
+
# segments became one and Wall 2 disappeared.
|
| 174 |
+
seg_gap = np.zeros((H, W), dtype=np.int32)
|
| 175 |
+
seg_gap[CEILING_ROWS, :] = class_index("ceiling")
|
| 176 |
+
seg_gap[WALL_ROWS, :] = class_index("wall")
|
| 177 |
+
seg_gap[FLOOR_ROWS, :] = class_index("floor")
|
| 178 |
+
seg_gap[130:300, 300:600] = class_index("door") # the opening
|
| 179 |
+
ISLAND = (slice(190, 250), slice(400, 500))
|
| 180 |
+
seg_gap[ISLAND] = class_index("wall") # far wall through it
|
| 181 |
+
wall_gap, barrier_gap, reclaim_gap = wall_region_masks(seg_gap)
|
| 182 |
+
|
| 183 |
+
near = np.zeros((H, W), dtype=np.uint8)
|
| 184 |
+
near[80:130, :] = 1
|
| 185 |
+
near[WALL_ROWS, 0:300] = 1
|
| 186 |
+
near[seg_gap == class_index("door")] = 0
|
| 187 |
+
near[ISLAND] = 0
|
| 188 |
+
near_refined2, _ = refine_wall_component_mask(near, wall_gap, reclaim_gap, barrier_gap)
|
| 189 |
+
|
| 190 |
+
check("disconnected far wall NOT absorbed", near_refined2[ISLAND].sum() == 0,
|
| 191 |
+
f"{int(near_refined2[ISLAND].sum())} px absorbed")
|
| 192 |
+
check("opening itself not tiled", near_refined2[150:290, 320:590].sum() == 0,
|
| 193 |
+
f"{int(near_refined2[150:290, 320:590].sum())} px in the opening")
|
| 194 |
+
check("near wall itself still intact", near_refined2[WALL_ROWS, 0:290].mean() > 0.95,
|
| 195 |
+
f"{near_refined2[WALL_ROWS, 0:290].mean():.0%}")
|
| 196 |
+
|
| 197 |
+
print("\nregression — a genuinely absent region must stay absent:")
|
| 198 |
+
# A wall that really does stop halfway across must not be stretched to fill
|
| 199 |
+
# the frame; contour fill only closes enclosed holes, never open edges.
|
| 200 |
+
partial = np.zeros((H, W), dtype=np.uint8)
|
| 201 |
+
partial[WALL_ROWS, 0:200] = 1
|
| 202 |
+
partial_refined, _ = refine_wall_component_mask(partial, wall_raw, reclaimable, barrier)
|
| 203 |
+
right_edge = partial_refined[WALL_ROWS, 400:]
|
| 204 |
+
check("does not invent wall on the far side", right_edge.sum() == 0,
|
| 205 |
+
f"{int(right_edge.sum())} px invented")
|
| 206 |
+
|
| 207 |
+
print("\nedge snapping (guided filter):")
|
| 208 |
+
# A photo with a dead-straight horizontal edge at row 200, and a mask whose
|
| 209 |
+
# boundary wobbles around it by +/-6 px, as ellipse morphology leaves it.
|
| 210 |
+
photo = np.zeros((H, W, 3), dtype=np.uint8)
|
| 211 |
+
photo[:200, :] = 210 # bright above the edge
|
| 212 |
+
photo[200:, :] = 90 # dark below
|
| 213 |
+
wobbly = np.zeros((H, W), dtype=np.uint8)
|
| 214 |
+
rng3 = np.random.default_rng(3)
|
| 215 |
+
for x in range(0, W, 12):
|
| 216 |
+
offset = int(rng3.integers(-6, 7))
|
| 217 |
+
wobbly[200 + offset:, x:x + 12] = 1
|
| 218 |
+
|
| 219 |
+
def boundary_spread(mask):
|
| 220 |
+
"""Std-dev of the first set row per column: 0 means dead straight."""
|
| 221 |
+
rows = [int(np.argmax(col)) for col in mask.T if col.any()]
|
| 222 |
+
return float(np.std(rows))
|
| 223 |
+
|
| 224 |
+
before_spread = boundary_spread(wobbly)
|
| 225 |
+
snapped = snap_mask_to_image_edges(wobbly, photo)
|
| 226 |
+
after_spread = boundary_spread(snapped)
|
| 227 |
+
check("wobble reduced", after_spread < before_spread * 0.5,
|
| 228 |
+
f"stddev {before_spread:.2f} -> {after_spread:.2f} px")
|
| 229 |
+
check("boundary landed on the real edge",
|
| 230 |
+
abs(np.mean([int(np.argmax(c)) for c in snapped.T if c.any()]) - 200) < 3,
|
| 231 |
+
f"mean row {np.mean([int(np.argmax(c)) for c in snapped.T if c.any()]):.1f}, expected ~200")
|
| 232 |
+
check("interior is untouched", snapped[300:, :].all())
|
| 233 |
+
check("no image means no change",
|
| 234 |
+
np.array_equal(snap_mask_to_image_edges(wobbly, None), wobbly))
|
| 235 |
+
|
| 236 |
+
print("\nregression — an unlisted object class must still be reclaimed:")
|
| 237 |
+
# A wall-mounted TV is often labelled `screen`, which was absent from
|
| 238 |
+
# OCCLUDER_CLASSES. It therefore landed in neither the barrier set nor the
|
| 239 |
+
# reclaimable set and got clamped away, punching a TV-shaped hole through
|
| 240 |
+
# the middle of the wall. Reclaimable is now defined by exclusion, so no
|
| 241 |
+
# object class can fall through the gap.
|
| 242 |
+
seg_tv = np.zeros((H, W), dtype=np.int32)
|
| 243 |
+
seg_tv[CEILING_ROWS, :] = class_index("ceiling")
|
| 244 |
+
seg_tv[WALL_ROWS, :] = class_index("wall")
|
| 245 |
+
seg_tv[FLOOR_ROWS, :] = class_index("floor")
|
| 246 |
+
TV = (slice(130, 230), slice(200, 420))
|
| 247 |
+
seg_tv[TV] = class_index("screen") # deliberately not in OCCLUDER_CLASSES
|
| 248 |
+
wall_tv, barrier_tv, reclaim_tv = wall_region_masks(seg_tv)
|
| 249 |
+
|
| 250 |
+
check("'screen' counts as reclaimable", reclaim_tv[TV].all())
|
| 251 |
+
check("'screen' is not a barrier", barrier_tv[TV].sum() == 0)
|
| 252 |
+
|
| 253 |
+
tv_component = np.zeros((H, W), dtype=np.uint8)
|
| 254 |
+
tv_component[WALL_ROWS, :] = 1
|
| 255 |
+
tv_component[TV] = 0 # segmentation cut the TV out
|
| 256 |
+
tv_refined, _ = refine_wall_component_mask(tv_component, wall_tv, reclaim_tv, barrier_tv)
|
| 257 |
+
check("tile is laid behind the TV", tv_refined[TV].all(),
|
| 258 |
+
f"{int((tv_refined[TV] == 0).sum())} px still missing")
|
| 259 |
+
check("still no ceiling bleed", tv_refined[CEILING_ROWS, :].sum() == 0)
|
| 260 |
+
|
| 261 |
+
print("\nwall_surface_components return contract:")
|
| 262 |
+
# Caught a real crash: the connectivity-first restructure appended bare masks
|
| 263 |
+
# where the repair pass expects (area, mask) pairs, so sorting compared numpy
|
| 264 |
+
# rows and every conversion died with "truth value of an array ... ambiguous".
|
| 265 |
+
# geometry=None short-circuits the planarity split, so the whole function is
|
| 266 |
+
# exercisable without a GPU.
|
| 267 |
+
parts, protected_out = wall_surface_components(seg_map, min_area=2000, geometry=None)
|
| 268 |
+
check("returns a list of pairs",
|
| 269 |
+
all(isinstance(item, tuple) and len(item) == 2 for item in parts),
|
| 270 |
+
f"got {[type(i).__name__ for i in parts[:3]]}")
|
| 271 |
+
check("first element is an int area",
|
| 272 |
+
all(isinstance(area, int) for area, _ in parts))
|
| 273 |
+
check("second element is a 2D uint8 mask",
|
| 274 |
+
all(mask.ndim == 2 and mask.dtype == np.uint8 for _, mask in parts))
|
| 275 |
+
check("areas are sorted largest first",
|
| 276 |
+
[a for a, _ in parts] == sorted([a for a, _ in parts], reverse=True))
|
| 277 |
+
check("found the wall", len(parts) >= 1, f"{len(parts)} components")
|
| 278 |
+
check("protected mask returned", protected_out.shape == seg_map.shape)
|
| 279 |
+
|
| 280 |
+
print("\nplane merging by point consistency:")
|
| 281 |
+
# Numbers taken from a real living room measured on the GPU backend: the two
|
| 282 |
+
# halves of each flat wall sat 0.018 m and 0.035 m apart, while the
|
| 283 |
+
# protruding chimney breast was 0.155 m from its neighbours. RANSAC had
|
| 284 |
+
# banded each wall into vertical depth slabs.
|
| 285 |
+
rng2 = np.random.default_rng(7)
|
| 286 |
+
|
| 287 |
+
def wall_points(offset_m, count=4000, jitter=0.01):
|
| 288 |
+
"""A patch of a flat wall at x = offset_m, facing +x."""
|
| 289 |
+
pts = np.zeros((count, 3), dtype=np.float32)
|
| 290 |
+
pts[:, 0] = offset_m + rng2.normal(0, jitter, count)
|
| 291 |
+
pts[:, 1] = rng2.uniform(0, 2.5, count)
|
| 292 |
+
pts[:, 2] = rng2.uniform(0, 3.0, count)
|
| 293 |
+
return pts
|
| 294 |
+
|
| 295 |
+
def plane_at(offset_m, count):
|
| 296 |
+
return {"id": 0, "normal": np.array([1.0, 0.0, 0.0], np.float32),
|
| 297 |
+
"origin": np.array([offset_m, 0.0, 0.0], np.float32),
|
| 298 |
+
"offset": -offset_m, "inlierCount": count, "fitMode": "normal-aware"}
|
| 299 |
+
|
| 300 |
+
# Two slabs of ONE wall (0.035 m apart) plus a chimney breast (0.155 m out).
|
| 301 |
+
near, far, chimney = wall_points(0.0), wall_points(0.035), wall_points(0.155)
|
| 302 |
+
pts = np.vstack([near, far, chimney])
|
| 303 |
+
assign = np.concatenate([np.zeros(len(near), np.int32),
|
| 304 |
+
np.ones(len(far), np.int32),
|
| 305 |
+
np.full(len(chimney), 2, np.int32)])
|
| 306 |
+
planes = [plane_at(0.0, len(near)), plane_at(0.035, len(far)), plane_at(0.155, len(chimney))]
|
| 307 |
+
|
| 308 |
+
new_assign, new_planes = merge_planes_by_point_consistency(pts, assign, planes, 0.04)
|
| 309 |
+
check("two slabs of one wall merged", len(new_planes) == 2,
|
| 310 |
+
f"got {len(new_planes)} planes, expected 2")
|
| 311 |
+
check("chimney breast kept separate",
|
| 312 |
+
len(set(new_assign[:len(near)])) == 1
|
| 313 |
+
and new_assign[0] == new_assign[len(near)]
|
| 314 |
+
and new_assign[0] != new_assign[-1])
|
| 315 |
+
check("no point left unassigned", (new_assign >= 0).all())
|
| 316 |
+
|
| 317 |
+
far_apart = merge_planes_by_point_consistency(
|
| 318 |
+
pts, assign.copy(), [plane_at(0.0, 4000), plane_at(0.6, 4000), plane_at(1.2, 4000)], 0.04)[1]
|
| 319 |
+
check("clearly separate walls are never merged", len(far_apart) == 3,
|
| 320 |
+
f"got {len(far_apart)}")
|
| 321 |
+
|
| 322 |
+
print()
|
| 323 |
+
if failures:
|
| 324 |
+
print(f"{len(failures)} FAILED: {', '.join(failures)}")
|
| 325 |
+
return 1
|
| 326 |
+
print("All checks passed.")
|
| 327 |
+
return 0
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
if __name__ == "__main__":
|
| 331 |
+
sys.exit(main())
|
scripts/wall_smoke_test.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Push one image through the pipeline and report what it found — wall-focused.
|
| 2 |
+
|
| 3 |
+
Usage (from backend/floor-visualizer, with the server running):
|
| 4 |
+
|
| 5 |
+
python scripts/wall_smoke_test.py
|
| 6 |
+
python scripts/wall_smoke_test.py path/to/room.jpg
|
| 7 |
+
python scripts/wall_smoke_test.py path/to/room.jpg --base https://xxx.trycloudflare.com
|
| 8 |
+
|
| 9 |
+
Prints the per-stage timings, then one line per detected surface. The wall lines
|
| 10 |
+
are the interesting ones:
|
| 11 |
+
|
| 12 |
+
uv=no -> the wall is on a single-matrix transform, so
|
| 13 |
+
tile scale comes from its bounding box
|
| 14 |
+
rather than from measured geometry
|
| 15 |
+
mapping=wall-contour-homography -> the metric fit was rejected entirely
|
| 16 |
+
mapping=surface-uv -> per-pixel UV, same treatment as the floor
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import io
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
import zipfile
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import requests
|
| 30 |
+
|
| 31 |
+
REPO_ROOT = Path(__file__).resolve().parents[3]
|
| 32 |
+
DEFAULT_IMAGE = (
|
| 33 |
+
REPO_ROOT / "frontend" / "viz2d-demo" / "src" / "assets" / "presets" / "bathroom.jpg"
|
| 34 |
+
)
|
| 35 |
+
# localtunnel serves a password interstitial to browsers; this header opts out.
|
| 36 |
+
HEADERS = {"bypass-tunnel-reminder": "1", "ngrok-skip-browser-warning": "true"}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main() -> int:
|
| 40 |
+
parser = argparse.ArgumentParser()
|
| 41 |
+
parser.add_argument("image", nargs="?", default=str(DEFAULT_IMAGE))
|
| 42 |
+
parser.add_argument("--base", default="http://localhost:8002")
|
| 43 |
+
parser.add_argument("--timeout", type=int, default=900, help="seconds to wait for the job")
|
| 44 |
+
args = parser.parse_args()
|
| 45 |
+
|
| 46 |
+
image_path = Path(args.image)
|
| 47 |
+
if not image_path.exists():
|
| 48 |
+
print(f"Image not found: {image_path}")
|
| 49 |
+
return 1
|
| 50 |
+
|
| 51 |
+
base = args.base.rstrip("/")
|
| 52 |
+
print(f"POST {base}/viz2d/convert ({image_path.name})")
|
| 53 |
+
with image_path.open("rb") as handle:
|
| 54 |
+
response = requests.post(
|
| 55 |
+
f"{base}/viz2d/convert",
|
| 56 |
+
files={"file": (image_path.name, handle, "image/jpeg")},
|
| 57 |
+
headers=HEADERS,
|
| 58 |
+
timeout=180,
|
| 59 |
+
)
|
| 60 |
+
response.raise_for_status()
|
| 61 |
+
job = response.json()
|
| 62 |
+
job_id = job["id"]
|
| 63 |
+
print(f"job {job_id}\n")
|
| 64 |
+
|
| 65 |
+
deadline = time.time() + args.timeout
|
| 66 |
+
last = None
|
| 67 |
+
while job.get("status") not in ("COMPLETED", "FAILED"):
|
| 68 |
+
if time.time() > deadline:
|
| 69 |
+
print(f"\nTimed out after {args.timeout}s (status={job.get('status')}).")
|
| 70 |
+
return 1
|
| 71 |
+
time.sleep(2)
|
| 72 |
+
job = requests.get(f"{base}/viz2d/jobs/{job_id}", headers=HEADERS, timeout=60).json()
|
| 73 |
+
line = f" {job.get('status', '?'):<14} {job.get('progress', 0):>3}% {job.get('message', '')}"
|
| 74 |
+
if line != last:
|
| 75 |
+
print(line)
|
| 76 |
+
last = line
|
| 77 |
+
|
| 78 |
+
if job.get("status") == "FAILED":
|
| 79 |
+
print(f"\nFAILED: {job.get('error')}")
|
| 80 |
+
return 1
|
| 81 |
+
|
| 82 |
+
print(f"\nCompleted in {job.get('durationMs')} ms")
|
| 83 |
+
for stage in job.get("pipelineStages", []):
|
| 84 |
+
print(f" {stage['name']:<34} {stage['elapsed_s']:>7.2f}s {stage.get('detail', '')}")
|
| 85 |
+
|
| 86 |
+
blob = requests.get(f"{base}/viz2d/jobs/{job_id}/file", headers=HEADERS, timeout=300).content
|
| 87 |
+
meta = json.loads(zipfile.ZipFile(io.BytesIO(blob)).read("metadata.json"))
|
| 88 |
+
|
| 89 |
+
print(f"\nBundle: {meta['width']}x{meta['height']}, {len(meta['segments'])} segment(s)")
|
| 90 |
+
walls = 0
|
| 91 |
+
for segment in meta["segments"]:
|
| 92 |
+
info = segment.get("metadata", {})
|
| 93 |
+
name = segment.get("className", "?")
|
| 94 |
+
if name == "wall":
|
| 95 |
+
walls += 1
|
| 96 |
+
pixels = info.get("surfacePixels") or info.get("wallPixels") or 0
|
| 97 |
+
width = info.get("surfaceWidthMeters")
|
| 98 |
+
height = info.get("surfaceHeightMeters")
|
| 99 |
+
size = (
|
| 100 |
+
f"{width:.2f}x{height:.2f}m"
|
| 101 |
+
if isinstance(width, (int, float)) and isinstance(height, (int, float))
|
| 102 |
+
else "n/a"
|
| 103 |
+
)
|
| 104 |
+
coverage = info.get("surfaceUvCoverage")
|
| 105 |
+
print(
|
| 106 |
+
f" [{segment.get('id')}] {name:<6} "
|
| 107 |
+
f"px={pixels:<8} "
|
| 108 |
+
f"uv={'yes' if segment.get('surfaceUv') else 'no':<4} "
|
| 109 |
+
f"cov={coverage if coverage is None else round(float(coverage), 4)!s:<8} "
|
| 110 |
+
f"mapping={str(info.get('textureMappingMode')):<26} "
|
| 111 |
+
f"conf={info.get('geometryConfidence')} "
|
| 112 |
+
f"size={size}"
|
| 113 |
+
)
|
| 114 |
+
print(f"\n{walls} wall segment(s).")
|
| 115 |
+
|
| 116 |
+
debug = requests.get(f"{base}/viz2d/jobs/{job_id}/debug", headers=HEADERS, timeout=60)
|
| 117 |
+
if debug.ok:
|
| 118 |
+
stages = debug.json().get("stages", [])
|
| 119 |
+
print(f"Debug artifacts: {len(stages)} stage(s) at data/jobs/{job_id}.debug/")
|
| 120 |
+
else:
|
| 121 |
+
print("Debug artifacts unavailable (DEBUG_ARTIFACTS_ENABLED off?).")
|
| 122 |
+
|
| 123 |
+
print(f"\nJOB_ID={job_id}")
|
| 124 |
+
return 0
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == "__main__":
|
| 128 |
+
sys.exit(main())
|
services/wall/components.py
CHANGED
|
@@ -13,24 +13,122 @@ from services.geometry.multi_plane import (
|
|
| 13 |
assign_points_to_surface_planes,
|
| 14 |
fit_multi_surface_planes,
|
| 15 |
geometry_point_maps,
|
|
|
|
|
|
|
| 16 |
)
|
| 17 |
from services.geometry.normals import normalize_vectors
|
|
|
|
|
|
|
|
|
|
| 18 |
from state import OCCLUDER_CLASSES, class_ids
|
| 19 |
from utils import seg_class_mask
|
| 20 |
|
| 21 |
|
| 22 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"""Create clean, independently renderable wall regions.
|
| 24 |
|
| 25 |
Semantic wall predictions often bridge across corners and openings. Removing
|
| 26 |
protected classes before connected-component analysis prevents one warped
|
| 27 |
transform from being applied to several physically different walls.
|
| 28 |
"""
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | {
|
| 31 |
"door", "window", "column", "base", "railing", "ceiling",
|
| 32 |
"building", "painting", "mirror", "curtain",
|
| 33 |
}))
|
|
|
|
|
|
|
|
|
|
| 34 |
radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
|
| 35 |
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
|
| 36 |
protected = cv2.dilate(protected, kernel, iterations=1)
|
|
@@ -39,54 +137,68 @@ def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict |
|
|
| 39 |
wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
|
| 40 |
wall[protected > 0] = 0
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
components = []
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
ys, xs = ys[normals_reliable], xs[normals_reliable]
|
| 59 |
-
planes = fit_multi_surface_planes(points, normals, True)
|
| 60 |
-
wall_planes = [
|
| 61 |
-
plane for plane in planes
|
| 62 |
-
if abs(float(plane["normal"][1])) <= 0.45
|
| 63 |
-
]
|
| 64 |
-
if wall_planes:
|
| 65 |
-
assignment = assign_points_to_surface_planes(
|
| 66 |
-
points, normals, wall_planes, True
|
| 67 |
-
)
|
| 68 |
-
for plane_index in range(len(wall_planes)):
|
| 69 |
-
selected = assignment == plane_index
|
| 70 |
-
if int(selected.sum()) < min_area:
|
| 71 |
-
continue
|
| 72 |
-
plane_mask = np.zeros_like(wall)
|
| 73 |
-
plane_mask[ys[selected], xs[selected]] = 1
|
| 74 |
-
count, labels, stats, _ = cv2.connectedComponentsWithStats(
|
| 75 |
-
plane_mask, connectivity=8
|
| 76 |
-
)
|
| 77 |
-
for component_id in range(1, count):
|
| 78 |
-
area = int(stats[component_id, cv2.CC_STAT_AREA])
|
| 79 |
-
if area >= min_area:
|
| 80 |
-
components.append((area, (labels == component_id).astype(np.uint8)))
|
| 81 |
-
|
| 82 |
-
# Geometry can be unavailable or too noisy. In that case retain the safe
|
| 83 |
-
# semantic connected-component fallback instead of emitting no walls.
|
| 84 |
-
if not components:
|
| 85 |
-
count, labels, stats, _ = cv2.connectedComponentsWithStats(wall, connectivity=8)
|
| 86 |
-
for component_id in range(1, count):
|
| 87 |
-
area = int(stats[component_id, cv2.CC_STAT_AREA])
|
| 88 |
-
if area < min_area:
|
| 89 |
-
continue
|
| 90 |
-
components.append((area, (labels == component_id).astype(np.uint8)))
|
| 91 |
components.sort(key=lambda item: item[0], reverse=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
return components, protected
|
|
|
|
| 13 |
assign_points_to_surface_planes,
|
| 14 |
fit_multi_surface_planes,
|
| 15 |
geometry_point_maps,
|
| 16 |
+
merge_coplanar_planes,
|
| 17 |
+
merge_planes_by_point_consistency,
|
| 18 |
)
|
| 19 |
from services.geometry.normals import normalize_vectors
|
| 20 |
+
from services.geometry.plane_fitting import surface_distance_threshold
|
| 21 |
+
from services.wall.corner import straighten_piece_seams
|
| 22 |
+
from services.wall.mask import refine_wall_component_mask, wall_region_masks
|
| 23 |
from state import OCCLUDER_CLASSES, class_ids
|
| 24 |
from utils import seg_class_mask
|
| 25 |
|
| 26 |
|
| 27 |
+
def split_region_if_not_planar(region: np.ndarray, geometry: dict | None, min_area: int):
|
| 28 |
+
"""Return [region] when it is one flat wall, else split it by fitted planes.
|
| 29 |
+
|
| 30 |
+
Connectivity alone is not quite enough: where two walls meet at a corner
|
| 31 |
+
with nothing between them, segmentation bridges the corner and hands us one
|
| 32 |
+
region covering both. Those need separating, or one warped transform gets
|
| 33 |
+
stretched across an angle.
|
| 34 |
+
|
| 35 |
+
So geometry gets a narrow, well-posed job: decide whether this region is
|
| 36 |
+
flat. A single least-squares plane is fitted and the 90th-percentile
|
| 37 |
+
residual measured. A real wall sits within a couple of centimetres of its
|
| 38 |
+
own plane; a region spanning a corner does not come close. Only when the
|
| 39 |
+
region fails that test do we fall back to multi-plane splitting.
|
| 40 |
+
"""
|
| 41 |
+
if geometry is None:
|
| 42 |
+
return [region]
|
| 43 |
+
maps = geometry_point_maps(region, geometry)
|
| 44 |
+
if maps is None:
|
| 45 |
+
return [region]
|
| 46 |
+
|
| 47 |
+
valid = maps["validMask"] & (region > 0)
|
| 48 |
+
ys, xs = np.where(valid)
|
| 49 |
+
if len(xs) < SURFACE_MIN_PLANE_PIXELS:
|
| 50 |
+
return [region]
|
| 51 |
+
points = maps["points"][ys, xs].astype(np.float32)
|
| 52 |
+
normals = maps["normals"][ys, xs].astype(np.float32)
|
| 53 |
+
finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1)
|
| 54 |
+
points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite]
|
| 55 |
+
if len(points) < SURFACE_MIN_PLANE_PIXELS:
|
| 56 |
+
return [region]
|
| 57 |
+
|
| 58 |
+
threshold = surface_distance_threshold(points)
|
| 59 |
+
centered = points - points.mean(axis=0)
|
| 60 |
+
# Smallest-eigenvalue eigenvector of the covariance is the plane normal.
|
| 61 |
+
_eigenvalues, eigenvectors = np.linalg.eigh(centered.T @ centered)
|
| 62 |
+
residual = np.abs(centered @ eigenvectors[:, 0].astype(np.float32))
|
| 63 |
+
flatness = float(np.percentile(residual, 90))
|
| 64 |
+
print(
|
| 65 |
+
f"[WALL_REGION] {int(region.sum())} px p90Flatness={flatness:.3f}m "
|
| 66 |
+
f"threshold={threshold:.3f}m {'FLAT (keep whole)' if flatness <= threshold else 'not flat -> split by plane'}",
|
| 67 |
+
flush=True,
|
| 68 |
+
)
|
| 69 |
+
if flatness <= threshold:
|
| 70 |
+
return [region]
|
| 71 |
+
|
| 72 |
+
lengths = np.linalg.norm(normals, axis=1)
|
| 73 |
+
usable = lengths > 1e-4
|
| 74 |
+
if int(usable.sum()) < SURFACE_MIN_PLANE_PIXELS:
|
| 75 |
+
return [region]
|
| 76 |
+
points, ys, xs = points[usable], ys[usable], xs[usable]
|
| 77 |
+
normals = normalize_vectors(normals[usable])
|
| 78 |
+
|
| 79 |
+
planes = fit_multi_surface_planes(points, normals, True, mark_floor=False)
|
| 80 |
+
planes = merge_coplanar_planes(planes, threshold)
|
| 81 |
+
wall_planes = [plane for plane in planes if abs(float(plane["normal"][1])) <= 0.45]
|
| 82 |
+
if len(wall_planes) <= 1:
|
| 83 |
+
return [region]
|
| 84 |
+
|
| 85 |
+
assignment = assign_points_to_surface_planes(points, normals, wall_planes, True)
|
| 86 |
+
assignment, wall_planes = merge_planes_by_point_consistency(
|
| 87 |
+
points, assignment, wall_planes, threshold
|
| 88 |
+
)
|
| 89 |
+
if len(wall_planes) <= 1:
|
| 90 |
+
return [region]
|
| 91 |
+
|
| 92 |
+
pieces = []
|
| 93 |
+
for plane_index in range(len(wall_planes)):
|
| 94 |
+
selected = assignment == plane_index
|
| 95 |
+
if int(selected.sum()) < min_area:
|
| 96 |
+
continue
|
| 97 |
+
piece = np.zeros_like(region)
|
| 98 |
+
piece[ys[selected], xs[selected]] = 1
|
| 99 |
+
pieces.append((plane_index, piece))
|
| 100 |
+
if not pieces:
|
| 101 |
+
return [region]
|
| 102 |
+
|
| 103 |
+
# Per-pixel assignment is the wrong tool for the seam *between* these
|
| 104 |
+
# pieces. At the corner every plane is equidistant, so the score collapses
|
| 105 |
+
# onto blended depth normals and the boundary ends up both biased and
|
| 106 |
+
# ragged. Put each seam back on the line where its two planes actually
|
| 107 |
+
# intersect -- see services/wall/corner.py for the measurements.
|
| 108 |
+
return straighten_piece_seams(pieces, wall_planes, maps.get("intrinsics"), min_area)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None,
|
| 112 |
+
image_rgb: np.ndarray | None = None):
|
| 113 |
"""Create clean, independently renderable wall regions.
|
| 114 |
|
| 115 |
Semantic wall predictions often bridge across corners and openings. Removing
|
| 116 |
protected classes before connected-component analysis prevents one warped
|
| 117 |
transform from being applied to several physically different walls.
|
| 118 |
"""
|
| 119 |
+
# Components may occupy the wall itself plus anything mounted on it; those
|
| 120 |
+
# objects are re-drawn over the tile via the segment occlusion mask instead
|
| 121 |
+
# of being cut out of the surface. See services/wall/mask.py.
|
| 122 |
+
wall_raw, barrier_mask, reclaimable_mask = wall_region_masks(seg_map)
|
| 123 |
+
|
| 124 |
+
wall = wall_raw.copy()
|
| 125 |
protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | {
|
| 126 |
"door", "window", "column", "base", "railing", "ceiling",
|
| 127 |
"building", "painting", "mirror", "curtain",
|
| 128 |
}))
|
| 129 |
+
# Wide enough to close the gap a wall-mounted TV or mirror leaves behind,
|
| 130 |
+
# narrow enough that a doorway or a room corner still separates two walls.
|
| 131 |
+
bridge_kernel_size = max(3, int(round(min(seg_map.shape[:2]) * 0.05))) | 1
|
| 132 |
radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
|
| 133 |
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
|
| 134 |
protected = cv2.dilate(protected, kernel, iterations=1)
|
|
|
|
| 137 |
wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
|
| 138 |
wall[protected > 0] = 0
|
| 139 |
|
| 140 |
+
# --- Stage 1: connectivity decides what counts as one wall ----------------
|
| 141 |
+
# Geometry used to decide this, by fitting planes over every wall pixel and
|
| 142 |
+
# assigning each pixel to its nearest plane. Per-pixel normals from depth are
|
| 143 |
+
# noisy, so that assignment banded single walls into vertical depth slabs: a
|
| 144 |
+
# living room with three walls produced three planes but five segments, each
|
| 145 |
+
# with its own UV frame, so the tile grid restarted and rotated at every
|
| 146 |
+
# seam. Spatial connectivity is far more reliable for "is this one wall",
|
| 147 |
+
# because walls are separated by corners, which are visible discontinuities.
|
| 148 |
+
bridge = cv2.morphologyEx(
|
| 149 |
+
wall,
|
| 150 |
+
cv2.MORPH_CLOSE,
|
| 151 |
+
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (bridge_kernel_size, bridge_kernel_size)),
|
| 152 |
+
)
|
| 153 |
+
region_count, region_labels, _region_stats, _ = cv2.connectedComponentsWithStats(
|
| 154 |
+
bridge, connectivity=8
|
| 155 |
+
)
|
| 156 |
+
regions = []
|
| 157 |
+
for region_id in range(1, region_count):
|
| 158 |
+
region = ((region_labels == region_id) & (wall > 0)).astype(np.uint8)
|
| 159 |
+
if int(region.sum()) >= min_area:
|
| 160 |
+
regions.append(region)
|
| 161 |
+
print(f"[WALL_COMPONENTS] {len(regions)} connected wall region(s)", flush=True)
|
| 162 |
+
|
| 163 |
+
# --- Stage 2: geometry only splits a region that is not actually flat -----
|
| 164 |
+
# components is a list of (area, mask) pairs; the repair pass below sorts on
|
| 165 |
+
# the area, so pieces must be paired up rather than appended bare.
|
| 166 |
components = []
|
| 167 |
+
for region in regions:
|
| 168 |
+
for piece in split_region_if_not_planar(region, geometry, min_area):
|
| 169 |
+
area = int(piece.sum())
|
| 170 |
+
if area >= min_area:
|
| 171 |
+
components.append((area, piece.astype(np.uint8)))
|
| 172 |
+
|
| 173 |
+
# --- Repair pass -------------------------------------------------------
|
| 174 |
+
# Splitting above deliberately runs on the protected-subtracted mask, so one
|
| 175 |
+
# warped transform is never stretched across a corner or an opening. Now
|
| 176 |
+
# that the split is settled, each component reclaims the holes that plane
|
| 177 |
+
# assignment and protection punched through it.
|
| 178 |
+
#
|
| 179 |
+
# Largest first, subtracting whatever earlier components already claimed, so
|
| 180 |
+
# the refined masks stay disjoint — otherwise the edge-repair dilation would
|
| 181 |
+
# let two walls overlap at a corner and that seam would be tiled twice.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
components.sort(key=lambda item: item[0], reverse=True)
|
| 183 |
+
claimed = np.zeros(wall_raw.shape[:2], dtype=bool)
|
| 184 |
+
refined_components = []
|
| 185 |
+
for _, component_mask in components:
|
| 186 |
+
refined, _metadata = refine_wall_component_mask(
|
| 187 |
+
component_mask, wall_raw, reclaimable_mask, barrier_mask, image_rgb
|
| 188 |
+
)
|
| 189 |
+
refined[claimed] = 0
|
| 190 |
+
area = int(refined.sum())
|
| 191 |
+
if area < min_area:
|
| 192 |
+
continue
|
| 193 |
+
claimed |= refined.astype(bool)
|
| 194 |
+
refined_components.append((area, refined))
|
| 195 |
+
|
| 196 |
+
if refined_components:
|
| 197 |
+
refined_components.sort(key=lambda item: item[0], reverse=True)
|
| 198 |
+
print(
|
| 199 |
+
f"[WALL_COMPONENTS] emitting {len(refined_components)} wall segment(s): "
|
| 200 |
+
f"{[area for area, _ in refined_components]} px",
|
| 201 |
+
flush=True,
|
| 202 |
+
)
|
| 203 |
+
return refined_components, protected
|
| 204 |
return components, protected
|
services/wall/corner.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Place the seam between two wall surfaces on the corner they actually share.
|
| 2 |
+
|
| 3 |
+
Why this exists
|
| 4 |
+
---------------
|
| 5 |
+
Splitting one connected wall region into several surfaces is done by
|
| 6 |
+
``assign_points_to_surface_planes``, which scores each pixel against each fitted
|
| 7 |
+
plane on its own. That works in the middle of a wall and fails at a corner, for
|
| 8 |
+
a reason that is structural rather than a tuning problem: two planes *intersect*
|
| 9 |
+
at the corner, so the distance term of the score goes to zero for both of them
|
| 10 |
+
there. The decision is left to the per-pixel depth normal, and a learned depth
|
| 11 |
+
model rounds a corner, so across a band of a few tens of pixels that normal is
|
| 12 |
+
a blend of both walls. Blended normals sit outside SURFACE_NORMAL_ANGLE_DEGREES
|
| 13 |
+
of either plane, the score degenerates to ``argmin(distance)`` on the rounded
|
| 14 |
+
surface, and the seam lands wherever the rounding happened to fall.
|
| 15 |
+
|
| 16 |
+
Measured on job 03d0c9df (a bathroom, white marble, three walls): the back
|
| 17 |
+
wall's left edge came out at column 291.5 against a corner at 262, wandering
|
| 18 |
+
between 277 and 337. On screen that is a ~25 px strip of untiled wall down the
|
| 19 |
+
inside of the corner with a torn edge.
|
| 20 |
+
|
| 21 |
+
The fix
|
| 22 |
+
-------
|
| 23 |
+
Two planes meet along a straight line in 3D, and a pinhole camera projects a
|
| 24 |
+
straight line to a straight line. That projection is the corner. It is derived
|
| 25 |
+
from the two *global* plane fits -- which are RANSAC results over tens of
|
| 26 |
+
thousands of points, inlier ratios around 0.9-0.99 -- and never from a per-pixel
|
| 27 |
+
normal, so it is both unbiased and straight by construction.
|
| 28 |
+
|
| 29 |
+
On that job the line lands at column 266.0-266.8 over the full image height:
|
| 30 |
+
4 px from the true corner instead of 30, and with no wander at all.
|
| 31 |
+
|
| 32 |
+
Limits
|
| 33 |
+
------
|
| 34 |
+
Only meaningful for two planes that genuinely meet inside the picture. Parallel
|
| 35 |
+
planes, and planes meeting behind the camera, are refused rather than guessed
|
| 36 |
+
at, and callers keep their original split.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
from __future__ import annotations
|
| 40 |
+
|
| 41 |
+
import numpy as np
|
| 42 |
+
|
| 43 |
+
# |n_a x n_b| is sin(angle between the planes), so this is a 5 degree floor.
|
| 44 |
+
#
|
| 45 |
+
# It is not about avoiding a divide-by-zero, it is about conditioning. The
|
| 46 |
+
# intersection line's position error scales roughly as (normal error)/sin(angle),
|
| 47 |
+
# and RANSAC plane normals are good to about half a degree. At 5 degrees that
|
| 48 |
+
# puts the line within ~10% of the wall's extent; at half a degree it is further
|
| 49 |
+
# out than the wall is wide, which is worse than the per-pixel split it replaces.
|
| 50 |
+
# Anything shallower than this is two fits of one flat wall, which
|
| 51 |
+
# merge_coplanar_planes is responsible for collapsing.
|
| 52 |
+
MIN_CROSS_NORM = float(np.sin(np.deg2rad(5.0)))
|
| 53 |
+
# A point on the intersection must be at least this far in front of the camera
|
| 54 |
+
# before it can be projected at all.
|
| 55 |
+
MIN_DEPTH_METERS = 0.05
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def corner_line_in_image(
|
| 59 |
+
plane_a: dict,
|
| 60 |
+
plane_b: dict,
|
| 61 |
+
intrinsics: np.ndarray,
|
| 62 |
+
height: int,
|
| 63 |
+
width: int,
|
| 64 |
+
) -> tuple[float, float, float] | None:
|
| 65 |
+
"""Return ``(a, b, c)`` with ``a*x + b*y + c = 0`` along the shared corner.
|
| 66 |
+
|
| 67 |
+
``plane_a`` and ``plane_b`` are the dicts produced by the plane fitter: a
|
| 68 |
+
unit ``normal`` and an ``origin`` lying on the plane. Returns None when the
|
| 69 |
+
planes do not meet in front of the camera.
|
| 70 |
+
"""
|
| 71 |
+
normal_a = np.asarray(plane_a["normal"], dtype=np.float64).ravel()
|
| 72 |
+
normal_b = np.asarray(plane_b["normal"], dtype=np.float64).ravel()
|
| 73 |
+
origin_a = np.asarray(plane_a["origin"], dtype=np.float64).ravel()
|
| 74 |
+
origin_b = np.asarray(plane_b["origin"], dtype=np.float64).ravel()
|
| 75 |
+
if normal_a.size != 3 or normal_b.size != 3:
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
direction = np.cross(normal_a, normal_b)
|
| 79 |
+
norm = float(np.linalg.norm(direction))
|
| 80 |
+
if norm < MIN_CROSS_NORM:
|
| 81 |
+
return None # parallel: no corner between them
|
| 82 |
+
direction /= norm
|
| 83 |
+
|
| 84 |
+
# The point on the intersection closest to the origin, found by adding the
|
| 85 |
+
# line's own direction as a third constraint so the system is square.
|
| 86 |
+
matrix = np.array([normal_a, normal_b, direction])
|
| 87 |
+
offsets = np.array([normal_a @ origin_a, normal_b @ origin_b, 0.0])
|
| 88 |
+
try:
|
| 89 |
+
anchor = np.linalg.solve(matrix, offsets)
|
| 90 |
+
except np.linalg.LinAlgError:
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
# Two points far enough apart to define the projected line stably. The line
|
| 94 |
+
# is straight under projection, so any two visible points on it will do.
|
| 95 |
+
intrinsics = np.asarray(intrinsics, dtype=np.float64).reshape(3, 3)
|
| 96 |
+
span = max(height, width) / float(max(intrinsics[0, 0], 1.0)) * float(anchor[2] or 1.0)
|
| 97 |
+
span = float(np.clip(abs(span), 1.0, 1e4))
|
| 98 |
+
projected = []
|
| 99 |
+
for step in (-span, span):
|
| 100 |
+
point = anchor + direction * step
|
| 101 |
+
if point[2] <= MIN_DEPTH_METERS:
|
| 102 |
+
continue
|
| 103 |
+
u = intrinsics[0, 0] * point[0] / point[2] + intrinsics[0, 2]
|
| 104 |
+
v = intrinsics[1, 1] * point[1] / point[2] + intrinsics[1, 2]
|
| 105 |
+
projected.append((float(u), float(v)))
|
| 106 |
+
if len(projected) < 2:
|
| 107 |
+
return None # the corner is behind the camera
|
| 108 |
+
|
| 109 |
+
(u0, v0), (u1, v1) = projected
|
| 110 |
+
dx, dy = u1 - u0, v1 - v0
|
| 111 |
+
if abs(dx) < 1e-9 and abs(dy) < 1e-9:
|
| 112 |
+
return None
|
| 113 |
+
# Line through the two points: a = dy, b = -dx, c = dx*v0 - dy*u0.
|
| 114 |
+
a, b = dy, -dx
|
| 115 |
+
c = dx * v0 - dy * u0
|
| 116 |
+
scale = float(np.hypot(a, b))
|
| 117 |
+
if scale < 1e-12:
|
| 118 |
+
return None
|
| 119 |
+
return (a / scale, b / scale, c / scale)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def signed_distance_to_line(
|
| 123 |
+
line: tuple[float, float, float], height: int, width: int
|
| 124 |
+
) -> np.ndarray:
|
| 125 |
+
"""Per-pixel signed distance to `line`, positive on one arbitrary side."""
|
| 126 |
+
a, b, c = line
|
| 127 |
+
ys, xs = np.mgrid[0:height, 0:width]
|
| 128 |
+
return (a * xs + b * ys + c).astype(np.float32)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def split_pieces_on_corner_line(
|
| 132 |
+
piece_a: np.ndarray,
|
| 133 |
+
piece_b: np.ndarray,
|
| 134 |
+
line: tuple[float, float, float],
|
| 135 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 136 |
+
"""Re-cut two touching pieces along `line`, keeping their union identical.
|
| 137 |
+
|
| 138 |
+
Which piece takes which side is decided by where each one's own mass
|
| 139 |
+
already lies, so the caller does not have to know the sign convention. Only
|
| 140 |
+
the pixels the two pieces already occupy are redistributed -- nothing is
|
| 141 |
+
gained from, or lost to, the rest of the image.
|
| 142 |
+
"""
|
| 143 |
+
a_mask = piece_a.astype(bool)
|
| 144 |
+
b_mask = piece_b.astype(bool)
|
| 145 |
+
union = a_mask | b_mask
|
| 146 |
+
if not union.any():
|
| 147 |
+
return piece_a.astype(np.uint8), piece_b.astype(np.uint8)
|
| 148 |
+
|
| 149 |
+
height, width = union.shape[:2]
|
| 150 |
+
distance = signed_distance_to_line(line, height, width)
|
| 151 |
+
|
| 152 |
+
# Orient by the medians rather than the means: a long thin annexed strip
|
| 153 |
+
# drags a mean across the line, and the whole point is that the strip is on
|
| 154 |
+
# the wrong side to begin with.
|
| 155 |
+
median_a = float(np.median(distance[a_mask])) if a_mask.any() else 0.0
|
| 156 |
+
median_b = float(np.median(distance[b_mask])) if b_mask.any() else 0.0
|
| 157 |
+
if median_a == median_b:
|
| 158 |
+
return piece_a.astype(np.uint8), piece_b.astype(np.uint8)
|
| 159 |
+
a_is_negative = median_a < median_b
|
| 160 |
+
|
| 161 |
+
a_side = distance < 0 if a_is_negative else distance >= 0
|
| 162 |
+
new_a = (union & a_side).astype(np.uint8)
|
| 163 |
+
new_b = (union & ~a_side).astype(np.uint8)
|
| 164 |
+
return new_a, new_b
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def straighten_piece_seams(
|
| 168 |
+
pieces: list[tuple[int, np.ndarray]],
|
| 169 |
+
planes: list[dict],
|
| 170 |
+
intrinsics: np.ndarray | None,
|
| 171 |
+
min_area: int,
|
| 172 |
+
) -> list[np.ndarray]:
|
| 173 |
+
"""Re-cut every seam between touching pieces onto its planes' shared corner.
|
| 174 |
+
|
| 175 |
+
`pieces` pairs each mask with the index of the plane it was assigned to.
|
| 176 |
+
Pieces that do not touch have no seam to straighten and are left alone, as
|
| 177 |
+
are pairs whose planes do not meet in front of the camera.
|
| 178 |
+
|
| 179 |
+
A straightened pair is only accepted when both sides survive `min_area`.
|
| 180 |
+
That is the guard against a line that misses the union entirely: rather
|
| 181 |
+
than hand one piece everything and delete the other, the original split is
|
| 182 |
+
kept. Falling back to a slightly ragged seam is always better than losing a
|
| 183 |
+
wall.
|
| 184 |
+
"""
|
| 185 |
+
import cv2
|
| 186 |
+
|
| 187 |
+
masks = [mask.astype(np.uint8, copy=True) for _, mask in pieces]
|
| 188 |
+
if intrinsics is None or len(masks) < 2:
|
| 189 |
+
return masks
|
| 190 |
+
|
| 191 |
+
height, width = masks[0].shape[:2]
|
| 192 |
+
touch_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
| 193 |
+
|
| 194 |
+
for first in range(len(masks)):
|
| 195 |
+
for second in range(first + 1, len(masks)):
|
| 196 |
+
mask_a, mask_b = masks[first], masks[second]
|
| 197 |
+
if not mask_a.any() or not mask_b.any():
|
| 198 |
+
continue
|
| 199 |
+
# Only a seam that exists is worth moving.
|
| 200 |
+
if not (cv2.dilate(mask_a, touch_kernel).astype(bool) & mask_b.astype(bool)).any():
|
| 201 |
+
continue
|
| 202 |
+
|
| 203 |
+
plane_a = planes[pieces[first][0]]
|
| 204 |
+
plane_b = planes[pieces[second][0]]
|
| 205 |
+
line = corner_line_in_image(plane_a, plane_b, intrinsics, height, width)
|
| 206 |
+
if line is None:
|
| 207 |
+
continue
|
| 208 |
+
|
| 209 |
+
new_a, new_b = split_pieces_on_corner_line(mask_a, mask_b, line)
|
| 210 |
+
if int(new_a.sum()) < min_area or int(new_b.sum()) < min_area:
|
| 211 |
+
continue # the line missed the union; keep the old split
|
| 212 |
+
masks[first], masks[second] = new_a, new_b
|
| 213 |
+
|
| 214 |
+
return masks
|
services/wall/mask.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Wall surface mask refinement — the wall counterpart to services/floor/mask.py.
|
| 2 |
+
|
| 3 |
+
Background
|
| 4 |
+
----------
|
| 5 |
+
Wall masks used to be authored entirely by 3D plane assignment inside
|
| 6 |
+
``wall_surface_components``: a pixel survived only if its back-projected normal
|
| 7 |
+
matched a fitted wall plane. Low-texture surfaces (marble, painted plaster)
|
| 8 |
+
produce smooth, ambiguous depth, so large organic patches were silently
|
| 9 |
+
discarded and nothing put them back. The result looked like torn paper.
|
| 10 |
+
|
| 11 |
+
The floor never had this problem, because for floors the geometry check is
|
| 12 |
+
*advisory*::
|
| 13 |
+
|
| 14 |
+
surface = (surface & depth_keep).astype(np.uint8)
|
| 15 |
+
surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1)
|
| 16 |
+
|
| 17 |
+
Geometry is allowed to refine the floor's edges but never to delete a pixel
|
| 18 |
+
segmentation was confident about. This module gives walls the same guarantee:
|
| 19 |
+
fill the holes back in, clamp to what segmentation actually called wall, and
|
| 20 |
+
never grow past a structural boundary.
|
| 21 |
+
|
| 22 |
+
Barriers vs reclaimables
|
| 23 |
+
------------------------
|
| 24 |
+
Not every object touching a wall should be treated the same way:
|
| 25 |
+
|
| 26 |
+
* **Barrier** — ceiling, floor, sky, doors, windows. These are where the wall
|
| 27 |
+
*ends*. Growing into them is the "tile bleeding onto the ceiling" bug, so the
|
| 28 |
+
mask must never cross them.
|
| 29 |
+
* **Reclaimable** — mirrors, paintings, televisions, curtains, and furniture
|
| 30 |
+
standing in front of the wall. These sit *on* an otherwise continuous wall.
|
| 31 |
+
The tile belongs behind them, and they are re-drawn on top via the segment's
|
| 32 |
+
occlusion mask (the same trick the floor uses for furniture). Cutting them
|
| 33 |
+
out of the mask instead is what produced the ragged holes around mirrors.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import cv2
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
from services.floor.edge_coverage import improve_surface_edge_coverage, scaled_odd_kernel_size
|
| 42 |
+
from services.image.edge_snap import snap_mask_to_image_edges
|
| 43 |
+
from state import class_ids
|
| 44 |
+
from utils import seg_class_mask
|
| 45 |
+
|
| 46 |
+
# Where a wall stops. The mask may never expand across these.
|
| 47 |
+
#
|
| 48 |
+
# Only barriers are enumerated. Everything else counts as reclaimable — see
|
| 49 |
+
# wall_region_masks for why listing the reclaimables instead does not work.
|
| 50 |
+
WALL_BARRIER_CLASSES = {"ceiling", "sky", "building", "floor", "door", "window"}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def contour_fill(mask: np.ndarray) -> np.ndarray:
|
| 54 |
+
"""Fill interior holes by re-drawing external contours solid.
|
| 55 |
+
|
| 56 |
+
This is the single most important repair: the patches dropped by plane
|
| 57 |
+
assignment are enclosed by surviving wall pixels, so refilling each external
|
| 58 |
+
contour restores them without touching the component's true outline.
|
| 59 |
+
"""
|
| 60 |
+
mask_u8 = mask.astype(np.uint8, copy=False)
|
| 61 |
+
if not mask_u8.any():
|
| 62 |
+
return mask_u8
|
| 63 |
+
contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 64 |
+
if not contours:
|
| 65 |
+
return mask_u8
|
| 66 |
+
filled = np.zeros(mask_u8.shape[:2], dtype=np.uint8)
|
| 67 |
+
cv2.drawContours(filled, contours, -1, 1, cv2.FILLED)
|
| 68 |
+
return filled
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def convex_hull_mask(mask: np.ndarray) -> np.ndarray:
|
| 72 |
+
"""Solid convex hull of a mask.
|
| 73 |
+
|
| 74 |
+
Plane assignment erodes a component's *outer* boundary as well as punching
|
| 75 |
+
interior holes, and contour_fill cannot repair an open edge. The hull spans
|
| 76 |
+
the region the wall would occupy if the boundary were intact; clipping it to
|
| 77 |
+
pixels segmentation actually called wall turns it into a safe repair.
|
| 78 |
+
"""
|
| 79 |
+
mask_u8 = mask.astype(np.uint8, copy=False)
|
| 80 |
+
if not mask_u8.any():
|
| 81 |
+
return mask_u8
|
| 82 |
+
points = cv2.findNonZero(mask_u8)
|
| 83 |
+
if points is None or len(points) < 3:
|
| 84 |
+
return mask_u8
|
| 85 |
+
hull = cv2.convexHull(points).reshape(-1, 2).astype(np.int32)
|
| 86 |
+
filled = np.zeros(mask_u8.shape[:2], dtype=np.uint8)
|
| 87 |
+
cv2.fillConvexPoly(filled, hull, 1)
|
| 88 |
+
return filled
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def extend_vertically_within(mask: np.ndarray, allowed: np.ndarray, reach_px: int) -> np.ndarray:
|
| 92 |
+
"""Grow a mask up and down, but only across pixels that are `allowed`.
|
| 93 |
+
|
| 94 |
+
A geodesic dilation restricted to the vertical axis. Walls run continuously
|
| 95 |
+
from floor to ceiling, so extending a component vertically until it runs out
|
| 96 |
+
of wall recovers the ceiling and skirting joins that plane assignment eats
|
| 97 |
+
away — the ragged top edge that convex-hull repair cannot reach, because the
|
| 98 |
+
hull can never extend above the highest surviving pixel.
|
| 99 |
+
|
| 100 |
+
Vertical-only is what makes this safe: two walls meeting at a corner are
|
| 101 |
+
side by side, so this can never merge them. `allowed` excludes barriers, so
|
| 102 |
+
growth halts at the ceiling rather than bleeding onto it.
|
| 103 |
+
"""
|
| 104 |
+
step = 9 # each pass reaches (step // 2) px further in both directions
|
| 105 |
+
kernel = np.ones((step, 1), dtype=np.uint8)
|
| 106 |
+
seed = mask.astype(np.uint8, copy=True)
|
| 107 |
+
grown = seed.copy()
|
| 108 |
+
allowed_u8 = allowed.astype(np.uint8)
|
| 109 |
+
for _ in range(max(1, int(round(reach_px / (step // 2))))):
|
| 110 |
+
previous = grown
|
| 111 |
+
# Union the seed back in every pass. Intersecting alone would delete any
|
| 112 |
+
# part of the seed lying outside the growth medium — which silently threw
|
| 113 |
+
# away mirrors and other reclaimed objects, since those are not wall.
|
| 114 |
+
grown = cv2.bitwise_or(
|
| 115 |
+
cv2.bitwise_and(cv2.dilate(grown, kernel), allowed_u8),
|
| 116 |
+
seed,
|
| 117 |
+
)
|
| 118 |
+
if np.array_equal(grown, previous):
|
| 119 |
+
break
|
| 120 |
+
return grown
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def keep_connected_to(mask: np.ndarray, seed: np.ndarray) -> np.ndarray:
|
| 124 |
+
"""Drop islands of `mask` that do not touch `seed`.
|
| 125 |
+
|
| 126 |
+
Hull repair spans a convex quad, so where a wall wraps around a doorway the
|
| 127 |
+
hull reaches across the opening and picks up whatever wall lies beyond it —
|
| 128 |
+
a different wall, at a different depth, needing its own transform. Requiring
|
| 129 |
+
contiguity with the original component keeps the repair local.
|
| 130 |
+
"""
|
| 131 |
+
mask_u8 = mask.astype(np.uint8, copy=False)
|
| 132 |
+
seed_bool = seed.astype(bool)
|
| 133 |
+
if not mask_u8.any() or not seed_bool.any():
|
| 134 |
+
return mask_u8
|
| 135 |
+
count, labels = cv2.connectedComponents(mask_u8, connectivity=8)
|
| 136 |
+
if count <= 2:
|
| 137 |
+
return mask_u8
|
| 138 |
+
keep = np.unique(labels[seed_bool])
|
| 139 |
+
keep = keep[keep > 0]
|
| 140 |
+
if keep.size == 0:
|
| 141 |
+
return mask_u8
|
| 142 |
+
return np.isin(labels, keep).astype(np.uint8)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def wall_region_masks(seg_map: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 146 |
+
"""Split the scene into (raw wall class, barriers, reclaimable objects).
|
| 147 |
+
|
| 148 |
+
Reclaimable is defined by exclusion: anything that is neither wall nor a
|
| 149 |
+
barrier. Enumerating the reclaimable classes instead looks tidier but loses
|
| 150 |
+
quietly -- a wall-mounted television is often labelled `screen`, which was
|
| 151 |
+
absent from OCCLUDER_CLASSES, so it fell into neither set and got clamped
|
| 152 |
+
away, punching a TV-shaped hole through the middle of the wall.
|
| 153 |
+
|
| 154 |
+
Defining it by exclusion cannot miss an object, and it is safe because
|
| 155 |
+
`allowed` only ever preserves pixels that hole filling has already reached:
|
| 156 |
+
hull repair and vertical growth are both clipped to the wall class itself,
|
| 157 |
+
so nothing can run away into the room.
|
| 158 |
+
"""
|
| 159 |
+
wall_raw = seg_class_mask(seg_map, class_ids({"wall"}))
|
| 160 |
+
barrier = seg_class_mask(seg_map, class_ids(WALL_BARRIER_CLASSES))
|
| 161 |
+
reclaimable = np.ones_like(wall_raw)
|
| 162 |
+
reclaimable[barrier > 0] = 0 # barriers win, so the mask cannot leak through a door
|
| 163 |
+
reclaimable[wall_raw > 0] = 0
|
| 164 |
+
return wall_raw, barrier, reclaimable
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def refine_wall_component_mask(
|
| 168 |
+
component_mask: np.ndarray,
|
| 169 |
+
wall_class_mask: np.ndarray,
|
| 170 |
+
reclaimable_mask: np.ndarray,
|
| 171 |
+
barrier_mask: np.ndarray,
|
| 172 |
+
image_rgb: np.ndarray | None = None,
|
| 173 |
+
) -> tuple[np.ndarray, dict]:
|
| 174 |
+
"""Repair one wall component: fill holes, close gaps, clamp to the wall.
|
| 175 |
+
|
| 176 |
+
Parameters
|
| 177 |
+
----------
|
| 178 |
+
component_mask
|
| 179 |
+
Raw component straight out of plane assignment / connected components.
|
| 180 |
+
wall_class_mask
|
| 181 |
+
Pixels segmentation called wall. This is the medium vertical growth
|
| 182 |
+
travels through — deliberately *not* the reclaimables, because a sofa or
|
| 183 |
+
cabinet standing against the wall reaches the floor, and growing through
|
| 184 |
+
it would let one wall swallow half the room.
|
| 185 |
+
reclaimable_mask
|
| 186 |
+
Objects mounted on / standing in front of the wall. The component may
|
| 187 |
+
occupy these (tile is drawn behind them) but only where hole filling
|
| 188 |
+
reaches them, never by unbounded growth.
|
| 189 |
+
barrier_mask
|
| 190 |
+
Pixels the component may never occupy (ceiling, floor, doors, windows).
|
| 191 |
+
Also passed to the edge-repair dilation so it cannot bleed.
|
| 192 |
+
"""
|
| 193 |
+
wall_only = wall_class_mask.astype(bool)
|
| 194 |
+
allowed = wall_only | reclaimable_mask.astype(bool)
|
| 195 |
+
barrier = barrier_mask.astype(bool)
|
| 196 |
+
seed = component_mask.astype(bool)
|
| 197 |
+
before = int(component_mask.sum())
|
| 198 |
+
|
| 199 |
+
h, w = component_mask.shape[:2]
|
| 200 |
+
close_size = scaled_odd_kernel_size(h, w, 0.008, minimum=3)
|
| 201 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size))
|
| 202 |
+
|
| 203 |
+
# Bridge hairline cracks first so contour fill sees one region, not many.
|
| 204 |
+
refined = cv2.morphologyEx(component_mask.astype(np.uint8), cv2.MORPH_CLOSE, kernel)
|
| 205 |
+
refined = contour_fill(refined)
|
| 206 |
+
refined = _clamp(refined, allowed, barrier)
|
| 207 |
+
|
| 208 |
+
# Recover the eroded outer boundary. contour_fill only closes holes that are
|
| 209 |
+
# enclosed by surviving pixels; where plane assignment ate into the edge of
|
| 210 |
+
# the wall (typically the ceiling join and around door frames) the gap is
|
| 211 |
+
# open, so filling contours cannot reach it. The convex hull spans the intact
|
| 212 |
+
# wall.
|
| 213 |
+
#
|
| 214 |
+
# Clipped to wall pixels only, never to `allowed`. The hull of a wall spans a
|
| 215 |
+
# large quad, and intersecting that with furniture-inclusive `allowed` swept
|
| 216 |
+
# in the TV cabinet, speakers and coffee table — 265k px of wall became 612k.
|
| 217 |
+
# Objects are reclaimed by contour_fill above, which requires them to be
|
| 218 |
+
# genuinely enclosed by wall, and that is the conservative behaviour we want.
|
| 219 |
+
hull = convex_hull_mask(refined)
|
| 220 |
+
refined = ((refined.astype(bool)) | (hull.astype(bool) & wall_only)).astype(np.uint8)
|
| 221 |
+
refined = _clamp(refined, allowed, barrier)
|
| 222 |
+
refined = keep_connected_to(refined, seed)
|
| 223 |
+
|
| 224 |
+
# The hull cannot reach above the highest surviving pixel, so the ceiling and
|
| 225 |
+
# skirting joins are still short. Grow vertically to walk the rest of the
|
| 226 |
+
# way — through wall pixels only, and only far enough to cross a ragged
|
| 227 |
+
# edge. An earlier version grew through `allowed` with a 25% reach and one
|
| 228 |
+
# wall swallowed the room: it travelled down through the TV cabinet, absorbed
|
| 229 |
+
# the neighbouring wall, and confidence fell from 0.91 to 0.70.
|
| 230 |
+
reach = max(8, int(round(min(h, w) * 0.08)))
|
| 231 |
+
refined = extend_vertically_within(refined, wall_only, reach)
|
| 232 |
+
refined = _clamp(refined, allowed, barrier)
|
| 233 |
+
refined = keep_connected_to(refined, seed)
|
| 234 |
+
|
| 235 |
+
refined, edge_metadata = improve_surface_edge_coverage(refined, barrier)
|
| 236 |
+
refined = _clamp(refined, allowed, barrier)
|
| 237 |
+
refined = keep_connected_to(refined, seed)
|
| 238 |
+
|
| 239 |
+
# Everything above is ellipse morphology, which scallops a straight
|
| 240 |
+
# architectural line. Snap the boundary back onto the edge the photo
|
| 241 |
+
# actually shows, then re-apply the semantic clamp -- the filter knows about
|
| 242 |
+
# image edges, not about classes, so on its own it would happily drift a few
|
| 243 |
+
# pixels onto the ceiling.
|
| 244 |
+
snapped = snap_mask_to_image_edges(refined, image_rgb)
|
| 245 |
+
snapped = _clamp(snapped, allowed, barrier)
|
| 246 |
+
snapped = keep_connected_to(snapped, seed)
|
| 247 |
+
if snapped.any():
|
| 248 |
+
refined = snapped
|
| 249 |
+
|
| 250 |
+
after = int(refined.sum())
|
| 251 |
+
metadata = {
|
| 252 |
+
f"wallEdge{key[0].upper()}{key[1:]}": value
|
| 253 |
+
for key, value in edge_metadata.items()
|
| 254 |
+
}
|
| 255 |
+
metadata.update({
|
| 256 |
+
"wallMaskPixelsBefore": before,
|
| 257 |
+
"wallMaskPixelsAfter": after,
|
| 258 |
+
"wallMaskPixelsRecovered": after - before,
|
| 259 |
+
})
|
| 260 |
+
return refined, metadata
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _clamp(mask: np.ndarray, allowed: np.ndarray, barrier: np.ndarray) -> np.ndarray:
|
| 264 |
+
clamped = (mask.astype(bool) & allowed).astype(np.uint8)
|
| 265 |
+
clamped[barrier] = 0
|
| 266 |
+
return clamped
|
services/wall/plane.py
CHANGED
|
@@ -16,14 +16,29 @@ from services.geometry.plane_fitting import (
|
|
| 16 |
fit_metric_floor_transform,
|
| 17 |
)
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
"""Return a stable image-space homography for a semantic wall mask.
|
| 22 |
|
| 23 |
Walls do not currently have metric depth fitting, so use the visible wall
|
| 24 |
contour as the source quad and its bounding rectangle as the planar target.
|
| 25 |
This preserves perspective convergence while keeping physical tile sizes
|
| 26 |
deterministic until wall-specific depth calibration is available.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
"""
|
| 28 |
ys, xs = np.where(mask > 0)
|
| 29 |
if len(xs) < 1000:
|
|
@@ -63,6 +78,23 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
|
|
| 63 |
if x2 - x1 < 20 or y2 - y1 < 20:
|
| 64 |
return None, None
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
|
| 67 |
homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
|
| 68 |
metric_geometry = None
|
|
@@ -77,6 +109,7 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
|
|
| 77 |
geometry.get("intrinsics"),
|
| 78 |
geometry.get("provider", GeometryProvider.METRIC_DEPTH),
|
| 79 |
surface_kind="wall",
|
|
|
|
| 80 |
)
|
| 81 |
if metric_geometry is None:
|
| 82 |
metric_geometry = estimate_metric_floor_transform(
|
|
@@ -85,6 +118,7 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
|
|
| 85 |
geometry.get("provider", GeometryProvider.DEPTH_ANYTHING),
|
| 86 |
geometry.get("intrinsics"),
|
| 87 |
surface_kind="wall",
|
|
|
|
| 88 |
)
|
| 89 |
|
| 90 |
plane = {
|
|
@@ -98,8 +132,10 @@ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
|
|
| 98 |
"floorTransform": None,
|
| 99 |
"surfaceTransform": None,
|
| 100 |
"surfaceType": SurfaceType.WALL,
|
| 101 |
-
"surfaceWidthMeters": max(
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
"metersPerUnit": None,
|
| 104 |
"cameraIntrinsics": None,
|
| 105 |
"camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
|
|
|
|
| 16 |
fit_metric_floor_transform,
|
| 17 |
)
|
| 18 |
|
| 19 |
+
# Assumed floor-to-ceiling height, in metres, for a wall with no depth to
|
| 20 |
+
# measure. Only the wall's *aspect* can be recovered from a single view without
|
| 21 |
+
# metric geometry, so this sets the absolute scale; the metric fit overrides
|
| 22 |
+
# both extents whenever it succeeds.
|
| 23 |
+
WALL_HEIGHT_PRIOR_METERS = 2.4
|
| 24 |
|
| 25 |
+
|
| 26 |
+
def estimate_wall_plane(
|
| 27 |
+
mask: np.ndarray,
|
| 28 |
+
geometry: dict | None = None,
|
| 29 |
+
vertical_ref: np.ndarray | None = None,
|
| 30 |
+
):
|
| 31 |
"""Return a stable image-space homography for a semantic wall mask.
|
| 32 |
|
| 33 |
Walls do not currently have metric depth fitting, so use the visible wall
|
| 34 |
contour as the source quad and its bounding rectangle as the planar target.
|
| 35 |
This preserves perspective convergence while keeping physical tile sizes
|
| 36 |
deterministic until wall-specific depth calibration is available.
|
| 37 |
+
|
| 38 |
+
`vertical_ref` is which direction gravity-up points, in the same frame as
|
| 39 |
+
the geometry's points. Geometry providers work in camera coordinates, so
|
| 40 |
+
without it the metric fit assumes camera +Y is up and rotates the wall's
|
| 41 |
+
tile grid by the camera's roll. Callers should pass the floor normal.
|
| 42 |
"""
|
| 43 |
ys, xs = np.where(mask > 0)
|
| 44 |
if len(xs) < 1000:
|
|
|
|
| 78 |
if x2 - x1 < 20 or y2 - y1 < 20:
|
| 79 |
return None, None
|
| 80 |
|
| 81 |
+
# Measure the wall along its own edges, averaging opposite pairs.
|
| 82 |
+
#
|
| 83 |
+
# The axis-aligned bounding box was standing in for these, which overstates
|
| 84 |
+
# a tilted wall: a slanted mask falls through to `minAreaRect`, whose
|
| 85 |
+
# corners can sit well outside the image, and the box around that rotated
|
| 86 |
+
# rect is far wider than the wall. Edge lengths are unaffected by the tilt
|
| 87 |
+
# and by corners leaving the frame, and for an axis-aligned quad they are
|
| 88 |
+
# exactly the box dimensions, so only genuinely tilted walls move.
|
| 89 |
+
quad_width = 0.5 * (
|
| 90 |
+
float(np.linalg.norm(ordered[1] - ordered[0]))
|
| 91 |
+
+ float(np.linalg.norm(ordered[2] - ordered[3]))
|
| 92 |
+
)
|
| 93 |
+
quad_height = 0.5 * (
|
| 94 |
+
float(np.linalg.norm(ordered[3] - ordered[0]))
|
| 95 |
+
+ float(np.linalg.norm(ordered[2] - ordered[1]))
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
|
| 99 |
homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
|
| 100 |
metric_geometry = None
|
|
|
|
| 109 |
geometry.get("intrinsics"),
|
| 110 |
geometry.get("provider", GeometryProvider.METRIC_DEPTH),
|
| 111 |
surface_kind="wall",
|
| 112 |
+
vertical_ref=vertical_ref,
|
| 113 |
)
|
| 114 |
if metric_geometry is None:
|
| 115 |
metric_geometry = estimate_metric_floor_transform(
|
|
|
|
| 118 |
geometry.get("provider", GeometryProvider.DEPTH_ANYTHING),
|
| 119 |
geometry.get("intrinsics"),
|
| 120 |
surface_kind="wall",
|
| 121 |
+
vertical_ref=vertical_ref,
|
| 122 |
)
|
| 123 |
|
| 124 |
plane = {
|
|
|
|
| 132 |
"floorTransform": None,
|
| 133 |
"surfaceTransform": None,
|
| 134 |
"surfaceType": SurfaceType.WALL,
|
| 135 |
+
"surfaceWidthMeters": max(
|
| 136 |
+
0.5, WALL_HEIGHT_PRIOR_METERS * quad_width / max(quad_height, 1.0)
|
| 137 |
+
),
|
| 138 |
+
"surfaceHeightMeters": WALL_HEIGHT_PRIOR_METERS,
|
| 139 |
"metersPerUnit": None,
|
| 140 |
"cameraIntrinsics": None,
|
| 141 |
"camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
|
test_wall_corner_split.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Where two wall planes meet, the seam must land on the architectural corner.
|
| 2 |
+
|
| 3 |
+
python test_wall_corner_split.py
|
| 4 |
+
|
| 5 |
+
Background
|
| 6 |
+
----------
|
| 7 |
+
Two adjacent walls used to be separated by `assign_points_to_surface_planes`,
|
| 8 |
+
which scores every pixel against every plane individually. Right at a corner
|
| 9 |
+
that score cannot discriminate: the distance term goes to zero for *both*
|
| 10 |
+
planes, so the decision falls entirely to the per-pixel depth normal -- and a
|
| 11 |
+
learned depth model rounds a corner, so for a few tens of pixels either side
|
| 12 |
+
the normal is a blend of the two walls.
|
| 13 |
+
|
| 14 |
+
Measured on a real bathroom photo (job 03d0c9df), that put the back wall's left
|
| 15 |
+
edge at column 291.5 when the corner is at 262, wandering between 277 and 337.
|
| 16 |
+
The visible result was a 25 px strip of untiled wall down the inside of the
|
| 17 |
+
corner with a torn edge.
|
| 18 |
+
|
| 19 |
+
Two planes intersect along a 3D line, and a pinhole camera projects a 3D line
|
| 20 |
+
to a straight line. That projection *is* the corner, it is computed from the
|
| 21 |
+
two global plane fits rather than from per-pixel normals, and it is straight by
|
| 22 |
+
construction. The numbers below are the real ones from that job.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import pathlib
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
from services.wall.corner import corner_line_in_image, split_pieces_on_corner_line
|
| 35 |
+
|
| 36 |
+
H, W = 576, 768
|
| 37 |
+
FOCAL, CX, CY = 579.6456298828125, 384.0, 288.0
|
| 38 |
+
INTRINSICS = np.array([[FOCAL, 0.0, CX], [0.0, FOCAL, CY], [0.0, 0.0, 1.0]], dtype=np.float32)
|
| 39 |
+
|
| 40 |
+
# Verbatim from the job's bundle metadata.
|
| 41 |
+
LEFT_WALL = {
|
| 42 |
+
"normal": np.array([-0.9999967813491821, 0.0022450105752795935, 0.0012066650670021772]),
|
| 43 |
+
"origin": np.array([-1.1624844074249268, -0.23183509707450867, 2.5155556201934814]),
|
| 44 |
+
}
|
| 45 |
+
BACK_WALL = {
|
| 46 |
+
"normal": np.array([-0.007814906537532806, 0.0010164726991206408, 0.999968945980072]),
|
| 47 |
+
"origin": np.array([0.07378386706113815, -0.7956849932670593, 5.718906402587891]),
|
| 48 |
+
}
|
| 49 |
+
TRUE_CORNER_COLUMN = 262 # measured from the photograph's vertical gradient
|
| 50 |
+
WRONG_BOUNDARY = 292 # what per-pixel plane assignment actually produced
|
| 51 |
+
|
| 52 |
+
failures: list[str] = []
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def check(label: str, condition: bool, detail: str = "") -> None:
|
| 56 |
+
if condition:
|
| 57 |
+
print(f" PASS {label}")
|
| 58 |
+
else:
|
| 59 |
+
failures.append(label)
|
| 60 |
+
print(f" FAIL {label}" + (f" ({detail})" if detail else ""))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def left_edge_of(mask: np.ndarray, rows: range) -> np.ndarray:
|
| 64 |
+
return np.array(
|
| 65 |
+
[np.flatnonzero(mask[y])[0] if mask[y].any() else np.nan for y in rows],
|
| 66 |
+
dtype=float,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def main() -> int:
|
| 71 |
+
print("corner line from two fitted planes")
|
| 72 |
+
line = corner_line_in_image(LEFT_WALL, BACK_WALL, INTRINSICS, H, W)
|
| 73 |
+
check("two perpendicular walls produce a corner line", line is not None)
|
| 74 |
+
if line is None:
|
| 75 |
+
print("\n1 FAILED: no line")
|
| 76 |
+
return 1
|
| 77 |
+
|
| 78 |
+
a, b, c = line
|
| 79 |
+
columns = [(-c - b * y) / a for y in (0, H // 2, H - 1)] if abs(a) > 1e-9 else []
|
| 80 |
+
check(
|
| 81 |
+
"the line lands on the real corner, not the biased boundary",
|
| 82 |
+
all(abs(col - TRUE_CORNER_COLUMN) <= 8 for col in columns),
|
| 83 |
+
f"columns={[round(v, 1) for v in columns]} true={TRUE_CORNER_COLUMN}",
|
| 84 |
+
)
|
| 85 |
+
check(
|
| 86 |
+
"the line is vertical, so it cannot wander",
|
| 87 |
+
max(columns) - min(columns) <= 2.0,
|
| 88 |
+
f"spread={max(columns) - min(columns):.2f}px",
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
print("\nre-cutting two pieces along it")
|
| 92 |
+
# The failure as it actually shipped: the left wall has annexed a strip of
|
| 93 |
+
# the back wall, and the seam between them is ragged rather than straight.
|
| 94 |
+
rng = np.random.default_rng(11)
|
| 95 |
+
left = np.zeros((H, W), np.uint8)
|
| 96 |
+
back = np.zeros((H, W), np.uint8)
|
| 97 |
+
for y in range(H):
|
| 98 |
+
seam = WRONG_BOUNDARY + int(rng.integers(-14, 46)) # biased *and* ragged
|
| 99 |
+
left[y, 40:seam] = 1
|
| 100 |
+
back[y, seam:545] = 1
|
| 101 |
+
|
| 102 |
+
before = left_edge_of(back, range(130, 390))
|
| 103 |
+
fixed_left, fixed_back = split_pieces_on_corner_line(left, back, line)
|
| 104 |
+
after = left_edge_of(fixed_back, range(130, 390))
|
| 105 |
+
|
| 106 |
+
print(f" before: mean={np.nanmean(before):6.1f} std={np.nanstd(before):5.1f}")
|
| 107 |
+
print(f" after : mean={np.nanmean(after):6.1f} std={np.nanstd(after):5.1f}")
|
| 108 |
+
|
| 109 |
+
check(
|
| 110 |
+
"the seam moves onto the corner",
|
| 111 |
+
abs(np.nanmean(after) - TRUE_CORNER_COLUMN) <= 8,
|
| 112 |
+
f"mean={np.nanmean(after):.1f} true={TRUE_CORNER_COLUMN}",
|
| 113 |
+
)
|
| 114 |
+
check(
|
| 115 |
+
"the seam stops wandering",
|
| 116 |
+
np.nanstd(after) <= 1.5,
|
| 117 |
+
f"std={np.nanstd(after):.2f} (was {np.nanstd(before):.2f})",
|
| 118 |
+
)
|
| 119 |
+
check(
|
| 120 |
+
"the back wall reclaims the annexed strip",
|
| 121 |
+
int(fixed_back.sum()) > int(back.sum()),
|
| 122 |
+
f"{int(back.sum())} -> {int(fixed_back.sum())}",
|
| 123 |
+
)
|
| 124 |
+
check(
|
| 125 |
+
"the two pieces stay disjoint",
|
| 126 |
+
not (fixed_left.astype(bool) & fixed_back.astype(bool)).any(),
|
| 127 |
+
)
|
| 128 |
+
check(
|
| 129 |
+
"no pixel is lost between them",
|
| 130 |
+
int(fixed_left.sum()) + int(fixed_back.sum())
|
| 131 |
+
== int(left.astype(bool).sum()) + int(back.astype(bool).sum()),
|
| 132 |
+
f"{int(fixed_left.sum()) + int(fixed_back.sum())} vs "
|
| 133 |
+
f"{int(left.sum()) + int(back.sum())}",
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
print("\nrefusals")
|
| 137 |
+
parallel = {"normal": np.array([0.0, 0.0, 1.0]), "origin": np.array([0.0, 0.0, 8.0])}
|
| 138 |
+
check(
|
| 139 |
+
"parallel planes have no corner",
|
| 140 |
+
corner_line_in_image(BACK_WALL, parallel, INTRINSICS, H, W) is None,
|
| 141 |
+
)
|
| 142 |
+
behind = {"normal": np.array([1.0, 0.0, 0.0]), "origin": np.array([0.0, 0.0, -4.0])}
|
| 143 |
+
check(
|
| 144 |
+
"a corner behind the camera is refused",
|
| 145 |
+
corner_line_in_image(behind, {"normal": np.array([0.0, 0.0, 1.0]),
|
| 146 |
+
"origin": np.array([0.0, 0.0, -4.0])},
|
| 147 |
+
INTRINSICS, H, W) is None,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
print()
|
| 151 |
+
if failures:
|
| 152 |
+
print(f"{len(failures)} FAILED: {', '.join(failures)}")
|
| 153 |
+
return 1
|
| 154 |
+
print("All checks passed.")
|
| 155 |
+
return 0
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if __name__ == "__main__":
|
| 159 |
+
sys.exit(main())
|
test_wall_plane_basis.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression checks for the wall plane's tile basis.
|
| 2 |
+
|
| 3 |
+
A wall's (u, v) basis decides which way its tile grid runs. `v` is meant to be
|
| 4 |
+
world-up projected onto the wall, so tiles run *up* the wall.
|
| 5 |
+
|
| 6 |
+
Geometry providers return points in *camera* coordinates, so camera +Y is
|
| 7 |
+
camera-up, not gravity-up. Assuming +Y is up therefore rotates every wall's
|
| 8 |
+
tile grid by the camera's roll -- the tilted grid users see on photos that were
|
| 9 |
+
not shot perfectly level. `plane_basis` already takes a `vertical_ref` for this
|
| 10 |
+
and the per-pixel UV path already passes it; the plane fit did not, so the
|
| 11 |
+
plane basis stayed camera-aligned.
|
| 12 |
+
|
| 13 |
+
The floor is unaffected by design: a floor's `u` comes from a horizontal
|
| 14 |
+
reference, so `vertical_ref` must not perturb it.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from services.geometry.plane_fitting import fit_metric_floor_transform
|
| 22 |
+
from services.pipeline.bundle_assembly import build_wall_segment
|
| 23 |
+
from services.wall.plane import estimate_wall_plane
|
| 24 |
+
|
| 25 |
+
HEIGHT, WIDTH = 200, 260
|
| 26 |
+
FX = FY = 300.0
|
| 27 |
+
CX, CY = 130.0, 100.0
|
| 28 |
+
WALL_DISTANCE = 3.0
|
| 29 |
+
CAMERA_ROLL_DEGREES = 20.0
|
| 30 |
+
|
| 31 |
+
# Gravity-up in camera coordinates for a camera rolled about its optical axis.
|
| 32 |
+
# It stays in the z=0 plane, so for a fronto-parallel wall it needs no
|
| 33 |
+
# projection and `v` should come back equal to it.
|
| 34 |
+
ROLL_RADIANS = np.deg2rad(CAMERA_ROLL_DEGREES)
|
| 35 |
+
TRUE_UP = np.array([np.sin(ROLL_RADIANS), np.cos(ROLL_RADIANS), 0.0], dtype=np.float32)
|
| 36 |
+
CAMERA_UP = np.array([0.0, 1.0, 0.0], dtype=np.float32)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _wall_scene():
|
| 40 |
+
"""A planar, fronto-parallel wall filling most of the frame.
|
| 41 |
+
|
| 42 |
+
Returns (mask, geometry). Every masked pixel lies exactly on z=WALL_DISTANCE
|
| 43 |
+
so the fit is unambiguous and the test isolates the basis, not the RANSAC.
|
| 44 |
+
"""
|
| 45 |
+
rows, cols = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
|
| 46 |
+
points = np.stack(
|
| 47 |
+
(
|
| 48 |
+
(cols - CX) / FX * WALL_DISTANCE,
|
| 49 |
+
(rows - CY) / FY * WALL_DISTANCE,
|
| 50 |
+
np.full_like(cols, WALL_DISTANCE),
|
| 51 |
+
),
|
| 52 |
+
axis=2,
|
| 53 |
+
).astype(np.float32)
|
| 54 |
+
|
| 55 |
+
mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
|
| 56 |
+
mask[20:180, 20:WIDTH - 20] = 1
|
| 57 |
+
|
| 58 |
+
normals = np.zeros((HEIGHT, WIDTH, 3), dtype=np.float32)
|
| 59 |
+
normals[:, :, 2] = -1.0 # the wall faces the camera
|
| 60 |
+
|
| 61 |
+
geometry = {
|
| 62 |
+
"points": points,
|
| 63 |
+
"validMask": np.ones((HEIGHT, WIDTH), dtype=bool),
|
| 64 |
+
"normals": normals,
|
| 65 |
+
"intrinsics": None,
|
| 66 |
+
}
|
| 67 |
+
return mask, geometry
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _floor_scene():
|
| 71 |
+
"""A planar floor seen from a camera 1.5m above it."""
|
| 72 |
+
rows, cols = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
|
| 73 |
+
ray = np.stack(((cols - CX) / FX, (rows - CY) / FY, np.ones_like(cols)), axis=2)
|
| 74 |
+
ray_y = np.clip(ray[:, :, 1], 1e-3, None)
|
| 75 |
+
points = (ray * (1.5 / ray_y)[:, :, None]).astype(np.float32)
|
| 76 |
+
|
| 77 |
+
mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
|
| 78 |
+
mask[150:HEIGHT, 10:WIDTH - 10] = 1
|
| 79 |
+
|
| 80 |
+
normals = np.zeros((HEIGHT, WIDTH, 3), dtype=np.float32)
|
| 81 |
+
normals[:, :, 1] = -1.0
|
| 82 |
+
|
| 83 |
+
geometry = {
|
| 84 |
+
"points": points,
|
| 85 |
+
"validMask": np.ones((HEIGHT, WIDTH), dtype=bool),
|
| 86 |
+
"normals": normals,
|
| 87 |
+
"intrinsics": None,
|
| 88 |
+
}
|
| 89 |
+
return mask, geometry
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _axis(vector) -> np.ndarray:
|
| 93 |
+
"""Normalize an axis and fix its sign so antiparallel axes compare equal."""
|
| 94 |
+
axis = np.asarray(vector, dtype=np.float32)
|
| 95 |
+
axis = axis / max(float(np.linalg.norm(axis)), 1e-6)
|
| 96 |
+
return axis if float(axis @ CAMERA_UP) >= 0 else -axis
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class WallPlaneBasisTest(unittest.TestCase):
|
| 100 |
+
def test_wall_v_axis_follows_the_supplied_vertical(self):
|
| 101 |
+
"""The tile grid runs along gravity-up, not the camera's tilted up."""
|
| 102 |
+
mask, geometry = _wall_scene()
|
| 103 |
+
|
| 104 |
+
result = fit_metric_floor_transform(
|
| 105 |
+
mask,
|
| 106 |
+
geometry["points"],
|
| 107 |
+
geometry["validMask"],
|
| 108 |
+
geometry["normals"],
|
| 109 |
+
None,
|
| 110 |
+
surface_kind="wall",
|
| 111 |
+
vertical_ref=TRUE_UP,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
self.assertIsNotNone(result, "the wall fit rejected a perfectly planar wall")
|
| 115 |
+
v_axis = _axis(result["surfaceVAxis"])
|
| 116 |
+
np.testing.assert_allclose(v_axis, TRUE_UP, atol=1e-3)
|
| 117 |
+
|
| 118 |
+
def test_wall_v_axis_defaults_to_camera_up(self):
|
| 119 |
+
"""Without a reference there is nothing better than camera-up."""
|
| 120 |
+
mask, geometry = _wall_scene()
|
| 121 |
+
|
| 122 |
+
result = fit_metric_floor_transform(
|
| 123 |
+
mask,
|
| 124 |
+
geometry["points"],
|
| 125 |
+
geometry["validMask"],
|
| 126 |
+
geometry["normals"],
|
| 127 |
+
None,
|
| 128 |
+
surface_kind="wall",
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
self.assertIsNotNone(result)
|
| 132 |
+
np.testing.assert_allclose(_axis(result["surfaceVAxis"]), CAMERA_UP, atol=1e-3)
|
| 133 |
+
|
| 134 |
+
def test_estimate_wall_plane_forwards_the_vertical_reference(self):
|
| 135 |
+
"""The pipeline's entry point must thread the reference to the basis."""
|
| 136 |
+
mask, geometry = _wall_scene()
|
| 137 |
+
|
| 138 |
+
_, plane = estimate_wall_plane(mask, geometry, vertical_ref=TRUE_UP)
|
| 139 |
+
|
| 140 |
+
self.assertIsNotNone(plane)
|
| 141 |
+
self.assertIn(
|
| 142 |
+
"surfaceVAxis",
|
| 143 |
+
plane,
|
| 144 |
+
"the metric wall fit was rejected, so the basis was never reached",
|
| 145 |
+
)
|
| 146 |
+
np.testing.assert_allclose(_axis(plane["surfaceVAxis"]), TRUE_UP, atol=1e-3)
|
| 147 |
+
|
| 148 |
+
def test_build_wall_segment_passes_its_up_vector_to_the_plane(self):
|
| 149 |
+
"""The pipeline already knows true vertical; the plane must receive it.
|
| 150 |
+
|
| 151 |
+
`build_wall_segment` forwarded `up_vector` to the per-pixel UV mapping
|
| 152 |
+
but not to the plane fit, so the plane's basis -- which is what the
|
| 153 |
+
renderer falls back to, and where the reported surface extents come
|
| 154 |
+
from -- stayed camera-aligned.
|
| 155 |
+
"""
|
| 156 |
+
mask, geometry = _wall_scene()
|
| 157 |
+
|
| 158 |
+
segment = build_wall_segment(
|
| 159 |
+
0,
|
| 160 |
+
mask,
|
| 161 |
+
np.zeros((HEIGHT, WIDTH), dtype=np.uint8),
|
| 162 |
+
geometry,
|
| 163 |
+
np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8),
|
| 164 |
+
[None],
|
| 165 |
+
{"segmentation": {"name": "test-segmenter"}},
|
| 166 |
+
precomputed_lighting={},
|
| 167 |
+
up_vector=TRUE_UP,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
self.assertIsNotNone(segment, "the wall segment builder rejected a clean wall")
|
| 171 |
+
plane = segment["plane"]
|
| 172 |
+
self.assertIn(
|
| 173 |
+
"surfaceVAxis",
|
| 174 |
+
plane,
|
| 175 |
+
"the metric wall fit was rejected, so the basis was never reached",
|
| 176 |
+
)
|
| 177 |
+
np.testing.assert_allclose(_axis(plane["surfaceVAxis"]), TRUE_UP, atol=1e-3)
|
| 178 |
+
|
| 179 |
+
def test_floor_basis_ignores_the_vertical_reference(self):
|
| 180 |
+
"""A floor's basis is built from a horizontal reference, not from up."""
|
| 181 |
+
mask, geometry = _floor_scene()
|
| 182 |
+
|
| 183 |
+
common = (mask, geometry["points"], geometry["validMask"], geometry["normals"], None)
|
| 184 |
+
without = fit_metric_floor_transform(*common, surface_kind="floor")
|
| 185 |
+
with_ref = fit_metric_floor_transform(*common, surface_kind="floor", vertical_ref=TRUE_UP)
|
| 186 |
+
|
| 187 |
+
self.assertIsNotNone(without)
|
| 188 |
+
self.assertIsNotNone(with_ref)
|
| 189 |
+
np.testing.assert_allclose(
|
| 190 |
+
np.asarray(with_ref["surfaceUAxis"], dtype=np.float32),
|
| 191 |
+
np.asarray(without["surfaceUAxis"], dtype=np.float32),
|
| 192 |
+
atol=1e-6,
|
| 193 |
+
)
|
| 194 |
+
np.testing.assert_allclose(
|
| 195 |
+
np.asarray(with_ref["surfaceVAxis"], dtype=np.float32),
|
| 196 |
+
np.asarray(without["surfaceVAxis"], dtype=np.float32),
|
| 197 |
+
atol=1e-6,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
unittest.main()
|
test_wall_plane_extents.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression checks for the reported physical size of a wall.
|
| 2 |
+
|
| 3 |
+
Tile density is computed from a wall's reported extents, so an extent that is
|
| 4 |
+
guessed rather than measured mis-scales the grid directly.
|
| 5 |
+
|
| 6 |
+
Without depth there is no absolute scale, so the wall *height* stays a prior
|
| 7 |
+
(WALL_HEIGHT_PRIOR_METERS). What must not be guessed is the wall's **aspect**:
|
| 8 |
+
it used to come from the axis-aligned bounding box of the source quad. A
|
| 9 |
+
slanted wall falls through to `cv2.minAreaRect`, whose corners may lie outside
|
| 10 |
+
the image entirely -- one wall in the sample photo reports a corner at x=-133 --
|
| 11 |
+
and the bounding box of that rotated rect is much wider than the wall is. The
|
| 12 |
+
quad's own edge lengths are the measurement.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
import cv2
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from services.wall.plane import WALL_HEIGHT_PRIOR_METERS, estimate_wall_plane
|
| 21 |
+
|
| 22 |
+
HEIGHT, WIDTH = 600, 700
|
| 23 |
+
LONG_SIDE, SHORT_SIDE = 400.0, 250.0
|
| 24 |
+
TILT_DEGREES = 20.0
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _rotated_wall_mask(tilt_degrees: float):
|
| 28 |
+
"""A rectangular wall of known side lengths, tilted in the image."""
|
| 29 |
+
radians = np.deg2rad(tilt_degrees)
|
| 30 |
+
rotation = np.array(
|
| 31 |
+
[
|
| 32 |
+
[np.cos(radians), -np.sin(radians)],
|
| 33 |
+
[np.sin(radians), np.cos(radians)],
|
| 34 |
+
],
|
| 35 |
+
dtype=np.float32,
|
| 36 |
+
)
|
| 37 |
+
corners = np.array(
|
| 38 |
+
[
|
| 39 |
+
[-LONG_SIDE / 2, -SHORT_SIDE / 2],
|
| 40 |
+
[LONG_SIDE / 2, -SHORT_SIDE / 2],
|
| 41 |
+
[LONG_SIDE / 2, SHORT_SIDE / 2],
|
| 42 |
+
[-LONG_SIDE / 2, SHORT_SIDE / 2],
|
| 43 |
+
],
|
| 44 |
+
dtype=np.float32,
|
| 45 |
+
)
|
| 46 |
+
placed = corners @ rotation.T + np.array([WIDTH / 2, HEIGHT / 2], dtype=np.float32)
|
| 47 |
+
|
| 48 |
+
mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
|
| 49 |
+
cv2.fillConvexPoly(mask, placed.round().astype(np.int32), 1)
|
| 50 |
+
return mask
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class WallPlaneExtentsTest(unittest.TestCase):
|
| 54 |
+
def test_a_tilted_wall_is_measured_along_its_own_edges(self):
|
| 55 |
+
"""Aspect comes from the quad's edges, not its bounding box."""
|
| 56 |
+
mask = _rotated_wall_mask(TILT_DEGREES)
|
| 57 |
+
|
| 58 |
+
_, plane = estimate_wall_plane(mask)
|
| 59 |
+
|
| 60 |
+
self.assertIsNotNone(plane)
|
| 61 |
+
expected = WALL_HEIGHT_PRIOR_METERS * (LONG_SIDE / SHORT_SIDE)
|
| 62 |
+
self.assertAlmostEqual(plane["surfaceWidthMeters"], expected, delta=0.05)
|
| 63 |
+
|
| 64 |
+
def test_the_bounding_box_of_a_tilted_wall_overstates_its_width(self):
|
| 65 |
+
"""Guards the test above: the old estimate really was different."""
|
| 66 |
+
radians = np.deg2rad(TILT_DEGREES)
|
| 67 |
+
box_width = LONG_SIDE * np.cos(radians) + SHORT_SIDE * np.sin(radians)
|
| 68 |
+
box_height = LONG_SIDE * np.sin(radians) + SHORT_SIDE * np.cos(radians)
|
| 69 |
+
|
| 70 |
+
from_box = WALL_HEIGHT_PRIOR_METERS * (box_width / box_height)
|
| 71 |
+
from_edges = WALL_HEIGHT_PRIOR_METERS * (LONG_SIDE / SHORT_SIDE)
|
| 72 |
+
|
| 73 |
+
self.assertGreater(abs(from_edges - from_box), 0.5)
|
| 74 |
+
|
| 75 |
+
def test_an_axis_aligned_wall_keeps_its_previous_extents(self):
|
| 76 |
+
"""The change must only move walls whose quad is actually tilted."""
|
| 77 |
+
mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
|
| 78 |
+
mask[100:100 + int(SHORT_SIDE), 150:150 + int(LONG_SIDE)] = 1
|
| 79 |
+
|
| 80 |
+
_, plane = estimate_wall_plane(mask)
|
| 81 |
+
|
| 82 |
+
self.assertIsNotNone(plane)
|
| 83 |
+
expected = WALL_HEIGHT_PRIOR_METERS * (LONG_SIDE / SHORT_SIDE)
|
| 84 |
+
self.assertAlmostEqual(plane["surfaceWidthMeters"], expected, delta=0.05)
|
| 85 |
+
self.assertAlmostEqual(plane["surfaceHeightMeters"], WALL_HEIGHT_PRIOR_METERS, places=6)
|
| 86 |
+
|
| 87 |
+
def test_a_wall_never_reports_a_degenerate_width(self):
|
| 88 |
+
"""A grazing sliver must still land in the renderer's usable range."""
|
| 89 |
+
mask = np.zeros((HEIGHT, WIDTH), dtype=np.uint8)
|
| 90 |
+
mask[100:560, 300:340] = 1 # a tall, very narrow strip
|
| 91 |
+
|
| 92 |
+
_, plane = estimate_wall_plane(mask)
|
| 93 |
+
|
| 94 |
+
self.assertIsNotNone(plane)
|
| 95 |
+
self.assertGreaterEqual(plane["surfaceWidthMeters"], 0.5)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
unittest.main()
|
visualizer.gpu.toml
CHANGED
|
@@ -17,7 +17,7 @@ enable_depth_estimation = true
|
|
| 17 |
enable_moge_geometry = true
|
| 18 |
enable_plane_fit = true
|
| 19 |
enable_multi_plane_surfaces = true
|
| 20 |
-
enable_wall_segments =
|
| 21 |
enable_intrinsic_shading = false
|
| 22 |
enable_shading_transfer = false
|
| 23 |
enable_fast_shadow_transfer = true
|
|
@@ -34,7 +34,7 @@ data_dir = "data"
|
|
| 34 |
|
| 35 |
[surface_mapping]
|
| 36 |
ransac_distance_threshold = 0.04
|
| 37 |
-
max_planes =
|
| 38 |
normal_angle_threshold_degrees = 35
|
| 39 |
normal_smoothing_kernel = 5
|
| 40 |
min_plane_pixels = 1500
|
|
|
|
| 17 |
enable_moge_geometry = true
|
| 18 |
enable_plane_fit = true
|
| 19 |
enable_multi_plane_surfaces = true
|
| 20 |
+
enable_wall_segments = true
|
| 21 |
enable_intrinsic_shading = false
|
| 22 |
enable_shading_transfer = false
|
| 23 |
enable_fast_shadow_transfer = true
|
|
|
|
| 34 |
|
| 35 |
[surface_mapping]
|
| 36 |
ransac_distance_threshold = 0.04
|
| 37 |
+
max_planes = 5
|
| 38 |
normal_angle_threshold_degrees = 35
|
| 39 |
normal_smoothing_kernel = 5
|
| 40 |
min_plane_pixels = 1500
|
visualizer.hf.toml
CHANGED
|
@@ -17,7 +17,7 @@ enable_depth_estimation = true
|
|
| 17 |
enable_moge_geometry = true
|
| 18 |
enable_plane_fit = true
|
| 19 |
enable_multi_plane_surfaces = true
|
| 20 |
-
enable_wall_segments =
|
| 21 |
enable_intrinsic_shading = false
|
| 22 |
enable_shading_transfer = false
|
| 23 |
enable_fast_shadow_transfer = true
|
|
@@ -31,7 +31,7 @@ data_dir = "data"
|
|
| 31 |
|
| 32 |
[surface_mapping]
|
| 33 |
ransac_distance_threshold = 0.04
|
| 34 |
-
max_planes =
|
| 35 |
normal_angle_threshold_degrees = 35
|
| 36 |
normal_smoothing_kernel = 5
|
| 37 |
min_plane_pixels = 1500
|
|
|
|
| 17 |
enable_moge_geometry = true
|
| 18 |
enable_plane_fit = true
|
| 19 |
enable_multi_plane_surfaces = true
|
| 20 |
+
enable_wall_segments = true
|
| 21 |
enable_intrinsic_shading = false
|
| 22 |
enable_shading_transfer = false
|
| 23 |
enable_fast_shadow_transfer = true
|
|
|
|
| 31 |
|
| 32 |
[surface_mapping]
|
| 33 |
ransac_distance_threshold = 0.04
|
| 34 |
+
max_planes = 5
|
| 35 |
normal_angle_threshold_degrees = 35
|
| 36 |
normal_smoothing_kernel = 5
|
| 37 |
min_plane_pixels = 1500
|
visualizer.local.toml
CHANGED
|
@@ -13,7 +13,7 @@ sam2_checkpoint = ""
|
|
| 13 |
enable_depth_estimation = false
|
| 14 |
enable_plane_fit = true
|
| 15 |
enable_multi_plane_surfaces = true
|
| 16 |
-
enable_wall_segments =
|
| 17 |
enable_intrinsic_shading = false
|
| 18 |
enable_shading_transfer = false
|
| 19 |
enable_fast_shadow_transfer = true
|
|
|
|
| 13 |
enable_depth_estimation = false
|
| 14 |
enable_plane_fit = true
|
| 15 |
enable_multi_plane_surfaces = true
|
| 16 |
+
enable_wall_segments = true
|
| 17 |
enable_intrinsic_shading = false
|
| 18 |
enable_shading_transfer = false
|
| 19 |
enable_fast_shadow_transfer = true
|