github-actions[bot]
Automated Deploy: 493daa301f7f4360c6f8a09b665c70b6c12463cd
790d9ba
Raw History Blame Contribute Delete
5.53 kB
"""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