File size: 5,529 Bytes
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
"""Wall plane estimation and metric geometry validation.

Functions
---------
estimate_wall_plane             - compute wall homography from contour analysis
validate_wall_metric_geometry   - sanity-check metric wall geometry
"""

import cv2
import numpy as np

from enums import GeometryProvider, SurfaceType
from config.runtime import ENABLE_PLANE_FIT
from services.geometry.plane_fitting import (
    estimate_metric_floor_transform,
    fit_metric_floor_transform,
)


def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
    """Return a stable image-space homography for a semantic wall mask.

    Walls do not currently have metric depth fitting, so use the visible wall
    contour as the source quad and its bounding rectangle as the planar target.
    This preserves perspective convergence while keeping physical tile sizes
    deterministic until wall-specific depth calibration is available.
    """
    ys, xs = np.where(mask > 0)
    if len(xs) < 1000:
        return None, None

    h, w = mask.shape[:2]
    contours, _ = cv2.findContours((mask > 0).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contour = max(contours, key=cv2.contourArea) if contours else None
    if contour is None or cv2.contourArea(contour) < 1000:
        return None, None

    perimeter = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, max(2.0, perimeter * 0.02), True)
    if len(approx) >= 4:
        points = approx.reshape(-1, 2).astype(np.float32)
        hull = cv2.convexHull(points)
        if len(hull) >= 4:
            points = hull.reshape(-1, 2)
    else:
        points = np.empty((0, 2), dtype=np.float32)

    if len(points) != 4:
        rect = cv2.minAreaRect(contour)
        points = cv2.boxPoints(rect).astype(np.float32)

    # Order corners as top-left, top-right, bottom-right, bottom-left.
    sums = points.sum(axis=1)
    diffs = points[:, 1] - points[:, 0]
    ordered = np.float32([
        points[np.argmin(sums)],
        points[np.argmin(diffs)],
        points[np.argmax(sums)],
        points[np.argmax(diffs)],
    ])
    x1, y1 = float(np.min(ordered[:, 0])), float(np.min(ordered[:, 1]))
    x2, y2 = float(np.max(ordered[:, 0])), float(np.max(ordered[:, 1]))
    if x2 - x1 < 20 or y2 - y1 < 20:
        return None, None

    destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
    homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
    metric_geometry = None
    if ENABLE_PLANE_FIT and geometry:
        points = geometry.get("points")
        if points is not None:
            metric_geometry = fit_metric_floor_transform(
                mask,
                points,
                geometry.get("validMask"),
                geometry.get("normals"),
                geometry.get("intrinsics"),
                geometry.get("provider", GeometryProvider.METRIC_DEPTH),
                surface_kind="wall",
            )
        if metric_geometry is None:
            metric_geometry = estimate_metric_floor_transform(
                mask,
                geometry.get("depth"),
                geometry.get("provider", GeometryProvider.DEPTH_ANYTHING),
                geometry.get("intrinsics"),
                surface_kind="wall",
            )

    plane = {
        "x": x1,
        "y": y1,
        "width": x2 - x1,
        "height": y2 - y1,
        "quad": ordered.flatten().tolist(),
        "geometryConfidence": 0.45,
        "geometryProvider": GeometryProvider.WALL_CONTOUR_HOMOGRAPHY,
        "floorTransform": None,
        "surfaceTransform": None,
        "surfaceType": SurfaceType.WALL,
        "surfaceWidthMeters": max(0.5, 2.4 * (x2 - x1) / max(y2 - y1, 1.0)),
        "surfaceHeightMeters": 2.4,
        "metersPerUnit": None,
        "cameraIntrinsics": None,
        "camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
    }
    if metric_geometry and not validate_wall_metric_geometry(metric_geometry):
        print(
            "[WALL_GEOMETRY] rejected metric wall fit; using contour homography "
            f"confidence={metric_geometry.get('geometryConfidence')} "
            f"normal={metric_geometry.get('planeNormal')} "
            f"size={metric_geometry.get('surfaceWidthMeters')}x{metric_geometry.get('surfaceHeightMeters')}",
            flush=True,
        )
        metric_geometry = None

    if metric_geometry:
        plane.update(metric_geometry)
        plane["surfaceType"] = SurfaceType.WALL
        plane["geometryProvider"] = metric_geometry.get("geometryProvider", GeometryProvider.WALL_DEPTH)
    return homography, plane


def validate_wall_metric_geometry(geometry: dict) -> bool:
    confidence = float(geometry.get("geometryConfidence") or 0.0)
    normal = np.asarray(geometry.get("planeNormal") or [], dtype=np.float32)
    width = float(geometry.get("surfaceWidthMeters") or 0.0)
    height = float(geometry.get("surfaceHeightMeters") or 0.0)
    if confidence < 0.45 or normal.shape != (3,) or not np.isfinite(normal).all():
        return False
    # In the indoor coordinate system Y is vertical; a wall normal should be
    # mostly horizontal, unlike the floor normal.
    normal /= max(float(np.linalg.norm(normal)), 1e-6)
    if abs(float(normal[1])) > 0.45:
        return False
    if not (0.25 <= width <= 30.0 and 0.25 <= height <= 15.0):
        return False
    if width / max(height, 1e-6) > 20.0 or height / max(width, 1e-6) > 20.0:
        return False
    return True