File size: 5,971 Bytes
d7b5c2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""Where two wall planes meet, the seam must land on the architectural corner.

    python test_wall_corner_split.py

Background
----------
Two adjacent walls used to be separated by `assign_points_to_surface_planes`,
which scores every pixel against every plane individually. Right at a corner
that score cannot discriminate: the distance term goes to zero for *both*
planes, so the decision falls entirely to the per-pixel depth normal -- and a
learned depth model rounds a corner, so for a few tens of pixels either side
the normal is a blend of the two walls.

Measured on a real bathroom photo (job 03d0c9df), that put the back wall's left
edge at column 291.5 when the corner is at 262, wandering between 277 and 337.
The visible result was a 25 px strip of untiled wall down the inside of the
corner with a torn edge.

Two planes intersect along a 3D line, and a pinhole camera projects a 3D line
to a straight line. That projection *is* the corner, it is computed from the
two global plane fits rather than from per-pixel normals, and it is straight by
construction. The numbers below are the real ones from that job.
"""

from __future__ import annotations

import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import numpy as np

from services.wall.corner import corner_line_in_image, split_pieces_on_corner_line

H, W = 576, 768
FOCAL, CX, CY = 579.6456298828125, 384.0, 288.0
INTRINSICS = np.array([[FOCAL, 0.0, CX], [0.0, FOCAL, CY], [0.0, 0.0, 1.0]], dtype=np.float32)

# Verbatim from the job's bundle metadata.
LEFT_WALL = {
    "normal": np.array([-0.9999967813491821, 0.0022450105752795935, 0.0012066650670021772]),
    "origin": np.array([-1.1624844074249268, -0.23183509707450867, 2.5155556201934814]),
}
BACK_WALL = {
    "normal": np.array([-0.007814906537532806, 0.0010164726991206408, 0.999968945980072]),
    "origin": np.array([0.07378386706113815, -0.7956849932670593, 5.718906402587891]),
}
TRUE_CORNER_COLUMN = 262        # measured from the photograph's vertical gradient
WRONG_BOUNDARY = 292            # what per-pixel plane assignment actually produced

failures: list[str] = []


def check(label: str, condition: bool, detail: str = "") -> None:
    if condition:
        print(f"  PASS  {label}")
    else:
        failures.append(label)
        print(f"  FAIL  {label}" + (f"  ({detail})" if detail else ""))


def left_edge_of(mask: np.ndarray, rows: range) -> np.ndarray:
    return np.array(
        [np.flatnonzero(mask[y])[0] if mask[y].any() else np.nan for y in rows],
        dtype=float,
    )


def main() -> int:
    print("corner line from two fitted planes")
    line = corner_line_in_image(LEFT_WALL, BACK_WALL, INTRINSICS, H, W)
    check("two perpendicular walls produce a corner line", line is not None)
    if line is None:
        print("\n1 FAILED: no line")
        return 1

    a, b, c = line
    columns = [(-c - b * y) / a for y in (0, H // 2, H - 1)] if abs(a) > 1e-9 else []
    check(
        "the line lands on the real corner, not the biased boundary",
        all(abs(col - TRUE_CORNER_COLUMN) <= 8 for col in columns),
        f"columns={[round(v, 1) for v in columns]} true={TRUE_CORNER_COLUMN}",
    )
    check(
        "the line is vertical, so it cannot wander",
        max(columns) - min(columns) <= 2.0,
        f"spread={max(columns) - min(columns):.2f}px",
    )

    print("\nre-cutting two pieces along it")
    # The failure as it actually shipped: the left wall has annexed a strip of
    # the back wall, and the seam between them is ragged rather than straight.
    rng = np.random.default_rng(11)
    left = np.zeros((H, W), np.uint8)
    back = np.zeros((H, W), np.uint8)
    for y in range(H):
        seam = WRONG_BOUNDARY + int(rng.integers(-14, 46))   # biased *and* ragged
        left[y, 40:seam] = 1
        back[y, seam:545] = 1

    before = left_edge_of(back, range(130, 390))
    fixed_left, fixed_back = split_pieces_on_corner_line(left, back, line)
    after = left_edge_of(fixed_back, range(130, 390))

    print(f"    before: mean={np.nanmean(before):6.1f} std={np.nanstd(before):5.1f}")
    print(f"    after : mean={np.nanmean(after):6.1f} std={np.nanstd(after):5.1f}")

    check(
        "the seam moves onto the corner",
        abs(np.nanmean(after) - TRUE_CORNER_COLUMN) <= 8,
        f"mean={np.nanmean(after):.1f} true={TRUE_CORNER_COLUMN}",
    )
    check(
        "the seam stops wandering",
        np.nanstd(after) <= 1.5,
        f"std={np.nanstd(after):.2f} (was {np.nanstd(before):.2f})",
    )
    check(
        "the back wall reclaims the annexed strip",
        int(fixed_back.sum()) > int(back.sum()),
        f"{int(back.sum())} -> {int(fixed_back.sum())}",
    )
    check(
        "the two pieces stay disjoint",
        not (fixed_left.astype(bool) & fixed_back.astype(bool)).any(),
    )
    check(
        "no pixel is lost between them",
        int(fixed_left.sum()) + int(fixed_back.sum())
        == int(left.astype(bool).sum()) + int(back.astype(bool).sum()),
        f"{int(fixed_left.sum()) + int(fixed_back.sum())} vs "
        f"{int(left.sum()) + int(back.sum())}",
    )

    print("\nrefusals")
    parallel = {"normal": np.array([0.0, 0.0, 1.0]), "origin": np.array([0.0, 0.0, 8.0])}
    check(
        "parallel planes have no corner",
        corner_line_in_image(BACK_WALL, parallel, INTRINSICS, H, W) is None,
    )
    behind = {"normal": np.array([1.0, 0.0, 0.0]), "origin": np.array([0.0, 0.0, -4.0])}
    check(
        "a corner behind the camera is refused",
        corner_line_in_image(behind, {"normal": np.array([0.0, 0.0, 1.0]),
                                      "origin": np.array([0.0, 0.0, -4.0])},
                             INTRINSICS, H, W) is None,
    )

    print()
    if failures:
        print(f"{len(failures)} FAILED: {', '.join(failures)}")
        return 1
    print("All checks passed.")
    return 0


if __name__ == "__main__":
    sys.exit(main())