File size: 9,140 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Place the seam between two wall surfaces on the corner they actually share.

Why this exists
---------------
Splitting one connected wall region into several surfaces is done by
``assign_points_to_surface_planes``, which scores each pixel against each fitted
plane on its own. That works in the middle of a wall and fails at a corner, for
a reason that is structural rather than a tuning problem: two planes *intersect*
at the corner, so the distance term of the score goes to zero for both of them
there. The decision is left to the per-pixel depth normal, and a learned depth
model rounds a corner, so across a band of a few tens of pixels that normal is
a blend of both walls. Blended normals sit outside SURFACE_NORMAL_ANGLE_DEGREES
of either plane, the score degenerates to ``argmin(distance)`` on the rounded
surface, and the seam lands wherever the rounding happened to fall.

Measured on job 03d0c9df (a bathroom, white marble, three walls): the back
wall's left edge came out at column 291.5 against a corner at 262, wandering
between 277 and 337. On screen that is a ~25 px strip of untiled wall down the
inside of the corner with a torn edge.

The fix
-------
Two planes meet along a straight line in 3D, and a pinhole camera projects a
straight line to a straight line. That projection is the corner. It is derived
from the two *global* plane fits -- which are RANSAC results over tens of
thousands of points, inlier ratios around 0.9-0.99 -- and never from a per-pixel
normal, so it is both unbiased and straight by construction.

On that job the line lands at column 266.0-266.8 over the full image height:
4 px from the true corner instead of 30, and with no wander at all.

