File size: 7,861 Bytes
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73828b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Debug overlay / visualization functions for pipeline stages."""

import numpy as np
import cv2


def debug_mask_overlay(
    image_rgb: np.ndarray,
    mask: np.ndarray,
    color: tuple[int, int, int] = (45, 180, 255),
) -> np.ndarray:
    """Overlay a binary analysis mask without changing the uploaded image."""
    output = image_rgb.copy()
    valid = mask.astype(bool)
    if valid.any():
        overlay = np.empty_like(output)
        overlay[:] = color
        output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid]
    return output


WALL_COMPONENT_COLORS = (
    (255, 96, 96), (96, 200, 255), (140, 240, 140), (255, 200, 80),
    (210, 140, 255), (255, 140, 200), (120, 255, 230), (200, 200, 120),
)


def debug_wall_components_overlay(image_rgb: np.ndarray, components) -> np.ndarray:
    """Tint each wall component a distinct colour and label it.

    `components` is the list of (area, mask) pairs returned by
    wall_surface_components(). Distinct colours are what make it obvious when
    two physically separate walls have been merged into one component, or when
    a single wall has been split across a corner.
    """
    output = image_rgb.copy()
    for index, item in enumerate(components):
        mask = item[1] if isinstance(item, (tuple, list)) else item
        valid = mask.astype(bool)
        if not valid.any():
            continue
        color = WALL_COMPONENT_COLORS[index % len(WALL_COMPONENT_COLORS)]
        overlay = np.empty_like(output)
        overlay[:] = color
        output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid]
        ys, xs = np.where(valid)
        center = (int(xs.mean()) - 42, int(ys.mean()))
        label = f"Wall {index + 1}"
        cv2.putText(output, label, center, cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 0), 5, cv2.LINE_AA)
        cv2.putText(output, label, center, cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2, cv2.LINE_AA)
    return output


def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
    labels = seg_map.astype(np.int32)
    hsv = np.zeros((*labels.shape, 3), dtype=np.uint8)
    hsv[..., 0] = (labels * 37) % 180
    hsv[..., 1] = 180
    hsv[..., 2] = 255
    colors = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
    return cv2.addWeighted(image_rgb, 0.42, colors, 0.58, 0)


def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
    scalar = values.astype(np.float32)
    finite = np.isfinite(scalar)
    if mask is not None:
        finite &= mask.astype(bool)
    valid = scalar[finite]
    if valid.size == 0:
        return np.zeros((*scalar.shape[:2], 3), dtype=np.uint8)
    low, high = np.percentile(valid, [2, 98])
    if high <= low:
        high = low + 1.0
    normalized = np.clip((scalar - low) / (high - low), 0.0, 1.0)
    normalized[~np.isfinite(normalized)] = 0.0
    output = cv2.applyColorMap(np.round(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO)
    output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
    if mask is not None:
        output[~mask.astype(bool)] = 0
    return output


def debug_plane_overlay(image_rgb: np.ndarray, plane: dict | None) -> np.ndarray:
    output = image_rgb.copy()
    if not plane:
        return output
    raw_quad = plane.get("quad")
    if not isinstance(raw_quad, list) or len(raw_quad) != 8:
        return output
    points = np.asarray(raw_quad, dtype=np.float32).reshape(-1, 2)
    if not np.isfinite(points).all():
        return output
    points_i = np.round(points).astype(np.int32)
    overlay = output.copy()
    cv2.fillConvexPoly(overlay, points_i, (45, 180, 255))
    output = cv2.addWeighted(output, 0.64, overlay, 0.36, 0)
    cv2.polylines(output, [points_i], isClosed=True, color=(255, 255, 255), thickness=3, lineType=cv2.LINE_AA)
    return output


def debug_surface_overlay(image_rgb: np.ndarray, floor_mask: np.ndarray, surface_mask: np.ndarray) -> np.ndarray:
    output = image_rgb.copy()
    removed = (floor_mask > 0) & (surface_mask == 0)
    if removed.any():
        red = np.empty_like(output)
        red[:] = (220, 80, 80)
        output[removed] = cv2.addWeighted(output, 0.42, red, 0.58, 0)[removed]
    return debug_mask_overlay(output, surface_mask, (45, 180, 255))


def debug_floor_direction_overlay(image_rgb: np.ndarray, floor_direction: dict) -> np.ndarray:
    output = image_rgb.copy()
    direction_axis = floor_direction.get("directionAxis")
    if isinstance(direction_axis, dict):
        try:
            start = (
                round(float(direction_axis["startX"])),
                round(float(direction_axis["startY"])),
            )
            end = (
                round(float(direction_axis["endX"])),
                round(float(direction_axis["endY"])),
            )
            cv2.arrowedLine(
                output,
                start,
                end,
                (45, 180, 255),
                4,
                cv2.LINE_AA,
                tipLength=0.08,
            )
        except (KeyError, TypeError, ValueError):
            pass

    geometry_axis = floor_direction.get("geometryAxis")
    if isinstance(geometry_axis, dict):
        try:
            start = (
                round(float(geometry_axis["nearX"])),
                round(float(geometry_axis["nearY"])),
            )
            end = (
                round(float(geometry_axis["farX"])),
                round(float(geometry_axis["farY"])),
            )
            cv2.arrowedLine(
                output,
                start,
                end,
                (45, 180, 255),
                4,
                cv2.LINE_AA,
                tipLength=0.08,
            )
        except (KeyError, TypeError, ValueError):
            pass

    for line in floor_direction.get("dominantLines") or []:
        try:
            start = (round(float(line["x1"])), round(float(line["y1"])))
            end = (round(float(line["x2"])), round(float(line["y2"])))
        except (KeyError, TypeError, ValueError):
            continue
        cv2.line(output, start, end, (45, 180, 255), 3, cv2.LINE_AA)

    label = floor_direction.get("directionLabel") or "unknown"
    angle = floor_direction.get("renderAngleDegrees")
    confidence = floor_direction.get("confidence")
    detail = f"{label}"
    if isinstance(angle, (int, float)):
        detail += f"  {angle:.1f} deg"
    if isinstance(confidence, (int, float)):
        detail += f"  {confidence:.0%}"
    cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (255, 255, 255), 3, cv2.LINE_AA)
    cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (25, 25, 25), 1, cv2.LINE_AA)
    return output


def debug_uv_checkerboard(
    height: int,
    width: int,
    surface_indices: np.ndarray,
    uv: np.ndarray,
) -> np.ndarray:
    output = np.zeros((height, width, 3), dtype=np.uint8)
    valid = np.isfinite(uv).all(axis=1)
    if not valid.any():
        return output
    coords = uv[valid]
    cells = (np.floor(coords[:, 0] * 8) + np.floor(coords[:, 1] * 8)).astype(np.int32)
    colors = np.where((cells % 2)[:, None] == 0, np.array([45, 180, 255]), np.array([45, 80, 180]))
    output.reshape(-1, 3)[surface_indices[valid]] = colors.astype(np.uint8)
    return output


def debug_plane_id_map(
    height: int,
    width: int,
    surface_indices: np.ndarray,
    plane_ids: np.ndarray,
) -> np.ndarray:
    output = np.zeros((height, width, 3), dtype=np.uint8)
    valid = plane_ids >= 0
    if not valid.any():
        return output
    ids = plane_ids[valid].astype(np.int32)
    hsv = np.zeros((len(ids), 1, 3), dtype=np.uint8)
    hsv[:, 0, 0] = (ids * 47) % 180
    hsv[:, 0, 1] = 190
    hsv[:, 0, 2] = 255
    output.reshape(-1, 3)[surface_indices[valid]] = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB).reshape(-1, 3)
    return output