github-actions[bot] commited on
Commit ·
e8f5b94
1
Parent(s): 6a5eed7
Automated Deploy: 6b2e9fd79a331c39f9ce8d407a6fb8b335f13eb8
Browse files- Dockerfile +8 -1
- Dockerfile.hf +8 -1
- app.py +747 -162
- frontend/viz2d-demo/e2e/lighting-preservation.spec.ts +99 -3
- frontend/viz2d-demo/package.json +7 -1
- test_floor_geometry.py +68 -0
- visualizer.gpu.toml +3 -0
- visualizer.hf.toml +3 -0
- visualizer.local.toml +1 -0
- visualizer.segformer.toml +1 -0
Dockerfile
CHANGED
|
@@ -9,10 +9,17 @@ ENV PYTHONUNBUFFERED=1 \
|
|
| 9 |
QA_FRONTEND_DIR=/app/frontend/viz2d-demo \
|
| 10 |
HOME=/home/user
|
| 11 |
|
| 12 |
-
# Install
|
|
|
|
| 13 |
RUN apt-get update && \
|
| 14 |
apt-get install -y --no-install-recommends \
|
|
|
|
|
|
|
| 15 |
git \
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
ffmpeg \
|
| 17 |
libglib2.0-0 \
|
| 18 |
libgomp1 \
|
|
|
|
| 9 |
QA_FRONTEND_DIR=/app/frontend/viz2d-demo \
|
| 10 |
HOME=/home/user
|
| 11 |
|
| 12 |
+
# Install runtime dependencies plus the tools required by Hugging Face Spaces
|
| 13 |
+
# Dev Mode. Dev Mode is enabled only on the staging Space.
|
| 14 |
RUN apt-get update && \
|
| 15 |
apt-get install -y --no-install-recommends \
|
| 16 |
+
bash \
|
| 17 |
+
curl \
|
| 18 |
git \
|
| 19 |
+
git-lfs \
|
| 20 |
+
procps \
|
| 21 |
+
rsync \
|
| 22 |
+
wget \
|
| 23 |
ffmpeg \
|
| 24 |
libglib2.0-0 \
|
| 25 |
libgomp1 \
|
Dockerfile.hf
CHANGED
|
@@ -9,10 +9,17 @@ ENV PYTHONUNBUFFERED=1 \
|
|
| 9 |
QA_FRONTEND_DIR=/app/frontend/viz2d-demo \
|
| 10 |
HOME=/home/user
|
| 11 |
|
| 12 |
-
# Install
|
|
|
|
| 13 |
RUN apt-get update && \
|
| 14 |
apt-get install -y --no-install-recommends \
|
|
|
|
|
|
|
| 15 |
git \
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
ffmpeg \
|
| 17 |
libglib2.0-0 \
|
| 18 |
libgomp1 \
|
|
|
|
| 9 |
QA_FRONTEND_DIR=/app/frontend/viz2d-demo \
|
| 10 |
HOME=/home/user
|
| 11 |
|
| 12 |
+
# Install runtime dependencies plus the tools required by Hugging Face Spaces
|
| 13 |
+
# Dev Mode. Dev Mode is enabled only on the staging Space.
|
| 14 |
RUN apt-get update && \
|
| 15 |
apt-get install -y --no-install-recommends \
|
| 16 |
+
bash \
|
| 17 |
+
curl \
|
| 18 |
git \
|
| 19 |
+
git-lfs \
|
| 20 |
+
procps \
|
| 21 |
+
rsync \
|
| 22 |
+
wget \
|
| 23 |
ffmpeg \
|
| 24 |
libglib2.0-0 \
|
| 25 |
libgomp1 \
|
app.py
CHANGED
|
@@ -9,6 +9,7 @@ import os
|
|
| 9 |
import shutil
|
| 10 |
import subprocess
|
| 11 |
import time
|
|
|
|
| 12 |
import urllib.error
|
| 13 |
import urllib.parse
|
| 14 |
import urllib.request
|
|
@@ -198,12 +199,18 @@ ENABLE_PLANE_FIT = str(config_value(
|
|
| 198 |
"enable_plane_fit",
|
| 199 |
"1",
|
| 200 |
)).lower() in {"1", "true", "yes", "on"}
|
| 201 |
-
ENABLE_MULTI_PLANE_SURFACES = str(config_value(
|
| 202 |
"ENABLE_MULTI_PLANE_SURFACES",
|
| 203 |
"runtime",
|
| 204 |
"enable_multi_plane_surfaces",
|
| 205 |
"1",
|
| 206 |
-
)).lower() in {"1", "true", "yes", "on"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
INTRINSIC_MODEL_VERSION = str(config_value(
|
| 208 |
"INTRINSIC_MODEL_VERSION",
|
| 209 |
"models",
|
|
@@ -258,7 +265,13 @@ DEBUG_ARTIFACTS_ENABLED = str(config_value(
|
|
| 258 |
"debug_artifacts_enabled",
|
| 259 |
"1",
|
| 260 |
)).lower() in {"1", "true", "yes", "on"}
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
"DEBUG_ARTIFACTS_MAX_DIMENSION",
|
| 263 |
"runtime",
|
| 264 |
"debug_artifacts_max_dimension",
|
|
@@ -511,7 +524,7 @@ moge_model = None
|
|
| 511 |
sam2_predictor = None
|
| 512 |
intrinsic_models = None
|
| 513 |
|
| 514 |
-
LIGHTING_TRANSFER_VERSION =
|
| 515 |
SHADE_MAP_MIN = 0.08
|
| 516 |
SHADE_MAP_MAX = 1.85
|
| 517 |
SHOWROOM_SHADE_MAP_MIN = 0.85
|
|
@@ -717,6 +730,7 @@ UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
|
| 717 |
JOB_DIR.mkdir(parents=True, exist_ok=True)
|
| 718 |
MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
|
| 719 |
QA_RUN_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 720 |
app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
|
| 721 |
|
| 722 |
|
|
@@ -1022,6 +1036,7 @@ class PipelineDebugCapture:
|
|
| 1022 |
self._write_manifest()
|
| 1023 |
|
| 1024 |
PRIMARY_FLOOR_CLASSES = {"floor", "rug", "carpet", "mat"}
|
|
|
|
| 1025 |
FLOOR_SURFACE_CLASSES = {
|
| 1026 |
"floor", "road", "sidewalk", "ground", "field", "grass", "sand",
|
| 1027 |
"runway", "dirt track", "land", "stairs", "step", "rug", "carpet", "mat",
|
|
@@ -1418,38 +1433,75 @@ def build_showroom_shade_map_from_luminance(
|
|
| 1418 |
return build_showroom_shade_map_from_relative(relative, surface_mask)
|
| 1419 |
|
| 1420 |
|
| 1421 |
-
def build_reflection_map(
|
| 1422 |
-
img_np: np.ndarray,
|
| 1423 |
-
surface_mask: np.ndarray,
|
| 1424 |
-
relative_shading: np.ndarray | None = None,
|
| 1425 |
-
|
|
|
|
| 1426 |
if not surface_mask.any():
|
| 1427 |
return None
|
| 1428 |
|
| 1429 |
-
mask = surface_mask.astype(np.uint8)
|
| 1430 |
-
h, w = mask.shape[:2]
|
| 1431 |
-
reflection_candidates: list[np.ndarray] = []
|
| 1432 |
-
|
| 1433 |
-
|
| 1434 |
-
|
| 1435 |
-
|
| 1436 |
-
|
| 1437 |
-
|
| 1438 |
-
|
| 1439 |
-
|
| 1440 |
-
|
| 1441 |
-
|
| 1442 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1443 |
floor_values = floor_values[np.isfinite(floor_values)]
|
| 1444 |
if floor_values.size >= max(256, int(h * w * 0.002)):
|
| 1445 |
-
median_lum = float(np.median(floor_values))
|
| 1446 |
-
if median_lum > 1e-3:
|
| 1447 |
-
filled = luminance
|
| 1448 |
-
filled
|
| 1449 |
-
|
| 1450 |
-
|
| 1451 |
-
|
| 1452 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1453 |
|
| 1454 |
if not reflection_candidates:
|
| 1455 |
return None
|
|
@@ -1457,22 +1509,64 @@ def build_reflection_map(
|
|
| 1457 |
# A reflection is additive light. Dark source-floor detail belongs to the
|
| 1458 |
# illumination map; transferring it here would turn old material color or
|
| 1459 |
# texture into an artificial dark reflection on the replacement material.
|
| 1460 |
-
reflection = np.maximum.reduce(reflection_candidates).astype(np.float32)
|
| 1461 |
-
if min(h, w) > 120:
|
| 1462 |
-
sigma = max(0.6, min(h, w) / 520.0)
|
| 1463 |
-
reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 1464 |
-
reflection = np.clip(reflection, REFLECTION_MAP_MIN, REFLECTION_MAP_MAX)
|
| 1465 |
-
reflection[
|
| 1466 |
if float(np.max(np.abs(reflection[mask > 0]))) < 0.025:
|
| 1467 |
return None
|
| 1468 |
encoded = (reflection - REFLECTION_MAP_MIN) / (REFLECTION_MAP_MAX - REFLECTION_MAP_MIN)
|
| 1469 |
-
return np.round(encoded * 255.0).clip(0, 255).astype(np.uint8)
|
| 1470 |
-
|
| 1471 |
-
|
| 1472 |
-
def
|
| 1473 |
-
|
| 1474 |
-
surface_mask: np.ndarray,
|
| 1475 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1476 |
if not surface_mask.any():
|
| 1477 |
return None
|
| 1478 |
|
|
@@ -1491,13 +1585,23 @@ def build_luminance_lighting_maps(
|
|
| 1491 |
|
| 1492 |
relative = filled / median_lum
|
| 1493 |
relative[~np.isfinite(relative)] = 1.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1494 |
shade = smooth_relative_lighting(relative, mask)
|
| 1495 |
if shade is None:
|
| 1496 |
return None
|
| 1497 |
-
return {
|
| 1498 |
-
"shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX),
|
| 1499 |
-
"showroomShadeMap":
|
| 1500 |
-
"reflectionMap": build_reflection_map(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1501 |
}
|
| 1502 |
|
| 1503 |
|
|
@@ -1706,9 +1810,10 @@ def preserve_observed_lighting(
|
|
| 1706 |
|
| 1707 |
|
| 1708 |
def build_intrinsic_lighting_maps(
|
| 1709 |
-
img_np: np.ndarray,
|
| 1710 |
-
surface_mask: np.ndarray,
|
| 1711 |
-
|
|
|
|
| 1712 |
if not surface_mask.any() or intrinsic_models is None:
|
| 1713 |
return None
|
| 1714 |
|
|
@@ -1728,7 +1833,11 @@ def build_intrinsic_lighting_maps(
|
|
| 1728 |
if smoothed is None:
|
| 1729 |
return None
|
| 1730 |
|
| 1731 |
-
luminance_maps = build_luminance_lighting_maps(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1732 |
if luminance_maps and luminance_maps.get("shadeMap") is not None:
|
| 1733 |
observed = decode_relative_map(
|
| 1734 |
luminance_maps["shadeMap"],
|
|
@@ -1737,12 +1846,22 @@ def build_intrinsic_lighting_maps(
|
|
| 1737 |
)
|
| 1738 |
smoothed = preserve_observed_lighting(smoothed, observed, surface_mask)
|
| 1739 |
alignment = f"{alignment}+observed-lighting"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1740 |
print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True)
|
| 1741 |
|
| 1742 |
return {
|
| 1743 |
"shadeMap": encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX),
|
| 1744 |
"showroomShadeMap": build_showroom_shade_map_from_relative(smoothed, surface_mask),
|
| 1745 |
-
"reflectionMap": build_reflection_map(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1746 |
}
|
| 1747 |
except Exception as exc:
|
| 1748 |
print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
|
|
@@ -2187,14 +2306,15 @@ def project_points_to_plane(points: np.ndarray, origin: np.ndarray, normal: np.n
|
|
| 2187 |
return projected.astype(np.float32), signed_distance.astype(np.float32)
|
| 2188 |
|
| 2189 |
|
| 2190 |
-
def fit_metric_floor_transform(
|
| 2191 |
-
mask: np.ndarray,
|
| 2192 |
-
points_map: np.ndarray,
|
| 2193 |
-
valid_mask: np.ndarray | None = None,
|
| 2194 |
-
normals_map: np.ndarray | None = None,
|
| 2195 |
-
intrinsics: np.ndarray | None = None,
|
| 2196 |
-
provider: str = "metric-depth",
|
| 2197 |
-
|
|
|
|
| 2198 |
h, w = mask.shape[:2]
|
| 2199 |
valid = (mask > 0) & np.isfinite(points_map).all(axis=2) & (points_map[:, :, 2] > 0.05)
|
| 2200 |
if valid_mask is not None:
|
|
@@ -2250,17 +2370,15 @@ def fit_metric_floor_transform(
|
|
| 2250 |
if inlier_ratio < 0.45 or residual > 0.18:
|
| 2251 |
return None
|
| 2252 |
|
| 2253 |
-
#
|
| 2254 |
-
|
| 2255 |
-
|
| 2256 |
-
|
| 2257 |
-
|
| 2258 |
-
|
| 2259 |
-
|
| 2260 |
-
|
| 2261 |
-
|
| 2262 |
-
floor_points = projected_points - centroid
|
| 2263 |
-
uv = np.column_stack((floor_points @ u_axis, floor_points @ v_axis)).astype(np.float32)
|
| 2264 |
image_points = np.column_stack((xs[keep], ys[keep])).astype(np.float32)
|
| 2265 |
transform, ransac_mask = cv2.findHomography(
|
| 2266 |
image_points,
|
|
@@ -2288,8 +2406,14 @@ def fit_metric_floor_transform(
|
|
| 2288 |
else None
|
| 2289 |
)
|
| 2290 |
|
| 2291 |
-
return {
|
| 2292 |
-
"floorTransform": transform.flatten().tolist(),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2293 |
"metersPerUnit": 1.0,
|
| 2294 |
"geometryConfidence": confidence,
|
| 2295 |
"geometryProvider": provider,
|
|
@@ -2311,12 +2435,13 @@ def fit_metric_floor_transform(
|
|
| 2311 |
}
|
| 2312 |
|
| 2313 |
|
| 2314 |
-
def estimate_metric_floor_transform(
|
| 2315 |
-
mask: np.ndarray,
|
| 2316 |
-
depth: np.ndarray | None,
|
| 2317 |
-
provider: str = "depth-anything",
|
| 2318 |
-
intrinsics: np.ndarray | None = None,
|
| 2319 |
-
|
|
|
|
| 2320 |
if depth is None or not ENABLE_PLANE_FIT:
|
| 2321 |
return None
|
| 2322 |
h, w = mask.shape[:2]
|
|
@@ -2324,7 +2449,13 @@ def estimate_metric_floor_transform(
|
|
| 2324 |
depth_for_points, depth_scale = prepare_depth_for_backprojection(depth, mask, is_metric_depth)
|
| 2325 |
pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h)
|
| 2326 |
points = backproject_depth(depth_for_points, pixel_intrinsics)
|
| 2327 |
-
result = fit_metric_floor_transform(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2328 |
if result is not None:
|
| 2329 |
result["depthScale"] = depth_scale
|
| 2330 |
return result
|
|
@@ -2723,10 +2854,6 @@ def analyze_surface_uv_quality(
|
|
| 2723 |
if coverage < SURFACE_UV_MIN_COVERAGE:
|
| 2724 |
quality["textureMappingReason"] = "incomplete-surface-uv"
|
| 2725 |
return quality
|
| 2726 |
-
if len(active_plane_ids) != 1:
|
| 2727 |
-
quality["textureMappingReason"] = "multiple-surface-planes"
|
| 2728 |
-
return quality
|
| 2729 |
-
|
| 2730 |
h, w = surface_mask.shape[:2]
|
| 2731 |
uv_grid = np.full((h * w, 2), np.nan, dtype=np.float32)
|
| 2732 |
plane_grid = np.full(h * w, 255, dtype=np.uint8)
|
|
@@ -2777,13 +2904,13 @@ def analyze_surface_uv_quality(
|
|
| 2777 |
if bad_ratio > SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO:
|
| 2778 |
quality["textureMappingReason"] = "noisy-surface-uv"
|
| 2779 |
return quality
|
| 2780 |
-
|
| 2781 |
-
|
| 2782 |
-
|
| 2783 |
-
|
| 2784 |
-
|
| 2785 |
-
|
| 2786 |
-
|
| 2787 |
return quality
|
| 2788 |
|
| 2789 |
|
|
@@ -2890,9 +3017,17 @@ def build_surface_uv_mapping(
|
|
| 2890 |
plane_ids[assigned_positions] = plane_idx
|
| 2891 |
plane["assignedCount"] = int(assigned_keep.sum())
|
| 2892 |
|
| 2893 |
-
serializable_planes = []
|
| 2894 |
-
for plane in planes:
|
| 2895 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2896 |
"id": int(plane["id"]),
|
| 2897 |
"normal": plane["normal"].astype(float).tolist(),
|
| 2898 |
"origin": plane["origin"].astype(float).tolist(),
|
|
@@ -2902,8 +3037,12 @@ def build_surface_uv_mapping(
|
|
| 2902 |
"inlierCount": int(plane["inlierCount"]),
|
| 2903 |
"assignedCount": int(plane.get("assignedCount", 0)),
|
| 2904 |
"isFloor": bool(plane["isFloor"]),
|
| 2905 |
-
"fitMode": str(plane.get("fitMode", "normal-aware")),
|
| 2906 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2907 |
|
| 2908 |
finite_uv = np.isfinite(uv_by_mask).all(axis=1)
|
| 2909 |
uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids)
|
|
@@ -2931,7 +3070,7 @@ def build_surface_uv_mapping(
|
|
| 2931 |
}
|
| 2932 |
|
| 2933 |
|
| 2934 |
-
def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray, geometry: dict | None = None):
|
| 2935 |
ys, xs = np.where(mask > 0)
|
| 2936 |
if len(xs) < 1000:
|
| 2937 |
return None, None
|
|
@@ -3038,7 +3177,203 @@ def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray, geometry: dict |
|
|
| 3038 |
"confidence": 0.25 if vanishing_point is not None else 0.1,
|
| 3039 |
},
|
| 3040 |
})
|
| 3041 |
-
return homography, plane
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3042 |
|
| 3043 |
|
| 3044 |
def build_floor_surface_mask(
|
|
@@ -3644,7 +3979,7 @@ def build_manifest_segmentation_bundle(
|
|
| 3644 |
return buffer.getvalue()
|
| 3645 |
|
| 3646 |
|
| 3647 |
-
def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None):
|
| 3648 |
t_start = time.perf_counter()
|
| 3649 |
|
| 3650 |
t0 = time.perf_counter()
|
|
@@ -3664,8 +3999,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3664 |
image_loading_elapsed * 1000,
|
| 3665 |
)
|
| 3666 |
|
| 3667 |
-
|
| 3668 |
-
|
|
|
|
|
|
|
| 3669 |
segmentation_elapsed = time.perf_counter() - t0
|
| 3670 |
print(f"[TIMING] Floor segmentation took {segmentation_elapsed:.3f} seconds", flush=True)
|
| 3671 |
if debug is not None:
|
|
@@ -3688,8 +4025,12 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3688 |
segmentation_elapsed * 1000,
|
| 3689 |
)
|
| 3690 |
|
| 3691 |
-
|
| 3692 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3693 |
print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 3694 |
|
| 3695 |
t0 = time.perf_counter()
|
|
@@ -3729,8 +4070,11 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3729 |
floor_mask_elapsed * 1000,
|
| 3730 |
)
|
| 3731 |
|
| 3732 |
-
|
| 3733 |
-
|
|
|
|
|
|
|
|
|
|
| 3734 |
depth = geometry.get("depth")
|
| 3735 |
geometry_elapsed = time.perf_counter() - t0
|
| 3736 |
print(
|
|
@@ -3755,8 +4099,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3755 |
geometry_elapsed * 1000,
|
| 3756 |
)
|
| 3757 |
|
| 3758 |
-
|
| 3759 |
-
|
|
|
|
|
|
|
| 3760 |
plane_elapsed = time.perf_counter() - t0
|
| 3761 |
print(f"[TIMING] Plane fitting / homography calculation took {plane_elapsed:.3f} seconds", flush=True)
|
| 3762 |
if debug is not None:
|
|
@@ -3776,9 +4122,15 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3776 |
plane_elapsed * 1000,
|
| 3777 |
)
|
| 3778 |
|
| 3779 |
-
|
| 3780 |
-
|
|
|
|
|
|
|
| 3781 |
surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3782 |
surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
|
| 3783 |
occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
|
| 3784 |
occlusion_indices = np.flatnonzero(occlusion_mask.ravel()).astype(np.uint32)
|
|
@@ -3800,8 +4152,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3800 |
surface_mask_elapsed * 1000,
|
| 3801 |
)
|
| 3802 |
|
| 3803 |
-
|
| 3804 |
-
|
|
|
|
|
|
|
| 3805 |
use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
|
| 3806 |
mapping_metadata = (
|
| 3807 |
surface_mapping["metadata"]
|
|
@@ -3855,8 +4209,11 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3855 |
surface_mapping_elapsed * 1000,
|
| 3856 |
)
|
| 3857 |
|
| 3858 |
-
|
| 3859 |
-
|
|
|
|
|
|
|
|
|
|
| 3860 |
shade_map = None
|
| 3861 |
showroom_shade_map = None
|
| 3862 |
reflection_map = None
|
|
@@ -3866,18 +4223,26 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3866 |
if intrinsic_models is None:
|
| 3867 |
_load_intrinsic_model()
|
| 3868 |
if intrinsic_models is not None:
|
| 3869 |
-
lighting_maps = build_intrinsic_lighting_maps(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3870 |
if lighting_maps and lighting_maps.get("shadeMap") is not None:
|
| 3871 |
lighting_source = f"intrinsic-{INTRINSIC_MODEL_VERSION}"
|
| 3872 |
intrinsic_lighting_used = True
|
| 3873 |
if ENABLE_SHADING_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
|
| 3874 |
-
lighting_maps = build_luminance_lighting_maps(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3875 |
if lighting_maps and lighting_maps.get("shadeMap") is not None:
|
| 3876 |
lighting_source = "luminance"
|
| 3877 |
-
if lighting_maps:
|
| 3878 |
-
shade_map = lighting_maps.get("shadeMap")
|
| 3879 |
-
showroom_shade_map = lighting_maps.get("showroomShadeMap")
|
| 3880 |
-
reflection_map = lighting_maps.get("reflectionMap")
|
| 3881 |
shade_statistics = lighting_map_statistics(shade_map, surface_mask)
|
| 3882 |
lighting_elapsed = time.perf_counter() - t0
|
| 3883 |
print(
|
|
@@ -3904,9 +4269,18 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3904 |
"shadingAvailable": shade_map is not None,
|
| 3905 |
"reflectionsAvailable": reflection_map is not None,
|
| 3906 |
},
|
| 3907 |
-
lighting_elapsed * 1000,
|
| 3908 |
-
)
|
| 3909 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3910 |
t0 = time.perf_counter()
|
| 3911 |
direction_transform = (
|
| 3912 |
plane.get("floorTransform")
|
|
@@ -3922,7 +4296,6 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3922 |
surface_mapping,
|
| 3923 |
use_surface_uv=use_surface_uv,
|
| 3924 |
)
|
| 3925 |
-
wall_mask = np.isin(seg_map, class_ids({"wall"})).astype(np.uint8)
|
| 3926 |
structure_mask = np.isin(
|
| 3927 |
seg_map,
|
| 3928 |
class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}),
|
|
@@ -3966,14 +4339,17 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 3966 |
[("Direction analysis", debug_floor_direction_overlay(img_np, floor_direction))],
|
| 3967 |
floor_direction,
|
| 3968 |
floor_direction_elapsed * 1000,
|
| 3969 |
-
)
|
| 3970 |
-
|
| 3971 |
-
|
|
|
|
|
|
|
|
|
|
| 3972 |
segments = []
|
| 3973 |
models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
|
| 3974 |
|
| 3975 |
-
if len(surface_indices) >= min_floor_area:
|
| 3976 |
-
segments.append({
|
| 3977 |
"id": 0,
|
| 3978 |
"className": "floor",
|
| 3979 |
"mask": base64.b64encode(surface_indices.tobytes()).decode(),
|
|
@@ -4007,6 +4383,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 4007 |
"segmentationModel": models["segmentation"]["name"],
|
| 4008 |
"floorPixels": int(floor_mask.sum()),
|
| 4009 |
"surfacePixels": int(surface_mask.sum()),
|
|
|
|
| 4010 |
"occlusionPixels": int(occlusion_mask.sum()),
|
| 4011 |
"floorDirection": floor_direction,
|
| 4012 |
**sam_metadata,
|
|
@@ -4044,8 +4421,65 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 4044 |
"metricGeometry": bool(plane and plane.get("floorTransform")),
|
| 4045 |
"geometryProvider": plane.get("geometryProvider", geometry.get("provider")) if plane else geometry.get("provider"),
|
| 4046 |
"geometryModel": models["geometry"]["name"],
|
| 4047 |
-
},
|
| 4048 |
-
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4049 |
|
| 4050 |
if not segments:
|
| 4051 |
flat_seg = seg_map.ravel()
|
|
@@ -4074,7 +4508,9 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 4074 |
},
|
| 4075 |
})
|
| 4076 |
|
| 4077 |
-
|
|
|
|
|
|
|
| 4078 |
print(f"[TIMING] Total bundle processing completed in {total_elapsed:.3f} seconds", flush=True)
|
| 4079 |
if debug is not None:
|
| 4080 |
debug.complete(total_elapsed * 1000)
|
|
@@ -4099,8 +4535,97 @@ def read_job(job_id: str):
|
|
| 4099 |
return json.loads(path.read_text())
|
| 4100 |
|
| 4101 |
|
| 4102 |
-
def write_job(job: dict):
|
| 4103 |
-
job_path(job["id"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4104 |
|
| 4105 |
|
| 4106 |
def spaces_upload_enabled() -> bool:
|
|
@@ -5025,34 +5550,86 @@ def run_qa_task(run_id: str, image_keys: list[str], tiles: list[str], descriptio
|
|
| 5025 |
|
| 5026 |
|
| 5027 |
def run_conversion_task(job_id: str, upload_path: Path):
|
| 5028 |
-
debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
|
| 5029 |
-
|
| 5030 |
-
|
| 5031 |
-
|
| 5032 |
-
|
| 5033 |
-
|
| 5034 |
-
|
| 5035 |
-
|
| 5036 |
-
|
| 5037 |
-
|
| 5038 |
-
|
| 5039 |
-
|
| 5040 |
-
|
| 5041 |
-
|
| 5042 |
-
|
| 5043 |
-
|
| 5044 |
-
|
| 5045 |
-
|
| 5046 |
-
|
| 5047 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5048 |
print(f"Background conversion failed: {exc}", flush=True)
|
| 5049 |
if debug is not None:
|
| 5050 |
debug.fail(exc)
|
| 5051 |
try:
|
| 5052 |
-
job = read_job(job_id)
|
| 5053 |
-
job["status"] = "FAILED"
|
| 5054 |
-
job["
|
| 5055 |
-
|
|
|
|
|
|
|
| 5056 |
except Exception:
|
| 5057 |
pass
|
| 5058 |
|
|
@@ -5380,10 +5957,18 @@ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile =
|
|
| 5380 |
upload_path = UPLOAD_DIR / f"{job_id}{ext}"
|
| 5381 |
upload_path.write_bytes(normalized_contents)
|
| 5382 |
|
| 5383 |
-
job = {
|
| 5384 |
-
"id": job_id,
|
| 5385 |
-
"status": "
|
| 5386 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5387 |
"outputUrl": f"/viz2d/jobs/{job_id}/file",
|
| 5388 |
"debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None,
|
| 5389 |
}
|
|
|
|
| 9 |
import shutil
|
| 10 |
import subprocess
|
| 11 |
import time
|
| 12 |
+
import threading
|
| 13 |
import urllib.error
|
| 14 |
import urllib.parse
|
| 15 |
import urllib.request
|
|
|
|
| 199 |
"enable_plane_fit",
|
| 200 |
"1",
|
| 201 |
)).lower() in {"1", "true", "yes", "on"}
|
| 202 |
+
ENABLE_MULTI_PLANE_SURFACES = str(config_value(
|
| 203 |
"ENABLE_MULTI_PLANE_SURFACES",
|
| 204 |
"runtime",
|
| 205 |
"enable_multi_plane_surfaces",
|
| 206 |
"1",
|
| 207 |
+
)).lower() in {"1", "true", "yes", "on"}
|
| 208 |
+
ENABLE_WALL_SEGMENTS = str(config_value(
|
| 209 |
+
"ENABLE_WALL_SEGMENTS",
|
| 210 |
+
"runtime",
|
| 211 |
+
"enable_wall_segments",
|
| 212 |
+
"1",
|
| 213 |
+
)).lower() in {"1", "true", "yes", "on"}
|
| 214 |
INTRINSIC_MODEL_VERSION = str(config_value(
|
| 215 |
"INTRINSIC_MODEL_VERSION",
|
| 216 |
"models",
|
|
|
|
| 265 |
"debug_artifacts_enabled",
|
| 266 |
"1",
|
| 267 |
)).lower() in {"1", "true", "yes", "on"}
|
| 268 |
+
CONVERSION_TARGET_MS = max(5_000, int(config_value(
|
| 269 |
+
"CONVERSION_TARGET_MS",
|
| 270 |
+
"runtime",
|
| 271 |
+
"conversion_target_ms",
|
| 272 |
+
"30000",
|
| 273 |
+
)))
|
| 274 |
+
DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value(
|
| 275 |
"DEBUG_ARTIFACTS_MAX_DIMENSION",
|
| 276 |
"runtime",
|
| 277 |
"debug_artifacts_max_dimension",
|
|
|
|
| 524 |
sam2_predictor = None
|
| 525 |
intrinsic_models = None
|
| 526 |
|
| 527 |
+
LIGHTING_TRANSFER_VERSION = 4
|
| 528 |
SHADE_MAP_MIN = 0.08
|
| 529 |
SHADE_MAP_MAX = 1.85
|
| 530 |
SHOWROOM_SHADE_MAP_MIN = 0.85
|
|
|
|
| 730 |
JOB_DIR.mkdir(parents=True, exist_ok=True)
|
| 731 |
MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
|
| 732 |
QA_RUN_DIR.mkdir(parents=True, exist_ok=True)
|
| 733 |
+
TIMING_BASELINE_PATH = DATA_DIR / "conversion-timings.json"
|
| 734 |
app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
|
| 735 |
|
| 736 |
|
|
|
|
| 1036 |
self._write_manifest()
|
| 1037 |
|
| 1038 |
PRIMARY_FLOOR_CLASSES = {"floor", "rug", "carpet", "mat"}
|
| 1039 |
+
REPLACEABLE_SOFT_FLOOR_CLASSES = {"rug", "carpet", "mat"}
|
| 1040 |
FLOOR_SURFACE_CLASSES = {
|
| 1041 |
"floor", "road", "sidewalk", "ground", "field", "grass", "sand",
|
| 1042 |
"runway", "dirt track", "land", "stairs", "step", "rug", "carpet", "mat",
|
|
|
|
| 1433 |
return build_showroom_shade_map_from_relative(relative, surface_mask)
|
| 1434 |
|
| 1435 |
|
| 1436 |
+
def build_reflection_map(
|
| 1437 |
+
img_np: np.ndarray,
|
| 1438 |
+
surface_mask: np.ndarray,
|
| 1439 |
+
relative_shading: np.ndarray | None = None,
|
| 1440 |
+
replaced_material_mask: np.ndarray | None = None,
|
| 1441 |
+
) -> np.ndarray | None:
|
| 1442 |
if not surface_mask.any():
|
| 1443 |
return None
|
| 1444 |
|
| 1445 |
+
mask = surface_mask.astype(np.uint8)
|
| 1446 |
+
h, w = mask.shape[:2]
|
| 1447 |
+
reflection_candidates: list[np.ndarray] = []
|
| 1448 |
+
min_side = min(h, w)
|
| 1449 |
+
|
| 1450 |
+
# High-pass filtering before removing a rug or carpet creates a bright halo
|
| 1451 |
+
# just outside its mask. Exclude a scale-aware feather around replaced
|
| 1452 |
+
# material, and a narrow surface boundary, before extracting reflections.
|
| 1453 |
+
boundary_radius = max(1, int(round(min_side / 320.0)))
|
| 1454 |
+
boundary_kernel = cv2.getStructuringElement(
|
| 1455 |
+
cv2.MORPH_ELLIPSE,
|
| 1456 |
+
(boundary_radius * 2 + 1, boundary_radius * 2 + 1),
|
| 1457 |
+
)
|
| 1458 |
+
reflection_surface = cv2.erode(mask, boundary_kernel) > 0
|
| 1459 |
+
replacement_exclusion = np.zeros((h, w), dtype=bool)
|
| 1460 |
+
if replaced_material_mask is not None and replaced_material_mask.shape[:2] == (h, w):
|
| 1461 |
+
replacement = ((replaced_material_mask > 0) & (mask > 0)).astype(np.uint8)
|
| 1462 |
+
if replacement.any():
|
| 1463 |
+
replacement_radius = max(3, int(round(min_side / 80.0)))
|
| 1464 |
+
replacement_kernel = cv2.getStructuringElement(
|
| 1465 |
+
cv2.MORPH_ELLIPSE,
|
| 1466 |
+
(replacement_radius * 2 + 1, replacement_radius * 2 + 1),
|
| 1467 |
+
)
|
| 1468 |
+
replacement_exclusion = cv2.dilate(replacement, replacement_kernel) > 0
|
| 1469 |
+
reflection_surface &= ~replacement_exclusion
|
| 1470 |
+
|
| 1471 |
+
if relative_shading is not None:
|
| 1472 |
+
rel = relative_shading.astype(np.float32).copy()
|
| 1473 |
+
rel = suppress_replaced_material_lighting(
|
| 1474 |
+
rel,
|
| 1475 |
+
mask,
|
| 1476 |
+
replacement_exclusion.astype(np.uint8),
|
| 1477 |
+
)
|
| 1478 |
+
rel[mask == 0] = 1.0
|
| 1479 |
+
broad_sigma = max(6.0, min(h, w) / 44.0)
|
| 1480 |
+
broad = cv2.GaussianBlur(rel, (0, 0), sigmaX=broad_sigma, sigmaY=broad_sigma)
|
| 1481 |
+
detail = rel / np.maximum(broad, 1e-3)
|
| 1482 |
+
candidate = np.clip((detail - 1.05) / 0.30, 0.0, 1.0)
|
| 1483 |
+
broad_excess = np.clip((broad - 1.05) / 0.45, 0.0, 1.0)
|
| 1484 |
+
reflection_candidates.append(candidate * (1.0 - 0.75 * broad_excess))
|
| 1485 |
+
|
| 1486 |
+
luminance = image_luminance(img_np) / 255.0
|
| 1487 |
+
floor_values = luminance[mask > 0]
|
| 1488 |
floor_values = floor_values[np.isfinite(floor_values)]
|
| 1489 |
if floor_values.size >= max(256, int(h * w * 0.002)):
|
| 1490 |
+
median_lum = float(np.median(floor_values))
|
| 1491 |
+
if median_lum > 1e-3:
|
| 1492 |
+
filled = luminance / median_lum
|
| 1493 |
+
filled = suppress_replaced_material_lighting(
|
| 1494 |
+
filled,
|
| 1495 |
+
mask,
|
| 1496 |
+
replacement_exclusion.astype(np.uint8),
|
| 1497 |
+
)
|
| 1498 |
+
filled[mask == 0] = 1.0
|
| 1499 |
+
broad_sigma = max(8.0, min(h, w) / 36.0)
|
| 1500 |
+
broad = cv2.GaussianBlur(filled, (0, 0), sigmaX=broad_sigma, sigmaY=broad_sigma)
|
| 1501 |
+
detail = filled / np.maximum(broad, 1e-3)
|
| 1502 |
+
candidate = np.clip((detail - 1.08) / 0.30, 0.0, 1.0)
|
| 1503 |
+
broad_excess = np.clip((broad - 1.05) / 0.45, 0.0, 1.0)
|
| 1504 |
+
reflection_candidates.append(candidate * (1.0 - 0.75 * broad_excess))
|
| 1505 |
|
| 1506 |
if not reflection_candidates:
|
| 1507 |
return None
|
|
|
|
| 1509 |
# A reflection is additive light. Dark source-floor detail belongs to the
|
| 1510 |
# illumination map; transferring it here would turn old material color or
|
| 1511 |
# texture into an artificial dark reflection on the replacement material.
|
| 1512 |
+
reflection = np.maximum.reduce(reflection_candidates).astype(np.float32)
|
| 1513 |
+
if min(h, w) > 120:
|
| 1514 |
+
sigma = max(0.6, min(h, w) / 520.0)
|
| 1515 |
+
reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 1516 |
+
reflection = np.clip(reflection, REFLECTION_MAP_MIN, min(REFLECTION_MAP_MAX, 0.55))
|
| 1517 |
+
reflection[~reflection_surface] = 0.0
|
| 1518 |
if float(np.max(np.abs(reflection[mask > 0]))) < 0.025:
|
| 1519 |
return None
|
| 1520 |
encoded = (reflection - REFLECTION_MAP_MIN) / (REFLECTION_MAP_MAX - REFLECTION_MAP_MIN)
|
| 1521 |
+
return np.round(encoded * 255.0).clip(0, 255).astype(np.uint8)
|
| 1522 |
+
|
| 1523 |
+
|
| 1524 |
+
def suppress_replaced_material_lighting(
|
| 1525 |
+
relative: np.ndarray,
|
| 1526 |
+
surface_mask: np.ndarray,
|
| 1527 |
+
replaced_material_mask: np.ndarray | None,
|
| 1528 |
+
) -> np.ndarray:
|
| 1529 |
+
"""Replace rug/carpet appearance with lighting extrapolated from nearby hard floor."""
|
| 1530 |
+
if replaced_material_mask is None or replaced_material_mask.shape != surface_mask.shape:
|
| 1531 |
+
return relative
|
| 1532 |
+
|
| 1533 |
+
replacement = (replaced_material_mask > 0) & (surface_mask > 0)
|
| 1534 |
+
if not replacement.any():
|
| 1535 |
+
return relative
|
| 1536 |
+
|
| 1537 |
+
known_surface = (surface_mask > 0) & (~replacement)
|
| 1538 |
+
known_values = relative[known_surface]
|
| 1539 |
+
known_values = known_values[np.isfinite(known_values) & (known_values > 1e-6)]
|
| 1540 |
+
output = relative.astype(np.float32).copy()
|
| 1541 |
+
if known_values.size < 64:
|
| 1542 |
+
output[replacement] = 1.0
|
| 1543 |
+
output[surface_mask == 0] = 1.0
|
| 1544 |
+
return output
|
| 1545 |
+
|
| 1546 |
+
median = float(np.median(known_values))
|
| 1547 |
+
source = output.copy()
|
| 1548 |
+
source[~np.isfinite(source)] = median
|
| 1549 |
+
source[surface_mask == 0] = median
|
| 1550 |
+
radius = max(3.0, min(surface_mask.shape[:2]) / 120.0)
|
| 1551 |
+
extrapolated = cv2.inpaint(
|
| 1552 |
+
source.astype(np.float32),
|
| 1553 |
+
replacement.astype(np.uint8),
|
| 1554 |
+
radius,
|
| 1555 |
+
cv2.INPAINT_TELEA,
|
| 1556 |
+
)
|
| 1557 |
+
sigma = max(8.0, min(surface_mask.shape[:2]) / 48.0)
|
| 1558 |
+
extrapolated = masked_gaussian_blur(extrapolated, surface_mask, sigma)
|
| 1559 |
+
output[replacement] = extrapolated[replacement]
|
| 1560 |
+
output = np.clip(output, SHADE_MAP_MIN, 1.65)
|
| 1561 |
+
output[surface_mask == 0] = 1.0
|
| 1562 |
+
return output
|
| 1563 |
+
|
| 1564 |
+
|
| 1565 |
+
def build_luminance_lighting_maps(
|
| 1566 |
+
img_np: np.ndarray,
|
| 1567 |
+
surface_mask: np.ndarray,
|
| 1568 |
+
replaced_material_mask: np.ndarray | None = None,
|
| 1569 |
+
) -> dict[str, np.ndarray | None] | None:
|
| 1570 |
if not surface_mask.any():
|
| 1571 |
return None
|
| 1572 |
|
|
|
|
| 1585 |
|
| 1586 |
relative = filled / median_lum
|
| 1587 |
relative[~np.isfinite(relative)] = 1.0
|
| 1588 |
+
relative = suppress_replaced_material_lighting(
|
| 1589 |
+
relative,
|
| 1590 |
+
mask,
|
| 1591 |
+
replaced_material_mask,
|
| 1592 |
+
)
|
| 1593 |
shade = smooth_relative_lighting(relative, mask)
|
| 1594 |
if shade is None:
|
| 1595 |
return None
|
| 1596 |
+
return {
|
| 1597 |
+
"shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX),
|
| 1598 |
+
"showroomShadeMap": build_showroom_shade_map_from_relative(shade, mask),
|
| 1599 |
+
"reflectionMap": build_reflection_map(
|
| 1600 |
+
img_np,
|
| 1601 |
+
surface_mask,
|
| 1602 |
+
None,
|
| 1603 |
+
replaced_material_mask,
|
| 1604 |
+
),
|
| 1605 |
}
|
| 1606 |
|
| 1607 |
|
|
|
|
| 1810 |
|
| 1811 |
|
| 1812 |
def build_intrinsic_lighting_maps(
|
| 1813 |
+
img_np: np.ndarray,
|
| 1814 |
+
surface_mask: np.ndarray,
|
| 1815 |
+
replaced_material_mask: np.ndarray | None = None,
|
| 1816 |
+
) -> dict[str, np.ndarray | None] | None:
|
| 1817 |
if not surface_mask.any() or intrinsic_models is None:
|
| 1818 |
return None
|
| 1819 |
|
|
|
|
| 1833 |
if smoothed is None:
|
| 1834 |
return None
|
| 1835 |
|
| 1836 |
+
luminance_maps = build_luminance_lighting_maps(
|
| 1837 |
+
img_np,
|
| 1838 |
+
surface_mask,
|
| 1839 |
+
replaced_material_mask,
|
| 1840 |
+
)
|
| 1841 |
if luminance_maps and luminance_maps.get("shadeMap") is not None:
|
| 1842 |
observed = decode_relative_map(
|
| 1843 |
luminance_maps["shadeMap"],
|
|
|
|
| 1846 |
)
|
| 1847 |
smoothed = preserve_observed_lighting(smoothed, observed, surface_mask)
|
| 1848 |
alignment = f"{alignment}+observed-lighting"
|
| 1849 |
+
smoothed = suppress_replaced_material_lighting(
|
| 1850 |
+
smoothed,
|
| 1851 |
+
surface_mask,
|
| 1852 |
+
replaced_material_mask,
|
| 1853 |
+
)
|
| 1854 |
print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True)
|
| 1855 |
|
| 1856 |
return {
|
| 1857 |
"shadeMap": encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX),
|
| 1858 |
"showroomShadeMap": build_showroom_shade_map_from_relative(smoothed, surface_mask),
|
| 1859 |
+
"reflectionMap": build_reflection_map(
|
| 1860 |
+
img_np,
|
| 1861 |
+
surface_mask,
|
| 1862 |
+
smoothed,
|
| 1863 |
+
replaced_material_mask,
|
| 1864 |
+
),
|
| 1865 |
}
|
| 1866 |
except Exception as exc:
|
| 1867 |
print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
|
|
|
|
| 2306 |
return projected.astype(np.float32), signed_distance.astype(np.float32)
|
| 2307 |
|
| 2308 |
|
| 2309 |
+
def fit_metric_floor_transform(
|
| 2310 |
+
mask: np.ndarray,
|
| 2311 |
+
points_map: np.ndarray,
|
| 2312 |
+
valid_mask: np.ndarray | None = None,
|
| 2313 |
+
normals_map: np.ndarray | None = None,
|
| 2314 |
+
intrinsics: np.ndarray | None = None,
|
| 2315 |
+
provider: str = "metric-depth",
|
| 2316 |
+
surface_kind: str = "floor",
|
| 2317 |
+
):
|
| 2318 |
h, w = mask.shape[:2]
|
| 2319 |
valid = (mask > 0) & np.isfinite(points_map).all(axis=2) & (points_map[:, :, 2] > 0.05)
|
| 2320 |
if valid_mask is not None:
|
|
|
|
| 2370 |
if inlier_ratio < 0.45 or residual > 0.18:
|
| 2371 |
return None
|
| 2372 |
|
| 2373 |
+
# Use local horizontal/vertical axes for walls and horizontal/depth axes
|
| 2374 |
+
# for floors. This keeps physical tile dimensions stable across surfaces.
|
| 2375 |
+
u_axis, v_axis = plane_basis(normal, is_floor=surface_kind != "wall")
|
| 2376 |
+
|
| 2377 |
+
projected_points, _ = project_points_to_plane(points[keep], centroid, normal)
|
| 2378 |
+
floor_points = projected_points - centroid
|
| 2379 |
+
uv = np.column_stack((floor_points @ u_axis, floor_points @ v_axis)).astype(np.float32)
|
| 2380 |
+
uv_min = np.min(uv, axis=0)
|
| 2381 |
+
uv_max = np.max(uv, axis=0)
|
|
|
|
|
|
|
| 2382 |
image_points = np.column_stack((xs[keep], ys[keep])).astype(np.float32)
|
| 2383 |
transform, ransac_mask = cv2.findHomography(
|
| 2384 |
image_points,
|
|
|
|
| 2406 |
else None
|
| 2407 |
)
|
| 2408 |
|
| 2409 |
+
return {
|
| 2410 |
+
"floorTransform": transform.flatten().tolist(),
|
| 2411 |
+
"surfaceTransform": transform.flatten().tolist(),
|
| 2412 |
+
"surfaceType": surface_kind,
|
| 2413 |
+
"surfaceUAxis": u_axis.tolist(),
|
| 2414 |
+
"surfaceVAxis": v_axis.tolist(),
|
| 2415 |
+
"surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)),
|
| 2416 |
+
"surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)),
|
| 2417 |
"metersPerUnit": 1.0,
|
| 2418 |
"geometryConfidence": confidence,
|
| 2419 |
"geometryProvider": provider,
|
|
|
|
| 2435 |
}
|
| 2436 |
|
| 2437 |
|
| 2438 |
+
def estimate_metric_floor_transform(
|
| 2439 |
+
mask: np.ndarray,
|
| 2440 |
+
depth: np.ndarray | None,
|
| 2441 |
+
provider: str = "depth-anything",
|
| 2442 |
+
intrinsics: np.ndarray | None = None,
|
| 2443 |
+
surface_kind: str = "floor",
|
| 2444 |
+
):
|
| 2445 |
if depth is None or not ENABLE_PLANE_FIT:
|
| 2446 |
return None
|
| 2447 |
h, w = mask.shape[:2]
|
|
|
|
| 2449 |
depth_for_points, depth_scale = prepare_depth_for_backprojection(depth, mask, is_metric_depth)
|
| 2450 |
pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h)
|
| 2451 |
points = backproject_depth(depth_for_points, pixel_intrinsics)
|
| 2452 |
+
result = fit_metric_floor_transform(
|
| 2453 |
+
mask,
|
| 2454 |
+
points,
|
| 2455 |
+
intrinsics=pixel_intrinsics,
|
| 2456 |
+
provider=provider,
|
| 2457 |
+
surface_kind=surface_kind,
|
| 2458 |
+
)
|
| 2459 |
if result is not None:
|
| 2460 |
result["depthScale"] = depth_scale
|
| 2461 |
return result
|
|
|
|
| 2854 |
if coverage < SURFACE_UV_MIN_COVERAGE:
|
| 2855 |
quality["textureMappingReason"] = "incomplete-surface-uv"
|
| 2856 |
return quality
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2857 |
h, w = surface_mask.shape[:2]
|
| 2858 |
uv_grid = np.full((h * w, 2), np.nan, dtype=np.float32)
|
| 2859 |
plane_grid = np.full(h * w, 255, dtype=np.uint8)
|
|
|
|
| 2904 |
if bad_ratio > SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO:
|
| 2905 |
quality["textureMappingReason"] = "noisy-surface-uv"
|
| 2906 |
return quality
|
| 2907 |
+
quality["surfaceUvEnabled"] = True
|
| 2908 |
+
quality["textureMappingMode"] = "surface-uv"
|
| 2909 |
+
quality["textureMappingReason"] = (
|
| 2910 |
+
"surface-uv-quality-ok"
|
| 2911 |
+
if len(active_plane_ids) <= 1
|
| 2912 |
+
else "multi-plane-surface-uv-quality-ok"
|
| 2913 |
+
)
|
| 2914 |
return quality
|
| 2915 |
|
| 2916 |
|
|
|
|
| 3017 |
plane_ids[assigned_positions] = plane_idx
|
| 3018 |
plane["assignedCount"] = int(assigned_keep.sum())
|
| 3019 |
|
| 3020 |
+
serializable_planes = []
|
| 3021 |
+
for plane in planes:
|
| 3022 |
+
assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])]
|
| 3023 |
+
assigned_plane_uv = assigned_plane_uv[np.isfinite(assigned_plane_uv).all(axis=1)]
|
| 3024 |
+
if len(assigned_plane_uv):
|
| 3025 |
+
uv_min = np.min(assigned_plane_uv, axis=0)
|
| 3026 |
+
uv_max = np.max(assigned_plane_uv, axis=0)
|
| 3027 |
+
else:
|
| 3028 |
+
uv_min = np.zeros(2, dtype=np.float32)
|
| 3029 |
+
uv_max = np.ones(2, dtype=np.float32)
|
| 3030 |
+
serializable_planes.append({
|
| 3031 |
"id": int(plane["id"]),
|
| 3032 |
"normal": plane["normal"].astype(float).tolist(),
|
| 3033 |
"origin": plane["origin"].astype(float).tolist(),
|
|
|
|
| 3037 |
"inlierCount": int(plane["inlierCount"]),
|
| 3038 |
"assignedCount": int(plane.get("assignedCount", 0)),
|
| 3039 |
"isFloor": bool(plane["isFloor"]),
|
| 3040 |
+
"fitMode": str(plane.get("fitMode", "normal-aware")),
|
| 3041 |
+
"uvMin": uv_min.astype(float).tolist(),
|
| 3042 |
+
"uvMax": uv_max.astype(float).tolist(),
|
| 3043 |
+
"uvWidth": float(max(uv_max[0] - uv_min[0], 0.05)),
|
| 3044 |
+
"uvHeight": float(max(uv_max[1] - uv_min[1], 0.05)),
|
| 3045 |
+
})
|
| 3046 |
|
| 3047 |
finite_uv = np.isfinite(uv_by_mask).all(axis=1)
|
| 3048 |
uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids)
|
|
|
|
| 3070 |
}
|
| 3071 |
|
| 3072 |
|
| 3073 |
+
def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray, geometry: dict | None = None):
|
| 3074 |
ys, xs = np.where(mask > 0)
|
| 3075 |
if len(xs) < 1000:
|
| 3076 |
return None, None
|
|
|
|
| 3177 |
"confidence": 0.25 if vanishing_point is not None else 0.1,
|
| 3178 |
},
|
| 3179 |
})
|
| 3180 |
+
return homography, plane
|
| 3181 |
+
|
| 3182 |
+
|
| 3183 |
+
def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
|
| 3184 |
+
"""Return a stable image-space homography for a semantic wall mask.
|
| 3185 |
+
|
| 3186 |
+
Walls do not currently have metric depth fitting, so use the visible wall
|
| 3187 |
+
contour as the source quad and its bounding rectangle as the planar target.
|
| 3188 |
+
This preserves perspective convergence while keeping physical tile sizes
|
| 3189 |
+
deterministic until wall-specific depth calibration is available.
|
| 3190 |
+
"""
|
| 3191 |
+
ys, xs = np.where(mask > 0)
|
| 3192 |
+
if len(xs) < 1000:
|
| 3193 |
+
return None, None
|
| 3194 |
+
|
| 3195 |
+
h, w = mask.shape[:2]
|
| 3196 |
+
contours, _ = cv2.findContours((mask > 0).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 3197 |
+
contour = max(contours, key=cv2.contourArea) if contours else None
|
| 3198 |
+
if contour is None or cv2.contourArea(contour) < 1000:
|
| 3199 |
+
return None, None
|
| 3200 |
+
|
| 3201 |
+
perimeter = cv2.arcLength(contour, True)
|
| 3202 |
+
approx = cv2.approxPolyDP(contour, max(2.0, perimeter * 0.02), True)
|
| 3203 |
+
if len(approx) >= 4:
|
| 3204 |
+
points = approx.reshape(-1, 2).astype(np.float32)
|
| 3205 |
+
hull = cv2.convexHull(points)
|
| 3206 |
+
if len(hull) >= 4:
|
| 3207 |
+
points = hull.reshape(-1, 2)
|
| 3208 |
+
else:
|
| 3209 |
+
points = np.empty((0, 2), dtype=np.float32)
|
| 3210 |
+
|
| 3211 |
+
if len(points) != 4:
|
| 3212 |
+
rect = cv2.minAreaRect(contour)
|
| 3213 |
+
points = cv2.boxPoints(rect).astype(np.float32)
|
| 3214 |
+
|
| 3215 |
+
# Order corners as top-left, top-right, bottom-right, bottom-left.
|
| 3216 |
+
sums = points.sum(axis=1)
|
| 3217 |
+
diffs = points[:, 1] - points[:, 0]
|
| 3218 |
+
ordered = np.float32([
|
| 3219 |
+
points[np.argmin(sums)],
|
| 3220 |
+
points[np.argmin(diffs)],
|
| 3221 |
+
points[np.argmax(sums)],
|
| 3222 |
+
points[np.argmax(diffs)],
|
| 3223 |
+
])
|
| 3224 |
+
x1, y1 = float(np.min(ordered[:, 0])), float(np.min(ordered[:, 1]))
|
| 3225 |
+
x2, y2 = float(np.max(ordered[:, 0])), float(np.max(ordered[:, 1]))
|
| 3226 |
+
if x2 - x1 < 20 or y2 - y1 < 20:
|
| 3227 |
+
return None, None
|
| 3228 |
+
|
| 3229 |
+
destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
|
| 3230 |
+
homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
|
| 3231 |
+
metric_geometry = None
|
| 3232 |
+
if ENABLE_PLANE_FIT and geometry:
|
| 3233 |
+
points = geometry.get("points")
|
| 3234 |
+
if points is not None:
|
| 3235 |
+
metric_geometry = fit_metric_floor_transform(
|
| 3236 |
+
mask,
|
| 3237 |
+
points,
|
| 3238 |
+
geometry.get("validMask"),
|
| 3239 |
+
geometry.get("normals"),
|
| 3240 |
+
geometry.get("intrinsics"),
|
| 3241 |
+
geometry.get("provider", "metric-depth"),
|
| 3242 |
+
surface_kind="wall",
|
| 3243 |
+
)
|
| 3244 |
+
if metric_geometry is None:
|
| 3245 |
+
metric_geometry = estimate_metric_floor_transform(
|
| 3246 |
+
mask,
|
| 3247 |
+
geometry.get("depth"),
|
| 3248 |
+
geometry.get("provider", "depth-anything"),
|
| 3249 |
+
geometry.get("intrinsics"),
|
| 3250 |
+
surface_kind="wall",
|
| 3251 |
+
)
|
| 3252 |
+
|
| 3253 |
+
plane = {
|
| 3254 |
+
"x": x1,
|
| 3255 |
+
"y": y1,
|
| 3256 |
+
"width": x2 - x1,
|
| 3257 |
+
"height": y2 - y1,
|
| 3258 |
+
"quad": ordered.flatten().tolist(),
|
| 3259 |
+
"geometryConfidence": 0.45,
|
| 3260 |
+
"geometryProvider": "wall-contour-homography",
|
| 3261 |
+
"floorTransform": None,
|
| 3262 |
+
"surfaceTransform": None,
|
| 3263 |
+
"surfaceType": "wall",
|
| 3264 |
+
"surfaceWidthMeters": max(0.5, 2.4 * (x2 - x1) / max(y2 - y1, 1.0)),
|
| 3265 |
+
"surfaceHeightMeters": 2.4,
|
| 3266 |
+
"metersPerUnit": None,
|
| 3267 |
+
"cameraIntrinsics": None,
|
| 3268 |
+
"camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
|
| 3269 |
+
}
|
| 3270 |
+
if metric_geometry and not validate_wall_metric_geometry(metric_geometry):
|
| 3271 |
+
print(
|
| 3272 |
+
"[WALL_GEOMETRY] rejected metric wall fit; using contour homography "
|
| 3273 |
+
f"confidence={metric_geometry.get('geometryConfidence')} "
|
| 3274 |
+
f"normal={metric_geometry.get('planeNormal')} "
|
| 3275 |
+
f"size={metric_geometry.get('surfaceWidthMeters')}x{metric_geometry.get('surfaceHeightMeters')}",
|
| 3276 |
+
flush=True,
|
| 3277 |
+
)
|
| 3278 |
+
metric_geometry = None
|
| 3279 |
+
|
| 3280 |
+
if metric_geometry:
|
| 3281 |
+
plane.update(metric_geometry)
|
| 3282 |
+
plane["surfaceType"] = "wall"
|
| 3283 |
+
plane["geometryProvider"] = metric_geometry.get("geometryProvider", "wall-depth")
|
| 3284 |
+
return homography, plane
|
| 3285 |
+
|
| 3286 |
+
|
| 3287 |
+
def validate_wall_metric_geometry(geometry: dict) -> bool:
|
| 3288 |
+
confidence = float(geometry.get("geometryConfidence") or 0.0)
|
| 3289 |
+
normal = np.asarray(geometry.get("planeNormal") or [], dtype=np.float32)
|
| 3290 |
+
width = float(geometry.get("surfaceWidthMeters") or 0.0)
|
| 3291 |
+
height = float(geometry.get("surfaceHeightMeters") or 0.0)
|
| 3292 |
+
if confidence < 0.45 or normal.shape != (3,) or not np.isfinite(normal).all():
|
| 3293 |
+
return False
|
| 3294 |
+
# In the indoor coordinate system Y is vertical; a wall normal should be
|
| 3295 |
+
# mostly horizontal, unlike the floor normal.
|
| 3296 |
+
normal /= max(float(np.linalg.norm(normal)), 1e-6)
|
| 3297 |
+
if abs(float(normal[1])) > 0.45:
|
| 3298 |
+
return False
|
| 3299 |
+
if not (0.25 <= width <= 30.0 and 0.25 <= height <= 15.0):
|
| 3300 |
+
return False
|
| 3301 |
+
if width / max(height, 1e-6) > 20.0 or height / max(width, 1e-6) > 20.0:
|
| 3302 |
+
return False
|
| 3303 |
+
return True
|
| 3304 |
+
|
| 3305 |
+
|
| 3306 |
+
def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None):
|
| 3307 |
+
"""Create clean, independently renderable wall regions.
|
| 3308 |
+
|
| 3309 |
+
Semantic wall predictions often bridge across corners and openings. Removing
|
| 3310 |
+
protected classes before connected-component analysis prevents one warped
|
| 3311 |
+
transform from being applied to several physically different walls.
|
| 3312 |
+
"""
|
| 3313 |
+
wall = np.isin(seg_map, class_ids({"wall"})).astype(np.uint8)
|
| 3314 |
+
protected = np.isin(seg_map, class_ids(OCCLUDER_CLASSES | {
|
| 3315 |
+
"door", "window", "column", "base", "railing", "ceiling",
|
| 3316 |
+
"building", "painting", "mirror", "curtain",
|
| 3317 |
+
})).astype(np.uint8)
|
| 3318 |
+
radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
|
| 3319 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
|
| 3320 |
+
protected = cv2.dilate(protected, kernel, iterations=1)
|
| 3321 |
+
wall[protected > 0] = 0
|
| 3322 |
+
wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel)
|
| 3323 |
+
wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
|
| 3324 |
+
wall[protected > 0] = 0
|
| 3325 |
+
|
| 3326 |
+
components = []
|
| 3327 |
+
if geometry is not None:
|
| 3328 |
+
maps = geometry_point_maps(wall, geometry)
|
| 3329 |
+
if maps is not None:
|
| 3330 |
+
valid = maps["validMask"] & (wall > 0)
|
| 3331 |
+
ys, xs = np.where(valid)
|
| 3332 |
+
if len(xs) >= SURFACE_MIN_PLANE_PIXELS:
|
| 3333 |
+
points = maps["points"][ys, xs].astype(np.float32)
|
| 3334 |
+
normals = maps["normals"][ys, xs].astype(np.float32)
|
| 3335 |
+
finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1)
|
| 3336 |
+
points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite]
|
| 3337 |
+
if len(points) >= SURFACE_MIN_PLANE_PIXELS:
|
| 3338 |
+
normals_reliable = np.linalg.norm(normals, axis=1) > 1e-4
|
| 3339 |
+
if normals_reliable.sum() >= SURFACE_MIN_PLANE_PIXELS:
|
| 3340 |
+
points = points[normals_reliable]
|
| 3341 |
+
normals = normalize_vectors(normals[normals_reliable])
|
| 3342 |
+
ys, xs = ys[normals_reliable], xs[normals_reliable]
|
| 3343 |
+
planes = fit_multi_surface_planes(points, normals, True)
|
| 3344 |
+
wall_planes = [
|
| 3345 |
+
plane for plane in planes
|
| 3346 |
+
if abs(float(plane["normal"][1])) <= 0.45
|
| 3347 |
+
]
|
| 3348 |
+
if wall_planes:
|
| 3349 |
+
assignment = assign_points_to_surface_planes(
|
| 3350 |
+
points, normals, wall_planes, True
|
| 3351 |
+
)
|
| 3352 |
+
for plane_index in range(len(wall_planes)):
|
| 3353 |
+
selected = assignment == plane_index
|
| 3354 |
+
if int(selected.sum()) < min_area:
|
| 3355 |
+
continue
|
| 3356 |
+
plane_mask = np.zeros_like(wall)
|
| 3357 |
+
plane_mask[ys[selected], xs[selected]] = 1
|
| 3358 |
+
count, labels, stats, _ = cv2.connectedComponentsWithStats(
|
| 3359 |
+
plane_mask, connectivity=8
|
| 3360 |
+
)
|
| 3361 |
+
for component_id in range(1, count):
|
| 3362 |
+
area = int(stats[component_id, cv2.CC_STAT_AREA])
|
| 3363 |
+
if area >= min_area:
|
| 3364 |
+
components.append((area, (labels == component_id).astype(np.uint8)))
|
| 3365 |
+
|
| 3366 |
+
# Geometry can be unavailable or too noisy. In that case retain the safe
|
| 3367 |
+
# semantic connected-component fallback instead of emitting no walls.
|
| 3368 |
+
if not components:
|
| 3369 |
+
count, labels, stats, _ = cv2.connectedComponentsWithStats(wall, connectivity=8)
|
| 3370 |
+
for component_id in range(1, count):
|
| 3371 |
+
area = int(stats[component_id, cv2.CC_STAT_AREA])
|
| 3372 |
+
if area < min_area:
|
| 3373 |
+
continue
|
| 3374 |
+
components.append((area, (labels == component_id).astype(np.uint8)))
|
| 3375 |
+
components.sort(key=lambda item: item[0], reverse=True)
|
| 3376 |
+
return components, protected
|
| 3377 |
|
| 3378 |
|
| 3379 |
def build_floor_surface_mask(
|
|
|
|
| 3979 |
return buffer.getvalue()
|
| 3980 |
|
| 3981 |
|
| 3982 |
+
def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None, progress_callback=None):
|
| 3983 |
t_start = time.perf_counter()
|
| 3984 |
|
| 3985 |
t0 = time.perf_counter()
|
|
|
|
| 3999 |
image_loading_elapsed * 1000,
|
| 4000 |
)
|
| 4001 |
|
| 4002 |
+
if progress_callback:
|
| 4003 |
+
progress_callback("segmentation", 0)
|
| 4004 |
+
t0 = time.perf_counter()
|
| 4005 |
+
seg_map = run_segmentation(img, img_np)
|
| 4006 |
segmentation_elapsed = time.perf_counter() - t0
|
| 4007 |
print(f"[TIMING] Floor segmentation took {segmentation_elapsed:.3f} seconds", flush=True)
|
| 4008 |
if debug is not None:
|
|
|
|
| 4025 |
segmentation_elapsed * 1000,
|
| 4026 |
)
|
| 4027 |
|
| 4028 |
+
if progress_callback:
|
| 4029 |
+
progress_callback("segmentation", 100)
|
| 4030 |
+
if progress_callback:
|
| 4031 |
+
progress_callback("masking", 0)
|
| 4032 |
+
t0 = time.perf_counter()
|
| 4033 |
+
pixels_b64 = encode_bundle_image_data_url(img_np)
|
| 4034 |
print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 4035 |
|
| 4036 |
t0 = time.perf_counter()
|
|
|
|
| 4070 |
floor_mask_elapsed * 1000,
|
| 4071 |
)
|
| 4072 |
|
| 4073 |
+
if progress_callback:
|
| 4074 |
+
progress_callback("masking", 100)
|
| 4075 |
+
progress_callback("geometry", 0)
|
| 4076 |
+
t0 = time.perf_counter()
|
| 4077 |
+
geometry = estimate_scene_geometry(img, img_np, w, h)
|
| 4078 |
depth = geometry.get("depth")
|
| 4079 |
geometry_elapsed = time.perf_counter() - t0
|
| 4080 |
print(
|
|
|
|
| 4099 |
geometry_elapsed * 1000,
|
| 4100 |
)
|
| 4101 |
|
| 4102 |
+
if progress_callback:
|
| 4103 |
+
progress_callback("geometry", 55)
|
| 4104 |
+
t0 = time.perf_counter()
|
| 4105 |
+
homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
|
| 4106 |
plane_elapsed = time.perf_counter() - t0
|
| 4107 |
print(f"[TIMING] Plane fitting / homography calculation took {plane_elapsed:.3f} seconds", flush=True)
|
| 4108 |
if debug is not None:
|
|
|
|
| 4122 |
plane_elapsed * 1000,
|
| 4123 |
)
|
| 4124 |
|
| 4125 |
+
if progress_callback:
|
| 4126 |
+
progress_callback("geometry", 100)
|
| 4127 |
+
t0 = time.perf_counter()
|
| 4128 |
+
quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
|
| 4129 |
surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
|
| 4130 |
+
replaced_material_mask = (
|
| 4131 |
+
np.isin(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES))
|
| 4132 |
+
& (surface_mask > 0)
|
| 4133 |
+
).astype(np.uint8)
|
| 4134 |
surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
|
| 4135 |
occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
|
| 4136 |
occlusion_indices = np.flatnonzero(occlusion_mask.ravel()).astype(np.uint32)
|
|
|
|
| 4152 |
surface_mask_elapsed * 1000,
|
| 4153 |
)
|
| 4154 |
|
| 4155 |
+
if progress_callback:
|
| 4156 |
+
progress_callback("surface-mapping", 0)
|
| 4157 |
+
t0 = time.perf_counter()
|
| 4158 |
+
surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
|
| 4159 |
use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
|
| 4160 |
mapping_metadata = (
|
| 4161 |
surface_mapping["metadata"]
|
|
|
|
| 4209 |
surface_mapping_elapsed * 1000,
|
| 4210 |
)
|
| 4211 |
|
| 4212 |
+
if progress_callback:
|
| 4213 |
+
progress_callback("surface-mapping", 100)
|
| 4214 |
+
progress_callback("lighting", 0)
|
| 4215 |
+
t0 = time.perf_counter()
|
| 4216 |
+
lighting_maps = None
|
| 4217 |
shade_map = None
|
| 4218 |
showroom_shade_map = None
|
| 4219 |
reflection_map = None
|
|
|
|
| 4223 |
if intrinsic_models is None:
|
| 4224 |
_load_intrinsic_model()
|
| 4225 |
if intrinsic_models is not None:
|
| 4226 |
+
lighting_maps = build_intrinsic_lighting_maps(
|
| 4227 |
+
img_np,
|
| 4228 |
+
surface_mask,
|
| 4229 |
+
replaced_material_mask,
|
| 4230 |
+
)
|
| 4231 |
if lighting_maps and lighting_maps.get("shadeMap") is not None:
|
| 4232 |
lighting_source = f"intrinsic-{INTRINSIC_MODEL_VERSION}"
|
| 4233 |
intrinsic_lighting_used = True
|
| 4234 |
if ENABLE_SHADING_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
|
| 4235 |
+
lighting_maps = build_luminance_lighting_maps(
|
| 4236 |
+
img_np,
|
| 4237 |
+
surface_mask,
|
| 4238 |
+
replaced_material_mask,
|
| 4239 |
+
)
|
| 4240 |
if lighting_maps and lighting_maps.get("shadeMap") is not None:
|
| 4241 |
lighting_source = "luminance"
|
| 4242 |
+
if lighting_maps:
|
| 4243 |
+
shade_map = lighting_maps.get("shadeMap")
|
| 4244 |
+
showroom_shade_map = lighting_maps.get("showroomShadeMap")
|
| 4245 |
+
reflection_map = lighting_maps.get("reflectionMap")
|
| 4246 |
shade_statistics = lighting_map_statistics(shade_map, surface_mask)
|
| 4247 |
lighting_elapsed = time.perf_counter() - t0
|
| 4248 |
print(
|
|
|
|
| 4269 |
"shadingAvailable": shade_map is not None,
|
| 4270 |
"reflectionsAvailable": reflection_map is not None,
|
| 4271 |
},
|
| 4272 |
+
lighting_elapsed * 1000,
|
| 4273 |
+
)
|
| 4274 |
+
|
| 4275 |
+
wall_mask = np.isin(seg_map, class_ids({"wall"})).astype(np.uint8)
|
| 4276 |
+
wall_components, wall_protected_mask = (
|
| 4277 |
+
wall_surface_components(seg_map, min_floor_area, geometry)
|
| 4278 |
+
if ENABLE_WALL_SEGMENTS else ([], np.zeros_like(wall_mask))
|
| 4279 |
+
)
|
| 4280 |
+
|
| 4281 |
+
if progress_callback:
|
| 4282 |
+
progress_callback("lighting", 100)
|
| 4283 |
+
progress_callback("direction", 0)
|
| 4284 |
t0 = time.perf_counter()
|
| 4285 |
direction_transform = (
|
| 4286 |
plane.get("floorTransform")
|
|
|
|
| 4296 |
surface_mapping,
|
| 4297 |
use_surface_uv=use_surface_uv,
|
| 4298 |
)
|
|
|
|
| 4299 |
structure_mask = np.isin(
|
| 4300 |
seg_map,
|
| 4301 |
class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}),
|
|
|
|
| 4339 |
[("Direction analysis", debug_floor_direction_overlay(img_np, floor_direction))],
|
| 4340 |
floor_direction,
|
| 4341 |
floor_direction_elapsed * 1000,
|
| 4342 |
+
)
|
| 4343 |
+
|
| 4344 |
+
if progress_callback:
|
| 4345 |
+
progress_callback("direction", 100)
|
| 4346 |
+
progress_callback("packaging", 0)
|
| 4347 |
+
t0 = time.perf_counter()
|
| 4348 |
segments = []
|
| 4349 |
models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
|
| 4350 |
|
| 4351 |
+
if len(surface_indices) >= min_floor_area:
|
| 4352 |
+
segments.append({
|
| 4353 |
"id": 0,
|
| 4354 |
"className": "floor",
|
| 4355 |
"mask": base64.b64encode(surface_indices.tobytes()).decode(),
|
|
|
|
| 4383 |
"segmentationModel": models["segmentation"]["name"],
|
| 4384 |
"floorPixels": int(floor_mask.sum()),
|
| 4385 |
"surfacePixels": int(surface_mask.sum()),
|
| 4386 |
+
"replacedSoftFloorPixels": int(replaced_material_mask.sum()),
|
| 4387 |
"occlusionPixels": int(occlusion_mask.sum()),
|
| 4388 |
"floorDirection": floor_direction,
|
| 4389 |
**sam_metadata,
|
|
|
|
| 4421 |
"metricGeometry": bool(plane and plane.get("floorTransform")),
|
| 4422 |
"geometryProvider": plane.get("geometryProvider", geometry.get("provider")) if plane else geometry.get("provider"),
|
| 4423 |
"geometryModel": models["geometry"]["name"],
|
| 4424 |
+
},
|
| 4425 |
+
})
|
| 4426 |
+
|
| 4427 |
+
for wall_index, (wall_area, component_mask) in enumerate(wall_components):
|
| 4428 |
+
wall_homography, wall_plane = estimate_wall_plane(component_mask, geometry)
|
| 4429 |
+
if wall_homography is None or wall_plane is None:
|
| 4430 |
+
continue
|
| 4431 |
+
wall_lighting_maps = build_luminance_lighting_maps(img_np, component_mask)
|
| 4432 |
+
wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
|
| 4433 |
+
wall_occlusion_indices = np.flatnonzero(wall_protected_mask.ravel()).astype(np.uint32)
|
| 4434 |
+
wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
|
| 4435 |
+
wall_showroom_shade_map = wall_lighting_maps.get("showroomShadeMap") if wall_lighting_maps else None
|
| 4436 |
+
wall_reflection_map = wall_lighting_maps.get("reflectionMap") if wall_lighting_maps else None
|
| 4437 |
+
segments.append({
|
| 4438 |
+
"id": wall_index + 1,
|
| 4439 |
+
"className": "wall",
|
| 4440 |
+
"surfaceType": "wall",
|
| 4441 |
+
"mask": base64.b64encode(wall_indices.tobytes()).decode(),
|
| 4442 |
+
"occlusionMask": (
|
| 4443 |
+
base64.b64encode(wall_occlusion_indices.tobytes()).decode()
|
| 4444 |
+
if len(wall_occlusion_indices) else None
|
| 4445 |
+
),
|
| 4446 |
+
"homography": wall_homography,
|
| 4447 |
+
"floorTransform": wall_plane.get("floorTransform"),
|
| 4448 |
+
"surfaceTransform": wall_plane.get("surfaceTransform"),
|
| 4449 |
+
"plane": wall_plane,
|
| 4450 |
+
"surfaceUv": None,
|
| 4451 |
+
"surfacePlaneIds": None,
|
| 4452 |
+
"surfacePlanes": None,
|
| 4453 |
+
"shadeMap": base64.b64encode(wall_shade_map.tobytes()).decode() if wall_shade_map is not None else None,
|
| 4454 |
+
"showroomShadeMap": (
|
| 4455 |
+
base64.b64encode(wall_showroom_shade_map.tobytes()).decode()
|
| 4456 |
+
if wall_showroom_shade_map is not None else None
|
| 4457 |
+
),
|
| 4458 |
+
"reflectionMap": (
|
| 4459 |
+
base64.b64encode(wall_reflection_map.tobytes()).decode()
|
| 4460 |
+
if wall_reflection_map is not None else None
|
| 4461 |
+
),
|
| 4462 |
+
"metadata": {
|
| 4463 |
+
"segmenter": segmenter_metadata_name(),
|
| 4464 |
+
"segmentationModel": models["segmentation"]["name"],
|
| 4465 |
+
"wallPixels": int(wall_area),
|
| 4466 |
+
"wallComponent": wall_index,
|
| 4467 |
+
"wallComponentCount": len(wall_components),
|
| 4468 |
+
"protectedPixels": int(wall_protected_mask.sum()),
|
| 4469 |
+
"shadingEnabled": wall_shade_map is not None,
|
| 4470 |
+
"reflectionTransferEnabled": wall_reflection_map is not None,
|
| 4471 |
+
"textureMappingMode": "wall-plane" if wall_plane.get("surfaceTransform") else "wall-contour-homography",
|
| 4472 |
+
"geometryConfidence": wall_plane.get("geometryConfidence", 0.0),
|
| 4473 |
+
"geometryProvider": wall_plane.get("geometryProvider"),
|
| 4474 |
+
"surfaceWidthMeters": wall_plane.get("surfaceWidthMeters"),
|
| 4475 |
+
"surfaceHeightMeters": wall_plane.get("surfaceHeightMeters"),
|
| 4476 |
+
"lightingTransferVersion": LIGHTING_TRANSFER_VERSION,
|
| 4477 |
+
"shadeMapEncoding": SHADE_MAP_ENCODING,
|
| 4478 |
+
"shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX],
|
| 4479 |
+
"showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX],
|
| 4480 |
+
"reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX],
|
| 4481 |
+
},
|
| 4482 |
+
})
|
| 4483 |
|
| 4484 |
if not segments:
|
| 4485 |
flat_seg = seg_map.ravel()
|
|
|
|
| 4508 |
},
|
| 4509 |
})
|
| 4510 |
|
| 4511 |
+
if progress_callback:
|
| 4512 |
+
progress_callback("packaging", 100)
|
| 4513 |
+
total_elapsed = time.perf_counter() - t_start
|
| 4514 |
print(f"[TIMING] Total bundle processing completed in {total_elapsed:.3f} seconds", flush=True)
|
| 4515 |
if debug is not None:
|
| 4516 |
debug.complete(total_elapsed * 1000)
|
|
|
|
| 4535 |
return json.loads(path.read_text())
|
| 4536 |
|
| 4537 |
|
| 4538 |
+
def write_job(job: dict):
|
| 4539 |
+
path = job_path(job["id"])
|
| 4540 |
+
temporary = path.with_suffix(f"{path.suffix}.{os.getpid()}.tmp")
|
| 4541 |
+
temporary.write_text(json.dumps(job, separators=(",", ":")))
|
| 4542 |
+
temporary.replace(path)
|
| 4543 |
+
|
| 4544 |
+
|
| 4545 |
+
CONVERSION_STAGE_WEIGHTS = {
|
| 4546 |
+
"segmentation": 0.28,
|
| 4547 |
+
"masking": 0.08,
|
| 4548 |
+
"geometry": 0.18,
|
| 4549 |
+
"surface-mapping": 0.12,
|
| 4550 |
+
"lighting": 0.15,
|
| 4551 |
+
"direction": 0.08,
|
| 4552 |
+
"packaging": 0.11,
|
| 4553 |
+
}
|
| 4554 |
+
CONVERSION_STAGE_ORDER = tuple(CONVERSION_STAGE_WEIGHTS)
|
| 4555 |
+
CONVERSION_GPU_LOCK = threading.Lock()
|
| 4556 |
+
|
| 4557 |
+
|
| 4558 |
+
def update_conversion_job(
|
| 4559 |
+
job_id: str,
|
| 4560 |
+
*,
|
| 4561 |
+
phase: str | None = None,
|
| 4562 |
+
progress: int | None = None,
|
| 4563 |
+
phase_progress: int | None = None,
|
| 4564 |
+
message: str | None = None,
|
| 4565 |
+
**values,
|
| 4566 |
+
):
|
| 4567 |
+
"""Persist live conversion state for the browser's progress and ETA display."""
|
| 4568 |
+
try:
|
| 4569 |
+
job = read_job(job_id)
|
| 4570 |
+
except HTTPException:
|
| 4571 |
+
return
|
| 4572 |
+
if phase is not None:
|
| 4573 |
+
job["phase"] = phase
|
| 4574 |
+
if progress is not None:
|
| 4575 |
+
job["progress"] = max(0, min(100, int(progress)))
|
| 4576 |
+
if phase_progress is not None:
|
| 4577 |
+
job["phaseProgress"] = max(0, min(100, int(phase_progress)))
|
| 4578 |
+
if message is not None:
|
| 4579 |
+
job["message"] = message
|
| 4580 |
+
job.update(values)
|
| 4581 |
+
write_job(job)
|
| 4582 |
+
|
| 4583 |
+
|
| 4584 |
+
def weighted_conversion_progress(completed_phases: set[str], phase: str, phase_progress: float) -> int:
|
| 4585 |
+
completed_weight = sum(
|
| 4586 |
+
CONVERSION_STAGE_WEIGHTS.get(item, 0.0)
|
| 4587 |
+
for item in completed_phases
|
| 4588 |
+
if item != phase
|
| 4589 |
+
)
|
| 4590 |
+
current_weight = CONVERSION_STAGE_WEIGHTS.get(phase, 0.0) * max(0.0, min(1.0, phase_progress / 100.0))
|
| 4591 |
+
return round((completed_weight + current_weight) * 100)
|
| 4592 |
+
|
| 4593 |
+
|
| 4594 |
+
TIMING_BASELINE_LOCK = threading.Lock()
|
| 4595 |
+
TIMING_BASELINE_PATH: Path | None = None
|
| 4596 |
+
|
| 4597 |
+
|
| 4598 |
+
def estimate_conversion_ms() -> int:
|
| 4599 |
+
default_ms = CONVERSION_TARGET_MS
|
| 4600 |
+
if TIMING_BASELINE_PATH is None or not TIMING_BASELINE_PATH.exists():
|
| 4601 |
+
return default_ms
|
| 4602 |
+
try:
|
| 4603 |
+
data = json.loads(TIMING_BASELINE_PATH.read_text())
|
| 4604 |
+
samples = [float(value) for value in data.get("totalMs", []) if float(value) > 0]
|
| 4605 |
+
if len(samples) < 3:
|
| 4606 |
+
return default_ms
|
| 4607 |
+
samples.sort()
|
| 4608 |
+
return max(5_000, round(samples[min(len(samples) - 1, int(len(samples) * 0.75))]))
|
| 4609 |
+
except (OSError, TypeError, ValueError, json.JSONDecodeError):
|
| 4610 |
+
return default_ms
|
| 4611 |
+
|
| 4612 |
+
|
| 4613 |
+
def record_conversion_ms(duration_ms: float):
|
| 4614 |
+
if TIMING_BASELINE_PATH is None:
|
| 4615 |
+
return
|
| 4616 |
+
with TIMING_BASELINE_LOCK:
|
| 4617 |
+
data = {"totalMs": []}
|
| 4618 |
+
try:
|
| 4619 |
+
if TIMING_BASELINE_PATH.exists():
|
| 4620 |
+
data = json.loads(TIMING_BASELINE_PATH.read_text())
|
| 4621 |
+
except (OSError, TypeError, ValueError, json.JSONDecodeError):
|
| 4622 |
+
data = {"totalMs": []}
|
| 4623 |
+
samples = [float(value) for value in data.get("totalMs", []) if float(value) > 0]
|
| 4624 |
+
samples.append(float(duration_ms))
|
| 4625 |
+
data["totalMs"] = samples[-40:]
|
| 4626 |
+
temporary = TIMING_BASELINE_PATH.with_suffix(f"{TIMING_BASELINE_PATH.suffix}.{os.getpid()}.tmp")
|
| 4627 |
+
temporary.write_text(json.dumps(data, separators=(",", ":")))
|
| 4628 |
+
temporary.replace(TIMING_BASELINE_PATH)
|
| 4629 |
|
| 4630 |
|
| 4631 |
def spaces_upload_enabled() -> bool:
|
|
|
|
| 5550 |
|
| 5551 |
|
| 5552 |
def run_conversion_task(job_id: str, upload_path: Path):
|
| 5553 |
+
debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
|
| 5554 |
+
estimate_ms = estimate_conversion_ms()
|
| 5555 |
+
try:
|
| 5556 |
+
update_conversion_job(
|
| 5557 |
+
job_id,
|
| 5558 |
+
status="QUEUED",
|
| 5559 |
+
phase="queued",
|
| 5560 |
+
progress=0,
|
| 5561 |
+
phase_progress=0,
|
| 5562 |
+
message="Waiting for an analysis slot…",
|
| 5563 |
+
estimatedTotalMs=estimate_ms,
|
| 5564 |
+
estimatedRemainingMs=estimate_ms,
|
| 5565 |
+
)
|
| 5566 |
+
with CONVERSION_GPU_LOCK:
|
| 5567 |
+
t_start = time.perf_counter()
|
| 5568 |
+
update_conversion_job(
|
| 5569 |
+
job_id,
|
| 5570 |
+
status="PROCESSING",
|
| 5571 |
+
phase="segmentation",
|
| 5572 |
+
progress=0,
|
| 5573 |
+
phase_progress=0,
|
| 5574 |
+
message="Analyzing floor…",
|
| 5575 |
+
startedAt=datetime.now(timezone.utc).isoformat(),
|
| 5576 |
+
estimatedTotalMs=estimate_ms,
|
| 5577 |
+
estimatedRemainingMs=estimate_ms,
|
| 5578 |
+
)
|
| 5579 |
+
completed_phases: set[str] = set()
|
| 5580 |
+
|
| 5581 |
+
def report_stage(phase: str, phase_progress: float):
|
| 5582 |
+
if phase_progress >= 100:
|
| 5583 |
+
completed_phases.add(phase)
|
| 5584 |
+
elapsed_ms = (time.perf_counter() - t_start) * 1000
|
| 5585 |
+
remaining_ms = max(0, estimate_ms - elapsed_ms)
|
| 5586 |
+
update_conversion_job(
|
| 5587 |
+
job_id,
|
| 5588 |
+
phase=phase,
|
| 5589 |
+
progress=weighted_conversion_progress(completed_phases, phase, phase_progress),
|
| 5590 |
+
phase_progress=round(phase_progress),
|
| 5591 |
+
message=f"Analyzing {phase.replace('-', ' ')}…",
|
| 5592 |
+
estimatedRemainingMs=round(remaining_ms),
|
| 5593 |
+
)
|
| 5594 |
+
|
| 5595 |
+
image_bytes = upload_path.read_bytes()
|
| 5596 |
+
bundle = build_segmentation_bundle(image_bytes, debug=debug, progress_callback=report_stage)
|
| 5597 |
+
report_stage("packaging", 25)
|
| 5598 |
+
binary_bundle = build_manifest_segmentation_bundle(
|
| 5599 |
+
bundle,
|
| 5600 |
+
job_id,
|
| 5601 |
+
image_url=f"/uploads/{upload_path.name}",
|
| 5602 |
+
include_image=False,
|
| 5603 |
+
)
|
| 5604 |
+
(JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle)
|
| 5605 |
+
report_stage("packaging", 100)
|
| 5606 |
+
elapsed_ms = (time.perf_counter() - t_start) * 1000
|
| 5607 |
+
record_conversion_ms(elapsed_ms)
|
| 5608 |
+
job = read_job(job_id)
|
| 5609 |
+
job["status"] = "COMPLETED"
|
| 5610 |
+
job["phase"] = "completed"
|
| 5611 |
+
job["progress"] = 100
|
| 5612 |
+
job["phaseProgress"] = 100
|
| 5613 |
+
job["message"] = "Surfaces ready"
|
| 5614 |
+
job["estimatedRemainingMs"] = 0
|
| 5615 |
+
job["completedAt"] = datetime.now(timezone.utc).isoformat()
|
| 5616 |
+
job["durationMs"] = round(elapsed_ms)
|
| 5617 |
+
job["modelName"] = bundle.get("modelName")
|
| 5618 |
+
job["models"] = bundle.get("models")
|
| 5619 |
+
job["outputFormat"] = "split-vizbundle"
|
| 5620 |
+
write_job(job)
|
| 5621 |
+
print(f"[TIMING] Background conversion task for job {job_id} took {elapsed_ms / 1000:.3f} seconds", flush=True)
|
| 5622 |
+
except Exception as exc:
|
| 5623 |
print(f"Background conversion failed: {exc}", flush=True)
|
| 5624 |
if debug is not None:
|
| 5625 |
debug.fail(exc)
|
| 5626 |
try:
|
| 5627 |
+
job = read_job(job_id)
|
| 5628 |
+
job["status"] = "FAILED"
|
| 5629 |
+
job["phase"] = "failed"
|
| 5630 |
+
job["estimatedRemainingMs"] = None
|
| 5631 |
+
job["error"] = str(exc)
|
| 5632 |
+
write_job(job)
|
| 5633 |
except Exception:
|
| 5634 |
pass
|
| 5635 |
|
|
|
|
| 5957 |
upload_path = UPLOAD_DIR / f"{job_id}{ext}"
|
| 5958 |
upload_path.write_bytes(normalized_contents)
|
| 5959 |
|
| 5960 |
+
job = {
|
| 5961 |
+
"id": job_id,
|
| 5962 |
+
"status": "QUEUED",
|
| 5963 |
+
"phase": "queued",
|
| 5964 |
+
"progress": 0,
|
| 5965 |
+
"phaseProgress": 0,
|
| 5966 |
+
"message": "Waiting for an analysis slot…",
|
| 5967 |
+
"createdAt": datetime.now(timezone.utc).isoformat(),
|
| 5968 |
+
"estimatedTotalMs": estimate_conversion_ms(),
|
| 5969 |
+
"estimatedRemainingMs": estimate_conversion_ms(),
|
| 5970 |
+
"targetMs": CONVERSION_TARGET_MS,
|
| 5971 |
+
"inputUrl": f"/uploads/{upload_path.name}",
|
| 5972 |
"outputUrl": f"/viz2d/jobs/{job_id}/file",
|
| 5973 |
"debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None,
|
| 5974 |
}
|
frontend/viz2d-demo/e2e/lighting-preservation.spec.ts
CHANGED
|
@@ -3,6 +3,37 @@ import { expect, test, type Page } from "@playwright/test";
|
|
| 3 |
const WIDTH = 120;
|
| 4 |
const HEIGHT = 72;
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
for (const renderer of ["webgl", "canvas"] as const) {
|
| 7 |
test(`applied tile preserves scene lighting in ${renderer}`, async ({ page }) => {
|
| 8 |
if (renderer === "canvas") {
|
|
@@ -32,6 +63,24 @@ for (const renderer of ["webgl", "canvas"] as const) {
|
|
| 32 |
expect(luminance.bright, "bright source region should approach white").toBeGreaterThan(240);
|
| 33 |
});
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
test(`applied tile fully covers the floor-mask edge in ${renderer}`, async ({ page }) => {
|
| 36 |
if (renderer === "canvas") {
|
| 37 |
await disableWebGl(page);
|
|
@@ -59,11 +108,36 @@ for (const renderer of ["webgl", "canvas"] as const) {
|
|
| 59 |
});
|
| 60 |
}
|
| 61 |
|
| 62 |
-
function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
const pixelCount = WIDTH * HEIGHT;
|
| 64 |
const pixels = new Uint8Array(pixelCount * 4);
|
| 65 |
const mask = new Uint32Array(pixelCount);
|
| 66 |
const shadeMap = new Uint8Array(pixelCount);
|
|
|
|
| 67 |
|
| 68 |
for (let index = 0; index < pixelCount; index += 1) {
|
| 69 |
const x = index % WIDTH;
|
|
@@ -76,6 +150,7 @@ function buildLightingBundle() {
|
|
| 76 |
pixels[pixelIndex + 3] = 255;
|
| 77 |
mask[index] = index;
|
| 78 |
shadeMap[index] = Math.round(((shade - 0.08) / (1.85 - 0.08)) * 255);
|
|
|
|
| 79 |
}
|
| 80 |
|
| 81 |
return {
|
|
@@ -93,10 +168,10 @@ function buildLightingBundle() {
|
|
| 93 |
plane: null,
|
| 94 |
shadeMap: Buffer.from(shadeMap).toString("base64"),
|
| 95 |
showroomShadeMap: null,
|
| 96 |
-
reflectionMap: null,
|
| 97 |
metadata: {
|
| 98 |
lightingSource: "synthetic-test",
|
| 99 |
-
lightingTransferVersion
|
| 100 |
shadeMapEncoding: "linear-relative",
|
| 101 |
shadeMapRange: [0.08, 1.85],
|
| 102 |
renderPresetDefaults: {
|
|
@@ -175,6 +250,27 @@ async function disableWebGl(page: Page) {
|
|
| 175 |
});
|
| 176 |
}
|
| 177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
async function readLightingRegions(page: Page) {
|
| 179 |
return page.getByTestId("visualizer-canvas").evaluate((node) => {
|
| 180 |
const canvas = node as HTMLCanvasElement;
|
|
|
|
| 3 |
const WIDTH = 120;
|
| 4 |
const HEIGHT = 72;
|
| 5 |
|
| 6 |
+
test("shows a persistent floor label without tinting the mask", async ({ page }) => {
|
| 7 |
+
await page.goto("/");
|
| 8 |
+
await page.getByTestId("room-file-input").setInputFiles({
|
| 9 |
+
name: "surface-label.vizbundle.json",
|
| 10 |
+
mimeType: "application/json",
|
| 11 |
+
buffer: Buffer.from(JSON.stringify(buildLightingBundle())),
|
| 12 |
+
});
|
| 13 |
+
|
| 14 |
+
const canvas = page.getByTestId("visualizer-canvas");
|
| 15 |
+
const label = page.getByTestId("surface-label").filter({ hasText: "Floor" });
|
| 16 |
+
await expect(canvas).toBeVisible();
|
| 17 |
+
await expect(label).toBeVisible();
|
| 18 |
+
await expectLabelInsideCanvas(canvas, label);
|
| 19 |
+
|
| 20 |
+
const beforeHover = await readCanvasPixel(canvas, WIDTH / 2, HEIGHT / 2);
|
| 21 |
+
const canvasBox = await canvas.boundingBox();
|
| 22 |
+
expect(canvasBox).not.toBeNull();
|
| 23 |
+
await page.mouse.move(canvasBox!.x + canvasBox!.width / 2, canvasBox!.y + canvasBox!.height / 2);
|
| 24 |
+
const afterHover = await readCanvasPixel(canvas, WIDTH / 2, HEIGHT / 2);
|
| 25 |
+
expect(afterHover).toEqual(beforeHover);
|
| 26 |
+
|
| 27 |
+
const labelBox = await label.boundingBox();
|
| 28 |
+
expect(labelBox).not.toBeNull();
|
| 29 |
+
await page.mouse.click(labelBox!.x + labelBox!.width / 2, labelBox!.y + labelBox!.height / 2);
|
| 30 |
+
await expect(page.getByTestId("texture-selector")).toBeVisible();
|
| 31 |
+
await page.getByLabel("Close", { exact: true }).click();
|
| 32 |
+
|
| 33 |
+
await page.setViewportSize({ width: 390, height: 844 });
|
| 34 |
+
await expectLabelInsideCanvas(canvas, label);
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
for (const renderer of ["webgl", "canvas"] as const) {
|
| 38 |
test(`applied tile preserves scene lighting in ${renderer}`, async ({ page }) => {
|
| 39 |
if (renderer === "canvas") {
|
|
|
|
| 63 |
expect(luminance.bright, "bright source region should approach white").toBeGreaterThan(240);
|
| 64 |
});
|
| 65 |
|
| 66 |
+
test(`v4 keeps shadows unchanged and controls highlights on dark tile in ${renderer}`, async ({ page }) => {
|
| 67 |
+
if (renderer === "canvas") {
|
| 68 |
+
await disableWebGl(page);
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
const legacy = await renderLightingBundle(page, 3, false, "Dark Marble");
|
| 72 |
+
const materialAware = await renderLightingBundle(page, 4, false, "Dark Marble");
|
| 73 |
+
const materialAwareWithReflection = await renderLightingBundle(page, 4, true, "Dark Marble");
|
| 74 |
+
|
| 75 |
+
expect(materialAware.dark, "v4 must not weaken or strengthen source shadows").toBeCloseTo(legacy.dark, 0);
|
| 76 |
+
expect(materialAware.neutral, "v4 must not alter neutral source lighting").toBeCloseTo(legacy.neutral, 0);
|
| 77 |
+
expect(materialAwareWithReflection.bright, "bright source lighting should remain visible").toBeGreaterThan(
|
| 78 |
+
materialAwareWithReflection.neutral + 8,
|
| 79 |
+
);
|
| 80 |
+
expect(materialAwareWithReflection.bright, "dark tile highlights should retain material color").toBeLessThan(190);
|
| 81 |
+
expect(materialAware.bright, "v4 should reduce additive whitening").toBeLessThan(legacy.bright);
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
test(`applied tile fully covers the floor-mask edge in ${renderer}`, async ({ page }) => {
|
| 85 |
if (renderer === "canvas") {
|
| 86 |
await disableWebGl(page);
|
|
|
|
| 108 |
});
|
| 109 |
}
|
| 110 |
|
| 111 |
+
async function readCanvasPixel(pageCanvas: ReturnType<import("@playwright/test").Page["getByTestId"]>, x: number, y: number) {
|
| 112 |
+
return pageCanvas.evaluate((canvas, point) => {
|
| 113 |
+
const context = (canvas as HTMLCanvasElement).getContext("2d");
|
| 114 |
+
if (!context) throw new Error("Canvas context is unavailable.");
|
| 115 |
+
return Array.from(context.getImageData(point.x, point.y, 1, 1).data);
|
| 116 |
+
}, { x, y });
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
async function expectLabelInsideCanvas(
|
| 120 |
+
canvas: ReturnType<import("@playwright/test").Page["getByTestId"]>,
|
| 121 |
+
label: ReturnType<import("@playwright/test").Page["getByTestId"]>,
|
| 122 |
+
) {
|
| 123 |
+
await expect.poll(async () => {
|
| 124 |
+
const [canvasBox, labelBox] = await Promise.all([canvas.boundingBox(), label.boundingBox()]);
|
| 125 |
+
if (!canvasBox || !labelBox) return false;
|
| 126 |
+
return (
|
| 127 |
+
labelBox.x >= canvasBox.x &&
|
| 128 |
+
labelBox.y >= canvasBox.y &&
|
| 129 |
+
labelBox.x + labelBox.width <= canvasBox.x + canvasBox.width &&
|
| 130 |
+
labelBox.y + labelBox.height <= canvasBox.y + canvasBox.height
|
| 131 |
+
);
|
| 132 |
+
}).toBe(true);
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
function buildLightingBundle(lightingTransferVersion = 3, includeReflection = false) {
|
| 136 |
const pixelCount = WIDTH * HEIGHT;
|
| 137 |
const pixels = new Uint8Array(pixelCount * 4);
|
| 138 |
const mask = new Uint32Array(pixelCount);
|
| 139 |
const shadeMap = new Uint8Array(pixelCount);
|
| 140 |
+
const reflectionMap = new Uint8Array(pixelCount);
|
| 141 |
|
| 142 |
for (let index = 0; index < pixelCount; index += 1) {
|
| 143 |
const x = index % WIDTH;
|
|
|
|
| 150 |
pixels[pixelIndex + 3] = 255;
|
| 151 |
mask[index] = index;
|
| 152 |
shadeMap[index] = Math.round(((shade - 0.08) / (1.85 - 0.08)) * 255);
|
| 153 |
+
reflectionMap[index] = includeReflection && x >= 80 ? 255 : 0;
|
| 154 |
}
|
| 155 |
|
| 156 |
return {
|
|
|
|
| 168 |
plane: null,
|
| 169 |
shadeMap: Buffer.from(shadeMap).toString("base64"),
|
| 170 |
showroomShadeMap: null,
|
| 171 |
+
reflectionMap: includeReflection ? Buffer.from(reflectionMap).toString("base64") : null,
|
| 172 |
metadata: {
|
| 173 |
lightingSource: "synthetic-test",
|
| 174 |
+
lightingTransferVersion,
|
| 175 |
shadeMapEncoding: "linear-relative",
|
| 176 |
shadeMapRange: [0.08, 1.85],
|
| 177 |
renderPresetDefaults: {
|
|
|
|
| 250 |
});
|
| 251 |
}
|
| 252 |
|
| 253 |
+
async function renderLightingBundle(
|
| 254 |
+
page: Page,
|
| 255 |
+
lightingTransferVersion: number,
|
| 256 |
+
includeReflection: boolean,
|
| 257 |
+
textureName: string,
|
| 258 |
+
) {
|
| 259 |
+
await page.goto("/");
|
| 260 |
+
await page.getByTestId("room-file-input").setInputFiles({
|
| 261 |
+
name: `lighting-v${lightingTransferVersion}.vizbundle.json`,
|
| 262 |
+
mimeType: "application/json",
|
| 263 |
+
buffer: Buffer.from(JSON.stringify(buildLightingBundle(lightingTransferVersion, includeReflection))),
|
| 264 |
+
});
|
| 265 |
+
await expect(page.getByTestId("visualizer-editor")).toBeVisible();
|
| 266 |
+
await page.getByTestId("surface-card").click();
|
| 267 |
+
await expect(page.getByTestId("texture-selector")).toBeVisible();
|
| 268 |
+
await page.getByTestId("texture-card").filter({ hasText: textureName }).click();
|
| 269 |
+
await expect(page.getByTestId("texture-selector")).toBeHidden();
|
| 270 |
+
await page.mouse.move(4, 4);
|
| 271 |
+
return readLightingRegions(page);
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
async function readLightingRegions(page: Page) {
|
| 275 |
return page.getByTestId("visualizer-canvas").evaluate((node) => {
|
| 276 |
const canvas = node as HTMLCanvasElement;
|
frontend/viz2d-demo/package.json
CHANGED
|
@@ -11,7 +11,13 @@
|
|
| 11 |
"qa:e2e": "playwright test",
|
| 12 |
"qa:e2e:headed": "playwright test --headed",
|
| 13 |
"qa:report": "node scripts/build-qa-summary.mjs",
|
| 14 |
-
"qa:real": "npm run build && playwright test"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
},
|
| 16 |
"dependencies": {
|
| 17 |
"@radix-ui/react-dialog": "^1.1.15",
|
|
|
|
| 11 |
"qa:e2e": "playwright test",
|
| 12 |
"qa:e2e:headed": "playwright test --headed",
|
| 13 |
"qa:report": "node scripts/build-qa-summary.mjs",
|
| 14 |
+
"qa:real": "npm run build && playwright test",
|
| 15 |
+
"hf:dev:check": "bash scripts/hf-stage-dev.sh check",
|
| 16 |
+
"hf:dev:ssh": "bash scripts/hf-stage-dev.sh ssh",
|
| 17 |
+
"hf:dev:tunnel": "bash scripts/hf-stage-dev.sh tunnel",
|
| 18 |
+
"hf:dev:sync": "bash scripts/hf-stage-dev.sh sync",
|
| 19 |
+
"hf:dev:watch": "bash scripts/hf-stage-dev.sh watch",
|
| 20 |
+
"hf:dev:stop": "bash scripts/hf-stage-dev.sh stop"
|
| 21 |
},
|
| 22 |
"dependencies": {
|
| 23 |
"@radix-ui/react-dialog": "^1.1.15",
|
test_floor_geometry.py
CHANGED
|
@@ -132,6 +132,34 @@ class MetricFloorGeometryTests(unittest.TestCase):
|
|
| 132 |
self.assertGreater(shadow_contrast, 0.25)
|
| 133 |
self.assertLess(stripe_contrast, 0.035)
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
def test_intrinsic_fusion_cannot_weaken_observed_shadow_or_highlight(self):
|
| 136 |
mask = np.ones((8, 12), dtype=np.uint8)
|
| 137 |
intrinsic = np.ones((8, 12), dtype=np.float32)
|
|
@@ -163,6 +191,46 @@ class MetricFloorGeometryTests(unittest.TestCase):
|
|
| 163 |
self.assertLessEqual(float(decoded[64, 48]), 0.02)
|
| 164 |
self.assertGreater(float(decoded[42:86, 92:132].max()), 0.0)
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
def test_intrinsic_shading_inversion_is_corrected_against_room_luminance(self):
|
| 167 |
height, width = 160, 180
|
| 168 |
image = np.zeros((height, width, 3), dtype=np.uint8)
|
|
|
|
| 132 |
self.assertGreater(shadow_contrast, 0.25)
|
| 133 |
self.assertLess(stripe_contrast, 0.035)
|
| 134 |
|
| 135 |
+
def test_replaced_carpet_does_not_transfer_its_color_or_pile_as_shadow(self):
|
| 136 |
+
height, width = 180, 240
|
| 137 |
+
image = np.full((height, width, 3), 165, dtype=np.uint8)
|
| 138 |
+
image[:, :45, :] = 55
|
| 139 |
+
image[55:155, 75:205, :] = 28
|
| 140 |
+
for y in range(55, 155, 5):
|
| 141 |
+
image[y:y + 2, 75:205, :] = 65
|
| 142 |
+
surface_mask = np.ones((height, width), dtype=np.uint8)
|
| 143 |
+
carpet_mask = np.zeros((height, width), dtype=np.uint8)
|
| 144 |
+
carpet_mask[55:155, 75:205] = 1
|
| 145 |
+
|
| 146 |
+
maps = app.build_luminance_lighting_maps(image, surface_mask, carpet_mask)
|
| 147 |
+
|
| 148 |
+
self.assertIsNotNone(maps)
|
| 149 |
+
shade = maps["shadeMap"]
|
| 150 |
+
decoded = (
|
| 151 |
+
app.SHADE_MAP_MIN
|
| 152 |
+
+ (shade.astype(np.float32) / 255.0)
|
| 153 |
+
* (app.SHADE_MAP_MAX - app.SHADE_MAP_MIN)
|
| 154 |
+
)
|
| 155 |
+
real_shadow = float(np.median(decoded[:, 12:35]))
|
| 156 |
+
normal_floor = float(np.median(decoded[65:145, 210:230]))
|
| 157 |
+
replaced_carpet = decoded[70:140, 95:185]
|
| 158 |
+
self.assertLess(real_shadow, normal_floor * 0.35)
|
| 159 |
+
self.assertGreater(float(np.median(replaced_carpet)), normal_floor * 0.80)
|
| 160 |
+
self.assertLess(float(np.std(replaced_carpet)), 0.08)
|
| 161 |
+
self.assertEqual(int(maps["reflectionMap"][carpet_mask > 0].max()), 0)
|
| 162 |
+
|
| 163 |
def test_intrinsic_fusion_cannot_weaken_observed_shadow_or_highlight(self):
|
| 164 |
mask = np.ones((8, 12), dtype=np.uint8)
|
| 165 |
intrinsic = np.ones((8, 12), dtype=np.float32)
|
|
|
|
| 191 |
self.assertLessEqual(float(decoded[64, 48]), 0.02)
|
| 192 |
self.assertGreater(float(decoded[42:86, 92:132].max()), 0.0)
|
| 193 |
|
| 194 |
+
def test_reflection_map_excludes_replaced_carpet_and_its_boundary(self):
|
| 195 |
+
height, width = 240, 320
|
| 196 |
+
image = np.full((height, width, 3), 105, dtype=np.uint8)
|
| 197 |
+
image[55:205, 85:255, :] = 245
|
| 198 |
+
image[18:30, 18:30, :] = 235
|
| 199 |
+
surface_mask = np.ones((height, width), dtype=np.uint8)
|
| 200 |
+
carpet_mask = np.zeros((height, width), dtype=np.uint8)
|
| 201 |
+
carpet_mask[55:205, 85:255] = 1
|
| 202 |
+
|
| 203 |
+
reflection = app.build_reflection_map(
|
| 204 |
+
image,
|
| 205 |
+
surface_mask,
|
| 206 |
+
replaced_material_mask=carpet_mask,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
self.assertIsNotNone(reflection)
|
| 210 |
+
boundary = np.zeros_like(carpet_mask, dtype=bool)
|
| 211 |
+
boundary[51:209, 81:259] = True
|
| 212 |
+
boundary[55:205, 85:255] = False
|
| 213 |
+
self.assertEqual(int(reflection[carpet_mask > 0].max()), 0)
|
| 214 |
+
self.assertEqual(int(reflection[boundary].max()), 0)
|
| 215 |
+
|
| 216 |
+
def test_broad_highlight_stays_in_shade_instead_of_reflection(self):
|
| 217 |
+
height, width = 240, 320
|
| 218 |
+
image = np.full((height, width, 3), 115, dtype=np.uint8)
|
| 219 |
+
image[:, 170:, :] = 205
|
| 220 |
+
surface_mask = np.ones((height, width), dtype=np.uint8)
|
| 221 |
+
|
| 222 |
+
maps = app.build_luminance_lighting_maps(image, surface_mask)
|
| 223 |
+
|
| 224 |
+
self.assertIsNotNone(maps)
|
| 225 |
+
shade = app.decode_relative_map(
|
| 226 |
+
maps["shadeMap"],
|
| 227 |
+
app.SHADE_MAP_MIN,
|
| 228 |
+
app.SHADE_MAP_MAX,
|
| 229 |
+
)
|
| 230 |
+
reflection = maps["reflectionMap"].astype(np.float32) / 255.0
|
| 231 |
+
self.assertGreater(float(np.median(shade[:, 230:285])), 1.20)
|
| 232 |
+
self.assertLess(float(np.median(reflection[:, 230:285])), 0.03)
|
| 233 |
+
|
| 234 |
def test_intrinsic_shading_inversion_is_corrected_against_room_luminance(self):
|
| 235 |
height, width = 160, 180
|
| 236 |
image = np.zeros((height, width, 3), dtype=np.uint8)
|
visualizer.gpu.toml
CHANGED
|
@@ -20,11 +20,14 @@ enable_depth_estimation = true
|
|
| 20 |
enable_moge_geometry = true
|
| 21 |
enable_plane_fit = true
|
| 22 |
enable_multi_plane_surfaces = true
|
|
|
|
| 23 |
enable_intrinsic_shading = true
|
| 24 |
enable_shading_transfer = true
|
| 25 |
enable_sam_refinement = false
|
| 26 |
enable_floor_mask_cleanup = false
|
| 27 |
warm_start_models = true
|
|
|
|
|
|
|
| 28 |
bundle_image_format = "jpeg"
|
| 29 |
bundle_image_quality = 92
|
| 30 |
data_dir = "data"
|
|
|
|
| 20 |
enable_moge_geometry = true
|
| 21 |
enable_plane_fit = true
|
| 22 |
enable_multi_plane_surfaces = true
|
| 23 |
+
enable_wall_segments = true
|
| 24 |
enable_intrinsic_shading = true
|
| 25 |
enable_shading_transfer = true
|
| 26 |
enable_sam_refinement = false
|
| 27 |
enable_floor_mask_cleanup = false
|
| 28 |
warm_start_models = true
|
| 29 |
+
debug_artifacts_enabled = false
|
| 30 |
+
conversion_target_ms = 30000
|
| 31 |
bundle_image_format = "jpeg"
|
| 32 |
bundle_image_quality = 92
|
| 33 |
data_dir = "data"
|
visualizer.hf.toml
CHANGED
|
@@ -20,9 +20,12 @@ enable_depth_estimation = true
|
|
| 20 |
enable_moge_geometry = true
|
| 21 |
enable_plane_fit = true
|
| 22 |
enable_multi_plane_surfaces = true
|
|
|
|
| 23 |
enable_intrinsic_shading = true
|
| 24 |
enable_shading_transfer = true
|
| 25 |
enable_sam_refinement = true
|
|
|
|
|
|
|
| 26 |
data_dir = "data"
|
| 27 |
|
| 28 |
[surface_mapping]
|
|
|
|
| 20 |
enable_moge_geometry = true
|
| 21 |
enable_plane_fit = true
|
| 22 |
enable_multi_plane_surfaces = true
|
| 23 |
+
enable_wall_segments = true
|
| 24 |
enable_intrinsic_shading = true
|
| 25 |
enable_shading_transfer = true
|
| 26 |
enable_sam_refinement = true
|
| 27 |
+
debug_artifacts_enabled = false
|
| 28 |
+
conversion_target_ms = 30000
|
| 29 |
data_dir = "data"
|
| 30 |
|
| 31 |
[surface_mapping]
|
visualizer.local.toml
CHANGED
|
@@ -14,6 +14,7 @@ sam2_checkpoint = ""
|
|
| 14 |
enable_depth_estimation = false
|
| 15 |
enable_plane_fit = true
|
| 16 |
enable_multi_plane_surfaces = true
|
|
|
|
| 17 |
enable_intrinsic_shading = false
|
| 18 |
enable_shading_transfer = true
|
| 19 |
enable_sam_refinement = false
|
|
|
|
| 14 |
enable_depth_estimation = false
|
| 15 |
enable_plane_fit = true
|
| 16 |
enable_multi_plane_surfaces = true
|
| 17 |
+
enable_wall_segments = true
|
| 18 |
enable_intrinsic_shading = false
|
| 19 |
enable_shading_transfer = true
|
| 20 |
enable_sam_refinement = false
|
visualizer.segformer.toml
CHANGED
|
@@ -15,6 +15,7 @@ sam2_checkpoint = ""
|
|
| 15 |
enable_depth_estimation = false
|
| 16 |
enable_plane_fit = true
|
| 17 |
enable_multi_plane_surfaces = true
|
|
|
|
| 18 |
enable_intrinsic_shading = false
|
| 19 |
enable_shading_transfer = true
|
| 20 |
enable_sam_refinement = false
|
|
|
|
| 15 |
enable_depth_estimation = false
|
| 16 |
enable_plane_fit = true
|
| 17 |
enable_multi_plane_surfaces = true
|
| 18 |
+
enable_wall_segments = true
|
| 19 |
enable_intrinsic_shading = false
|
| 20 |
enable_shading_transfer = true
|
| 21 |
enable_sam_refinement = false
|