github-actions[bot]
Automated Deploy: 95241fef61713656c774921da02adaf14380bc08
18196ae
Raw History Blame Contribute Delete
6.67 kB
"""Wall stage of the conversion pipeline: one bundle segment per physical wall.
Functions
---------
build_wall_segments - discover walls and build their bundle segments
Designed to run in a background thread alongside the floor stages: all
analysis is at working resolution, and full-resolution work is limited to
each wall's own pixels (mask upscale, index encoding). Each wall's texture
mapping is an exact 3x3 plane transform, so no per-pixel UV is shipped.
"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
import cv2
import numpy as np
from config.runtime import ENABLE_FAST_SHADOW_TRANSFER, ENABLE_SHADING_TRANSFER
from config.surface import WALL_UV_MIN_COVERAGE
from services.geometry.camera import pixel_intrinsics_from_model
from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis
from services.lighting.shading import build_fast_shadow_lighting_maps, build_luminance_lighting_maps
from services.pipeline.bundle_assembly import build_wall_segment
from services.wall.components import WallComponent, WallDiscovery, discover_wall_components
from services.wall.plane import estimate_wall_plane
# Pixels sampled per wall to measure plane coverage and size.
MAPPING_SAMPLE_PIXELS = 20000
@dataclass
class WallResult:
segments: list[dict] = field(default_factory=list)
timings_ms: dict[str, float] = field(default_factory=dict)
@property
def detail(self) -> str:
parts = [f"walls={len(self.segments)}"]
parts += [f"{name}={ms:.0f}ms" for name, ms in self.timings_ms.items()]
return " ".join(parts)
def build_wall_segments(
img_np: np.ndarray,
seg_map: np.ndarray,
geometry: dict | None,
min_area: int,
segmentation_model: str,
first_segment_id: int = 1,
) -> WallResult:
"""Discover walls and return their bundle segments (ids start at first_segment_id)."""
result = WallResult()
started = time.perf_counter()
discovery = discover_wall_components(seg_map, geometry, min_area)
result.timings_ms["discovery"] = (time.perf_counter() - started) * 1000
if not discovery.components:
return result
started = time.perf_counter()
full_h, full_w = seg_map.shape[:2]
intrinsics = (
pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h)
if geometry is not None else None
)
work_h, work_w = discovery.components[0].work_mask.shape[:2]
work_image = cv2.resize(img_np, (work_w, work_h), interpolation=cv2.INTER_AREA)
for index, component in enumerate(discovery.components):
segment = _build_segment(
component,
discovery,
index=index,
segment_id=first_segment_id + index,
intrinsics=intrinsics,
geometry=geometry,
img_np=img_np,
work_image=work_image,
segmentation_model=segmentation_model,
)
if segment is not None:
result.segments.append(segment)
for segment in result.segments:
segment["metadata"]["wallComponentCount"] = len(result.segments)
result.timings_ms["segments"] = (time.perf_counter() - started) * 1000
return result
def _build_segment(
component: WallComponent,
discovery: WallDiscovery,
*,
index: int,
segment_id: int,
intrinsics: np.ndarray | None,
geometry: dict | None,
img_np: np.ndarray,
work_image: np.ndarray,
segmentation_model: str,
) -> dict | None:
wall_indices = np.flatnonzero(component.mask.ravel()).astype(np.uint32)
mapping = _wall_plane_mapping(component, discovery.vertical, wall_indices, intrinsics)
# With an exact plane mapping, skip estimate_wall_plane's second RANSAC fit
# and keep only its cheap contour quad as a fallback homography.
homography, plane = estimate_wall_plane(component.mask, None if mapping else geometry)
if homography is None or plane is None:
return None
if mapping:
plane.update(mapping)
plane["geometryProvider"] = (geometry or {}).get("provider")
return build_wall_segment(
wall_id=segment_id,
wall_index=index,
wall_indices=wall_indices,
homography=homography,
plane=plane,
lighting_maps=_wall_lighting(component, img_np, work_image),
segmentation_model=segmentation_model,
)
def _wall_plane_mapping(
component: WallComponent,
vertical: np.ndarray,
wall_indices: np.ndarray,
intrinsics: np.ndarray | None,
) -> dict | None:
"""Exact metric plane mapping for the wall, or None to use the contour homography.
Coverage and the wall's size in metres are measured on a pixel sample; the
renderer gets the 3x3 surfaceTransform, which is exact for every pixel.
"""
if component.plane is None or intrinsics is None or not len(wall_indices):
return None
u_axis, v_axis = upright_plane_basis(component.plane.normal, vertical)
sample = wall_indices[:: max(1, len(wall_indices) // MAPPING_SAMPLE_PIXELS)]
uv, hit = ray_plane_uv(
sample, component.mask.shape[1], intrinsics,
component.plane.origin, component.plane.normal, u_axis, v_axis,
)
coverage = float(hit.mean())
if coverage < WALL_UV_MIN_COVERAGE:
return None
uv_min = np.nanmin(uv, axis=0)
uv_max = np.nanmax(uv, axis=0)
transform = plane_to_image_transform(
intrinsics, component.plane.origin, component.plane.normal, u_axis, v_axis,
).flatten().tolist()
return {
"floorTransform": transform,
"surfaceTransform": transform,
"surfaceUAxis": u_axis.astype(float).tolist(),
"surfaceVAxis": v_axis.astype(float).tolist(),
"planeNormal": component.plane.normal.astype(float).tolist(),
"planeOrigin": component.plane.origin.astype(float).tolist(),
"surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)),
"surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)),
# The renderer treats the transform as metric at >= 0.35 confidence.
"geometryConfidence": coverage,
}
def _wall_lighting(component: WallComponent, img_np: np.ndarray, work_image: np.ndarray) -> dict | None:
"""Same lighting switches as the floor; the fast path runs at working resolution."""
if ENABLE_FAST_SHADOW_TRANSFER:
maps = build_fast_shadow_lighting_maps(work_image, component.work_mask)
if maps and maps.get("shadeMap") is not None:
return maps
if ENABLE_SHADING_TRANSFER:
return build_luminance_lighting_maps(img_np, component.mask)
return None