Limits
------
Only meaningful for two planes that genuinely meet inside the picture. Parallel
planes, and planes meeting behind the camera, are refused rather than guessed
at, and callers keep their original split.
"""

from __future__ import annotations

import numpy as np

# |n_a x n_b| is sin(angle between the planes), so this is a 5 degree floor.
#
# It is not about avoiding a divide-by-zero, it is about conditioning. The
# intersection line's position error scales roughly as (normal error)/sin(angle),
# and RANSAC plane normals are good to about half a degree. At 5 degrees that
# puts the line within ~10% of the wall's extent; at half a degree it is further
# out than the wall is wide, which is worse than the per-pixel split it replaces.
# Anything shallower than this is two fits of one flat wall, which
# merge_coplanar_planes is responsible for collapsing.
MIN_CROSS_NORM = float(np.sin(np.deg2rad(5.0)))
# A point on the intersection must be at least this far in front of the camera
# before it can be projected at all.
MIN_DEPTH_METERS = 0.05


def corner_line_in_image(
    plane_a: dict,
    plane_b: dict,
    intrinsics: np.ndarray,
    height: int,
    width: int,
) -> tuple[float, float, float] | None:
    """Return ``(a, b, c)`` with ``a*x + b*y + c = 0`` along the shared corner.

    ``plane_a`` and ``plane_b`` are the dicts produced by the plane fitter: a
    unit ``normal`` and an ``origin`` lying on the plane. Returns None when the
    planes do not meet in front of the camera.
    """
    normal_a = np.asarray(plane_a["normal"], dtype=np.float64).ravel()
    normal_b = np.asarray(plane_b["normal"], dtype=np.float64).ravel()
    origin_a = np.asarray(plane_a["origin"], dtype=np.float64).ravel()
    origin_b = np.asarray(plane_b["origin"], dtype=np.float64).ravel()
    if normal_a.size != 3 or normal_b.size != 3:
        return None

    direction = np.cross(normal_a, normal_b)
    norm = float(np.linalg.norm(direction))
    if norm < MIN_CROSS_NORM:
        return None                      # parallel: no corner between them
    direction /= norm

    # The point on the intersection closest to the origin, found by adding the
    # line's own direction as a third constraint so the system is square.
    matrix = np.array([normal_a, normal_b, direction])
    offsets = np.array([normal_a @ origin_a, normal_b @ origin_b, 0.0])
    try:
        anchor = np.linalg.solve(matrix, offsets)
    except np.linalg.LinAlgError:
        return None

    # Two points far enough apart to define the projected line stably. The line
    # is straight under projection, so any two visible points on it will do.
    intrinsics = np.asarray(intrinsics, dtype=np.float64).reshape(3, 3)
    span = max(height, width) / float(max(intrinsics[0, 0], 1.0)) * float(anchor[2] or 1.0)
    span = float(np.clip(abs(span), 1.0, 1e4))
    projected = []
    for step in (-span, span):
        point = anchor + direction * step
        if point[2] <= MIN_DEPTH_METERS:
            continue
        u = intrinsics[0, 0] * point[0] / point[2] + intrinsics[0, 2]
        v = intrinsics[1, 1] * point[1] / point[2] + intrinsics[1, 2]
        projected.append((float(u), float(v)))
    if len(projected) < 2:
        return None                      # the corner is behind the camera

    (u0, v0), (u1, v1) = projected
    dx, dy = u1 - u0, v1 - v0
    if abs(dx) < 1e-9 and abs(dy) < 1e-9:
        return None
    # Line through the two points: a = dy, b = -dx, c = dx*v0 - dy*u0.
    a, b = dy, -dx
    c = dx * v0 - dy * u0
    scale = float(np.hypot(a, b))
    if scale < 1e-12:
        return None
    return (a / scale, b / scale, c / scale)


def signed_distance_to_line(
    line: tuple[float, float, float], height: int, width: int
) -> np.ndarray:
    """Per-pixel signed distance to `line`, positive on one arbitrary side."""
    a, b, c = line
    ys, xs = np.mgrid[0:height, 0:width]
    return (a * xs + b * ys + c).astype(np.float32)


def split_pieces_on_corner_line(
    piece_a: np.ndarray,
    piece_b: np.ndarray,
    line: tuple[float, float, float],
) -> tuple[np.ndarray, np.ndarray]:
    """Re-cut two touching pieces along `line`, keeping their union identical.

    Which piece takes which side is decided by where each one's own mass
    already lies, so the caller does not have to know the sign convention. Only
    the pixels the two pieces already occupy are redistributed -- nothing is
    gained from, or lost to, the rest of the image.
    """
    a_mask = piece_a.astype(bool)
    b_mask = piece_b.astype(bool)
    union = a_mask | b_mask
    if not union.any():
        return piece_a.astype(np.uint8), piece_b.astype(np.uint8)

    height, width = union.shape[:2]
    distance = signed_distance_to_line(line, height, width)

    # Orient by the medians rather than the means: a long thin annexed strip
    # drags a mean across the line, and the whole point is that the strip is on
    # the wrong side to begin with.
    median_a = float(np.median(distance[a_mask])) if a_mask.any() else 0.0
    median_b = float(np.median(distance[b_mask])) if b_mask.any() else 0.0
    if median_a == median_b:
        return piece_a.astype(np.uint8), piece_b.astype(np.uint8)
    a_is_negative = median_a < median_b

    a_side = distance < 0 if a_is_negative else distance >= 0
    new_a = (union & a_side).astype(np.uint8)
    new_b = (union & ~a_side).astype(np.uint8)
    return new_a, new_b


def straighten_piece_seams(
    pieces: list[tuple[int, np.ndarray]],
    planes: list[dict],
    intrinsics: np.ndarray | None,
    min_area: int,
) -> list[np.ndarray]:
    """Re-cut every seam between touching pieces onto its planes' shared corner.

    `pieces` pairs each mask with the index of the plane it was assigned to.
    Pieces that do not touch have no seam to straighten and are left alone, as
    are pairs whose planes do not meet in front of the camera.

    A straightened pair is only accepted when both sides survive `min_area`.
    That is the guard against a line that misses the union entirely: rather
    than hand one piece everything and delete the other, the original split is
    kept. Falling back to a slightly ragged seam is always better than losing a
    wall.
    """
    import cv2

    masks = [mask.astype(np.uint8, copy=True) for _, mask in pieces]
    if intrinsics is None or len(masks) < 2:
        return masks

    height, width = masks[0].shape[:2]
    touch_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))

    for first in range(len(masks)):
        for second in range(first + 1, len(masks)):
            mask_a, mask_b = masks[first], masks[second]
            if not mask_a.any() or not mask_b.any():
                continue
            # Only a seam that exists is worth moving.
            if not (cv2.dilate(mask_a, touch_kernel).astype(bool) & mask_b.astype(bool)).any():
                continue

            plane_a = planes[pieces[first][0]]
            plane_b = planes[pieces[second][0]]
            line = corner_line_in_image(plane_a, plane_b, intrinsics, height, width)
            if line is None:
                continue

            new_a, new_b = split_pieces_on_corner_line(mask_a, mask_b, line)
            if int(new_a.sum()) < min_area or int(new_b.sum()) < min_area:
                continue        # the line missed the union; keep the old split
            masks[first], masks[second] = new_a, new_b

    return masks