github-actions[bot] commited on
Commit
bcb16c3
·
1 Parent(s): 9365782

Automated Deploy: 5acd2f365b06d21726c0ae83b7bfd7a88af2460c

Browse files
Files changed (1) hide show
  1. app.py +284 -284
app.py CHANGED
@@ -276,35 +276,35 @@ SURFACE_EDGE_KERNEL_RATIO = float(config_value(
276
  "edge_kernel_ratio",
277
  "0.006",
278
  ))
279
- SURFACE_EDGE_DILATION_ITERATIONS = int(config_value(
280
- "SURFACE_EDGE_DILATION_ITERATIONS",
281
- "surface_mapping",
282
- "edge_dilation_iterations",
283
- "2",
284
- ))
285
- ENABLE_SOFT_FLOOR_COVERING_EXPANSION = str(config_value(
286
- "ENABLE_SOFT_FLOOR_COVERING_EXPANSION",
287
- "surface_mapping",
288
- "soft_floor_covering_expansion_enabled",
289
- "1",
290
- )).lower() in {"1", "true", "yes", "on"}
291
- SOFT_FLOOR_COVERING_KERNEL_RATIO = float(config_value(
292
- "SOFT_FLOOR_COVERING_KERNEL_RATIO",
293
- "surface_mapping",
294
- "soft_floor_covering_kernel_ratio",
295
- "0.008",
296
- ))
297
- SOFT_FLOOR_COVERING_DILATION_ITERATIONS = int(config_value(
298
- "SOFT_FLOOR_COVERING_DILATION_ITERATIONS",
299
- "surface_mapping",
300
- "soft_floor_covering_dilation_iterations",
301
- "2",
302
- ))
303
- SURFACE_UV_MIN_COVERAGE = float(config_value(
304
- "SURFACE_UV_MIN_COVERAGE",
305
- "surface_mapping",
306
- "uv_min_coverage",
307
- "0.995",
308
  ))
309
  SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO = float(config_value(
310
  "SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO",
@@ -487,14 +487,14 @@ FLOOR_SURFACE_CLASSES = {
487
  "floor", "road", "sidewalk", "ground", "field", "grass", "sand",
488
  "runway", "dirt track", "land", "stairs", "step",
489
  }
490
- REJECT_SURFACE_CLASSES = {"wall", "ceiling", "building", "sky", "window"}
491
- SOFT_FLOOR_COVERING_CLASSES = {"rug", "carpet"}
492
- OCCLUDER_CLASSES = {
493
- "bed", "cabinet", "person", "door", "table", "plant", "curtain", "chair",
494
- "car", "painting", "sofa", "shelf", "mirror", "armchair", "seat", "desk",
495
- "wardrobe", "lamp", "bathtub", "railing", "cushion", "base", "box",
496
- "column", "chest of drawers", "counter", "sink", "fireplace",
497
- "refrigerator", "bookcase", "blind", "coffee table", "toilet", "bench",
498
  "countertop", "stove", "kitchen island", "computer", "swivel chair",
499
  "bar", "ottoman", "bottle", "buffet", "poster", "towel", "television",
500
  "washer", "plaything", "stool", "basket", "bag", "cradle", "oven",
@@ -1141,10 +1141,10 @@ def scaled_odd_kernel_size(
1141
  return size | 1
1142
 
1143
 
1144
- def improve_surface_edge_coverage(
1145
- surface: np.ndarray,
1146
- protected_mask: np.ndarray,
1147
- ) -> tuple[np.ndarray, dict]:
1148
  h, w = surface.shape[:2]
1149
  before = int(surface.sum())
1150
  repaired = surface.astype(np.uint8).copy()
@@ -1165,81 +1165,81 @@ def improve_surface_edge_coverage(
1165
  repaired = (repaired > 0).astype(np.uint8)
1166
  after = int(repaired.sum())
1167
 
1168
- return repaired, {
1169
- "surfacePixelsBeforeEdgeFix": before,
1170
- "surfacePixelsAfterEdgeFix": after,
1171
- "surfaceEdgeCloseKernel": close_size,
1172
- "surfaceEdgeKernel": edge_size,
1173
- "surfaceEdgeDilationIterations": SURFACE_EDGE_DILATION_ITERATIONS,
1174
- }
1175
-
1176
-
1177
- def expand_surface_over_soft_floor_coverings(
1178
- surface: np.ndarray,
1179
- soft_covering_mask: np.ndarray,
1180
- protected_mask: np.ndarray,
1181
- ) -> tuple[np.ndarray, dict]:
1182
- h, w = surface.shape[:2]
1183
- before = int(surface.sum())
1184
- soft_pixels = int(soft_covering_mask.sum())
1185
- metadata = {
1186
- "softFloorCoveringExpansionEnabled": ENABLE_SOFT_FLOOR_COVERING_EXPANSION,
1187
- "softFloorCoveringExpansionApplied": False,
1188
- "softFloorCoveringExpansionReason": (
1189
- "disabled" if not ENABLE_SOFT_FLOOR_COVERING_EXPANSION else "unavailable"
1190
- ),
1191
- "softFloorCoveringPixels": soft_pixels,
1192
- "softFloorCoveringPixelsBefore": before,
1193
- "softFloorCoveringPixelsAfter": before,
1194
- "softFloorCoveringKernel": 0,
1195
- "softFloorCoveringDilationIterations": SOFT_FLOOR_COVERING_DILATION_ITERATIONS,
1196
- }
1197
- if not ENABLE_SOFT_FLOOR_COVERING_EXPANSION:
1198
- return surface, metadata
1199
- if before == 0:
1200
- metadata["softFloorCoveringExpansionReason"] = "empty-surface"
1201
- return surface, metadata
1202
- if soft_pixels == 0:
1203
- metadata["softFloorCoveringExpansionReason"] = "no-soft-floor-covering"
1204
- return surface, metadata
1205
- if SOFT_FLOOR_COVERING_DILATION_ITERATIONS <= 0:
1206
- metadata["softFloorCoveringExpansionReason"] = "zero-dilation"
1207
- return surface, metadata
1208
-
1209
- kernel_size = scaled_odd_kernel_size(
1210
- h,
1211
- w,
1212
- SOFT_FLOOR_COVERING_KERNEL_RATIO,
1213
- minimum=3,
1214
- )
1215
- metadata["softFloorCoveringKernel"] = kernel_size
1216
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
1217
- surface_reach = cv2.dilate(
1218
- surface.astype(np.uint8),
1219
- kernel,
1220
- iterations=SOFT_FLOOR_COVERING_DILATION_ITERATIONS,
1221
- )
1222
- soft_reach = cv2.dilate(soft_covering_mask.astype(np.uint8), kernel, iterations=1)
1223
- protected = protected_mask.astype(bool)
1224
- candidates = (surface_reach > 0) & (soft_reach > 0) & (~protected)
1225
- expanded = surface.astype(np.uint8).copy()
1226
- expanded[candidates] = 1
1227
- expanded[protected] = 0
1228
- expanded = (expanded > 0).astype(np.uint8)
1229
- after = int(expanded.sum())
1230
- metadata["softFloorCoveringPixelsAfter"] = after
1231
- metadata["softFloorCoveringExpansionApplied"] = after > before
1232
- metadata["softFloorCoveringExpansionReason"] = (
1233
- "expanded-near-soft-floor-covering" if after > before else "no-adjacent-candidates"
1234
- )
1235
- return expanded, metadata
1236
-
1237
-
1238
- def filter_surface_by_floor_geometry(
1239
- surface: np.ndarray,
1240
- geometry: dict | None,
1241
- plane: dict | None,
1242
- ) -> tuple[np.ndarray, dict]:
1243
  before = int(surface.sum())
1244
  metadata = {
1245
  "geometrySurfaceFilterEnabled": ENABLE_GEOMETRY_SURFACE_FILTER,
@@ -1357,7 +1357,7 @@ def detect_vanishing_point(img_np: np.ndarray, floor_mask: np.ndarray):
1357
 
1358
  h, w = img_np.shape[:2]
1359
  candidates = []
1360
- for line in lines[:, 0, :]:
1361
  x1, y1, x2, y2 = [float(v) for v in line]
1362
  dx, dy = x2 - x1, y2 - y1
1363
  length = float(np.hypot(dx, dy))
@@ -2365,98 +2365,98 @@ def build_floor_surface_mask(
2365
  geometry: dict | None,
2366
  plane: dict | None,
2367
  ):
2368
- h, w = floor_mask.shape[:2]
2369
- kern_size = max(5, min(h, w) // 160) | 1
2370
- kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size))
2371
- occluder_mask = np.isin(seg_map, class_ids(OCCLUDER_CLASSES)).astype(np.uint8)
2372
- occ_dilated = cv2.dilate(occluder_mask, kern, iterations=2)
2373
- soft_covering_mask = np.isin(seg_map, class_ids(SOFT_FLOOR_COVERING_CLASSES)).astype(np.uint8)
2374
- reject_mask = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES)).astype(np.uint8)
2375
- reject_dilated = cv2.dilate(reject_mask, kern, iterations=2)
2376
- hard_protected_mask = (occ_dilated > 0) | (reject_dilated > 0)
2377
- normal_edge_protected_mask = hard_protected_mask | (soft_covering_mask > 0)
2378
-
2379
- surface = floor_mask.copy()
2380
- surface[reject_dilated > 0] = 0
2381
- surface[soft_covering_mask > 0] = 0
2382
- if not surface.any():
2383
- surface = floor_mask.copy()
2384
- surface[soft_covering_mask > 0] = 0
2385
-
2386
- contours, _ = cv2.findContours(surface, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
2387
- if contours:
2388
- filled = np.zeros((h, w), dtype=np.uint8)
2389
- cv2.drawContours(filled, contours, -1, 1, cv2.FILLED)
2390
- filled[reject_dilated > 0] = 0
2391
- filled[soft_covering_mask > 0] = 0
2392
- surface = filled
2393
-
2394
- if quad is not None and surface.any():
2395
- plane_mask = np.zeros((h, w), dtype=np.uint8)
2396
- cv2.fillConvexPoly(plane_mask, np.round(quad).astype(np.int32), 1)
2397
- plane_mask[reject_dilated > 0] = 0
2398
- plane_mask[soft_covering_mask > 0] = 0
2399
- near_floor = cv2.dilate(surface, kern, iterations=6)
2400
- surface = cv2.bitwise_or(surface, cv2.bitwise_and(plane_mask, near_floor))
2401
- surface[soft_covering_mask > 0] = 0
2402
-
2403
- surface[occ_dilated > 0] = 0
2404
- surface[soft_covering_mask > 0] = 0
2405
- if depth is not None and floor_mask.any():
2406
- floor_depth = depth[(floor_mask > 0) & np.isfinite(depth)]
2407
- if floor_depth.size == 0:
2408
- floor_depth = None
2409
  else:
2410
  floor_depth = None
2411
  if floor_depth is not None:
2412
  lo, hi = float(np.percentile(floor_depth, 2)), float(np.percentile(floor_depth, 98))
2413
  margin = max(0.08, (hi - lo) * 0.35)
2414
  depth_keep = (depth >= lo - margin) & (depth <= hi + margin)
2415
- surface = (surface & depth_keep.astype(np.uint8)).astype(np.uint8)
2416
- surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1)
2417
- surface[occ_dilated > 0] = 0
2418
- surface[reject_dilated > 0] = 0
2419
- surface[soft_covering_mask > 0] = 0
2420
-
2421
- surface, geometry_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2422
- surface[occ_dilated > 0] = 0
2423
- surface[reject_dilated > 0] = 0
2424
- surface[soft_covering_mask > 0] = 0
2425
-
2426
- surface = clean_floor_mask(surface)
2427
- surface[occ_dilated > 0] = 0
2428
- surface[reject_dilated > 0] = 0
2429
- surface[soft_covering_mask > 0] = 0
2430
-
2431
- surface, edge_metadata = improve_surface_edge_coverage(surface, normal_edge_protected_mask)
2432
- surface, post_edge_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2433
- surface[occ_dilated > 0] = 0
2434
- surface[reject_dilated > 0] = 0
2435
- surface[soft_covering_mask > 0] = 0
2436
- post_edge_filter_metadata = {
2437
- f"postEdge{k[0].upper()}{k[1:]}": value
2438
- for k, value in post_edge_filter_metadata.items()
2439
- }
2440
-
2441
- surface, soft_covering_metadata = expand_surface_over_soft_floor_coverings(
2442
- surface,
2443
- soft_covering_mask,
2444
- hard_protected_mask,
2445
- )
2446
- surface, post_soft_covering_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2447
- surface[occ_dilated > 0] = 0
2448
- surface[reject_dilated > 0] = 0
2449
- post_soft_covering_filter_metadata = {
2450
- f"postSoftFloorCovering{k[0].upper()}{k[1:]}": value
2451
- for k, value in post_soft_covering_filter_metadata.items()
2452
- }
2453
- return surface, {
2454
- **geometry_filter_metadata,
2455
- **edge_metadata,
2456
- **post_edge_filter_metadata,
2457
- **soft_covering_metadata,
2458
- **post_soft_covering_filter_metadata,
2459
- }
2460
 
2461
 
2462
  def run_segmentation(img: Image.Image, img_np: np.ndarray):
@@ -2859,25 +2859,25 @@ def build_segmentation_bundle(contents: bytes):
2859
  shade_map = lighting_maps.get("shadeMap")
2860
  showroom_shade_map = lighting_maps.get("showroomShadeMap")
2861
  reflection_map = lighting_maps.get("reflectionMap")
2862
- print(
2863
- "[TIMING] Lighting map construction took "
2864
- f"{time.perf_counter() - t0:.3f} seconds "
2865
- f"(source={lighting_source}, reflections={reflection_map is not None})",
2866
- flush=True,
2867
- )
2868
-
2869
- t0 = time.perf_counter()
2870
- floor_direction = analyze_floor_direction_for_surface_mask(img_np, surface_mask)
2871
- print(
2872
- "[TIMING] Floor direction analysis took "
2873
- f"{time.perf_counter() - t0:.3f} seconds "
2874
- f"(angle={floor_direction.get('angleDegrees')}, confidence={floor_direction.get('confidence')})",
2875
- flush=True,
2876
- )
2877
-
2878
- t0 = time.perf_counter()
2879
- segments = []
2880
- models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
2881
 
2882
  if len(surface_indices) >= min_floor_area:
2883
  segments.append({
@@ -2908,12 +2908,12 @@ def build_segmentation_bundle(contents: bytes):
2908
  "metadata": {
2909
  "segmenter": segmenter_metadata_name(),
2910
  "segmentationModel": models["segmentation"]["name"],
2911
- "floorPixels": int(floor_mask.sum()),
2912
- "surfacePixels": int(surface_mask.sum()),
2913
- "floorDirection": floor_direction,
2914
- **sam_metadata,
2915
- **edge_metadata,
2916
- **mapping_metadata,
2917
  "depthEnabled": depth is not None,
2918
  "shadingEnabled": shade_map is not None,
2919
  "planeFitEnabled": ENABLE_PLANE_FIT,
@@ -3318,10 +3318,10 @@ def encode_png_data_url(image_bgr: np.ndarray) -> str:
3318
  return f"data:image/png;base64,{payload}"
3319
 
3320
 
3321
- def floor_direction_response(result, segmentation) -> dict:
3322
- overlay_image_base64 = None
3323
- if result.overlay_bgr is not None:
3324
- overlay_image_base64 = encode_png_data_url(result.overlay_bgr)
3325
 
3326
  return {
3327
  "angle_degrees": result.angle_degrees,
@@ -3351,58 +3351,58 @@ def floor_direction_response(result, segmentation) -> dict:
3351
  for line in result.dominant_lines
3352
  ],
3353
  "warnings": result.warnings,
3354
- "overlay_image_base64": overlay_image_base64,
3355
- }
3356
-
3357
-
3358
- def floor_direction_metadata(result, segmentation) -> dict:
3359
- return {
3360
- "source": "backend-floor-direction",
3361
- "angleDegrees": result.angle_degrees,
3362
- "secondaryAngleDegrees": result.secondary_angle_degrees,
3363
- "directionLabel": result.direction_label,
3364
- "confidence": result.confidence,
3365
- "floorAreaRatio": result.floor_area_ratio,
3366
- "lineCount": result.line_count,
3367
- "dominantLineCount": result.dominant_line_count,
3368
- "gridPatternDetected": result.grid_pattern_detected,
3369
- "warnings": result.warnings,
3370
- "segmentation": {
3371
- "label": segmentation.label,
3372
- "confidence": segmentation.confidence,
3373
- "polygonCount": len(segmentation.polygons),
3374
- "sourcePath": segmentation.source_path,
3375
- },
3376
- }
3377
-
3378
-
3379
- def analyze_floor_direction_for_surface_mask(
3380
- img_np: np.ndarray,
3381
- surface_mask: np.ndarray,
3382
- ) -> dict:
3383
- h, w = img_np.shape[:2]
3384
- polygons = mask_to_polygons(
3385
- surface_mask,
3386
- min_area=max(32.0, float(w * h) * 0.001),
3387
- simplify_epsilon=2.0,
3388
- )
3389
- floor_segmentation = parse_floor_segmentation({
3390
- "label": "floor",
3391
- "confidence": 1.0,
3392
- "width": int(w),
3393
- "height": int(h),
3394
- "polygons": polygons,
3395
- })
3396
- result = analyze_floor_direction_from_segmentation(
3397
- cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR),
3398
- floor_segmentation,
3399
- include_overlay=False,
3400
- )
3401
- return floor_direction_metadata(result, floor_segmentation)
3402
-
3403
-
3404
- @app.post("/oneformer/polygons")
3405
- async def oneformer_polygons(
3406
  file: UploadFile = File(...),
3407
  threshold: float = Form(0.5),
3408
  mask_threshold: float = Form(0.5),
 
276
  "edge_kernel_ratio",
277
  "0.006",
278
  ))
279
+ SURFACE_EDGE_DILATION_ITERATIONS = int(config_value(
280
+ "SURFACE_EDGE_DILATION_ITERATIONS",
281
+ "surface_mapping",
282
+ "edge_dilation_iterations",
283
+ "2",
284
+ ))
285
+ ENABLE_SOFT_FLOOR_COVERING_EXPANSION = str(config_value(
286
+ "ENABLE_SOFT_FLOOR_COVERING_EXPANSION",
287
+ "surface_mapping",
288
+ "soft_floor_covering_expansion_enabled",
289
+ "1",
290
+ )).lower() in {"1", "true", "yes", "on"}
291
+ SOFT_FLOOR_COVERING_KERNEL_RATIO = float(config_value(
292
+ "SOFT_FLOOR_COVERING_KERNEL_RATIO",
293
+ "surface_mapping",
294
+ "soft_floor_covering_kernel_ratio",
295
+ "0.008",
296
+ ))
297
+ SOFT_FLOOR_COVERING_DILATION_ITERATIONS = int(config_value(
298
+ "SOFT_FLOOR_COVERING_DILATION_ITERATIONS",
299
+ "surface_mapping",
300
+ "soft_floor_covering_dilation_iterations",
301
+ "2",
302
+ ))
303
+ SURFACE_UV_MIN_COVERAGE = float(config_value(
304
+ "SURFACE_UV_MIN_COVERAGE",
305
+ "surface_mapping",
306
+ "uv_min_coverage",
307
+ "0.995",
308
  ))
309
  SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO = float(config_value(
310
  "SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO",
 
487
  "floor", "road", "sidewalk", "ground", "field", "grass", "sand",
488
  "runway", "dirt track", "land", "stairs", "step",
489
  }
490
+ REJECT_SURFACE_CLASSES = {"wall", "ceiling", "building", "sky", "window"}
491
+ SOFT_FLOOR_COVERING_CLASSES = {"rug", "carpet"}
492
+ OCCLUDER_CLASSES = {
493
+ "bed", "cabinet", "person", "door", "table", "plant", "curtain", "chair",
494
+ "car", "painting", "sofa", "shelf", "mirror", "armchair", "seat", "desk",
495
+ "wardrobe", "lamp", "bathtub", "railing", "cushion", "base", "box",
496
+ "column", "chest of drawers", "counter", "sink", "fireplace",
497
+ "refrigerator", "bookcase", "blind", "coffee table", "toilet", "bench",
498
  "countertop", "stove", "kitchen island", "computer", "swivel chair",
499
  "bar", "ottoman", "bottle", "buffet", "poster", "towel", "television",
500
  "washer", "plaything", "stool", "basket", "bag", "cradle", "oven",
 
1141
  return size | 1
1142
 
1143
 
1144
+ def improve_surface_edge_coverage(
1145
+ surface: np.ndarray,
1146
+ protected_mask: np.ndarray,
1147
+ ) -> tuple[np.ndarray, dict]:
1148
  h, w = surface.shape[:2]
1149
  before = int(surface.sum())
1150
  repaired = surface.astype(np.uint8).copy()
 
1165
  repaired = (repaired > 0).astype(np.uint8)
1166
  after = int(repaired.sum())
1167
 
1168
+ return repaired, {
1169
+ "surfacePixelsBeforeEdgeFix": before,
1170
+ "surfacePixelsAfterEdgeFix": after,
1171
+ "surfaceEdgeCloseKernel": close_size,
1172
+ "surfaceEdgeKernel": edge_size,
1173
+ "surfaceEdgeDilationIterations": SURFACE_EDGE_DILATION_ITERATIONS,
1174
+ }
1175
+
1176
+
1177
+ def expand_surface_over_soft_floor_coverings(
1178
+ surface: np.ndarray,
1179
+ soft_covering_mask: np.ndarray,
1180
+ protected_mask: np.ndarray,
1181
+ ) -> tuple[np.ndarray, dict]:
1182
+ h, w = surface.shape[:2]
1183
+ before = int(surface.sum())
1184
+ soft_pixels = int(soft_covering_mask.sum())
1185
+ metadata = {
1186
+ "softFloorCoveringExpansionEnabled": ENABLE_SOFT_FLOOR_COVERING_EXPANSION,
1187
+ "softFloorCoveringExpansionApplied": False,
1188
+ "softFloorCoveringExpansionReason": (
1189
+ "disabled" if not ENABLE_SOFT_FLOOR_COVERING_EXPANSION else "unavailable"
1190
+ ),
1191
+ "softFloorCoveringPixels": soft_pixels,
1192
+ "softFloorCoveringPixelsBefore": before,
1193
+ "softFloorCoveringPixelsAfter": before,
1194
+ "softFloorCoveringKernel": 0,
1195
+ "softFloorCoveringDilationIterations": SOFT_FLOOR_COVERING_DILATION_ITERATIONS,
1196
+ }
1197
+ if not ENABLE_SOFT_FLOOR_COVERING_EXPANSION:
1198
+ return surface, metadata
1199
+ if before == 0:
1200
+ metadata["softFloorCoveringExpansionReason"] = "empty-surface"
1201
+ return surface, metadata
1202
+ if soft_pixels == 0:
1203
+ metadata["softFloorCoveringExpansionReason"] = "no-soft-floor-covering"
1204
+ return surface, metadata
1205
+ if SOFT_FLOOR_COVERING_DILATION_ITERATIONS <= 0:
1206
+ metadata["softFloorCoveringExpansionReason"] = "zero-dilation"
1207
+ return surface, metadata
1208
+
1209
+ kernel_size = scaled_odd_kernel_size(
1210
+ h,
1211
+ w,
1212
+ SOFT_FLOOR_COVERING_KERNEL_RATIO,
1213
+ minimum=3,
1214
+ )
1215
+ metadata["softFloorCoveringKernel"] = kernel_size
1216
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
1217
+ surface_reach = cv2.dilate(
1218
+ surface.astype(np.uint8),
1219
+ kernel,
1220
+ iterations=SOFT_FLOOR_COVERING_DILATION_ITERATIONS,
1221
+ )
1222
+ soft_reach = cv2.dilate(soft_covering_mask.astype(np.uint8), kernel, iterations=1)
1223
+ protected = protected_mask.astype(bool)
1224
+ candidates = (surface_reach > 0) & (soft_reach > 0) & (~protected)
1225
+ expanded = surface.astype(np.uint8).copy()
1226
+ expanded[candidates] = 1
1227
+ expanded[protected] = 0
1228
+ expanded = (expanded > 0).astype(np.uint8)
1229
+ after = int(expanded.sum())
1230
+ metadata["softFloorCoveringPixelsAfter"] = after
1231
+ metadata["softFloorCoveringExpansionApplied"] = after > before
1232
+ metadata["softFloorCoveringExpansionReason"] = (
1233
+ "expanded-near-soft-floor-covering" if after > before else "no-adjacent-candidates"
1234
+ )
1235
+ return expanded, metadata
1236
+
1237
+
1238
+ def filter_surface_by_floor_geometry(
1239
+ surface: np.ndarray,
1240
+ geometry: dict | None,
1241
+ plane: dict | None,
1242
+ ) -> tuple[np.ndarray, dict]:
1243
  before = int(surface.sum())
1244
  metadata = {
1245
  "geometrySurfaceFilterEnabled": ENABLE_GEOMETRY_SURFACE_FILTER,
 
1357
 
1358
  h, w = img_np.shape[:2]
1359
  candidates = []
1360
+ for line in lines.reshape(-1, 4):
1361
  x1, y1, x2, y2 = [float(v) for v in line]
1362
  dx, dy = x2 - x1, y2 - y1
1363
  length = float(np.hypot(dx, dy))
 
2365
  geometry: dict | None,
2366
  plane: dict | None,
2367
  ):
2368
+ h, w = floor_mask.shape[:2]
2369
+ kern_size = max(5, min(h, w) // 160) | 1
2370
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size))
2371
+ occluder_mask = np.isin(seg_map, class_ids(OCCLUDER_CLASSES)).astype(np.uint8)
2372
+ occ_dilated = cv2.dilate(occluder_mask, kern, iterations=2)
2373
+ soft_covering_mask = np.isin(seg_map, class_ids(SOFT_FLOOR_COVERING_CLASSES)).astype(np.uint8)
2374
+ reject_mask = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES)).astype(np.uint8)
2375
+ reject_dilated = cv2.dilate(reject_mask, kern, iterations=2)
2376
+ hard_protected_mask = (occ_dilated > 0) | (reject_dilated > 0)
2377
+ normal_edge_protected_mask = hard_protected_mask | (soft_covering_mask > 0)
2378
+
2379
+ surface = floor_mask.copy()
2380
+ surface[reject_dilated > 0] = 0
2381
+ surface[soft_covering_mask > 0] = 0
2382
+ if not surface.any():
2383
+ surface = floor_mask.copy()
2384
+ surface[soft_covering_mask > 0] = 0
2385
+
2386
+ contours, _ = cv2.findContours(surface, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
2387
+ if contours:
2388
+ filled = np.zeros((h, w), dtype=np.uint8)
2389
+ cv2.drawContours(filled, contours, -1, 1, cv2.FILLED)
2390
+ filled[reject_dilated > 0] = 0
2391
+ filled[soft_covering_mask > 0] = 0
2392
+ surface = filled
2393
+
2394
+ if quad is not None and surface.any():
2395
+ plane_mask = np.zeros((h, w), dtype=np.uint8)
2396
+ cv2.fillConvexPoly(plane_mask, np.round(quad).astype(np.int32), 1)
2397
+ plane_mask[reject_dilated > 0] = 0
2398
+ plane_mask[soft_covering_mask > 0] = 0
2399
+ near_floor = cv2.dilate(surface, kern, iterations=6)
2400
+ surface = cv2.bitwise_or(surface, cv2.bitwise_and(plane_mask, near_floor))
2401
+ surface[soft_covering_mask > 0] = 0
2402
+
2403
+ surface[occ_dilated > 0] = 0
2404
+ surface[soft_covering_mask > 0] = 0
2405
+ if depth is not None and floor_mask.any():
2406
+ floor_depth = depth[(floor_mask > 0) & np.isfinite(depth)]
2407
+ if floor_depth.size == 0:
2408
+ floor_depth = None
2409
  else:
2410
  floor_depth = None
2411
  if floor_depth is not None:
2412
  lo, hi = float(np.percentile(floor_depth, 2)), float(np.percentile(floor_depth, 98))
2413
  margin = max(0.08, (hi - lo) * 0.35)
2414
  depth_keep = (depth >= lo - margin) & (depth <= hi + margin)
2415
+ surface = (surface & depth_keep.astype(np.uint8)).astype(np.uint8)
2416
+ surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1)
2417
+ surface[occ_dilated > 0] = 0
2418
+ surface[reject_dilated > 0] = 0
2419
+ surface[soft_covering_mask > 0] = 0
2420
+
2421
+ surface, geometry_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2422
+ surface[occ_dilated > 0] = 0
2423
+ surface[reject_dilated > 0] = 0
2424
+ surface[soft_covering_mask > 0] = 0
2425
+
2426
+ surface = clean_floor_mask(surface)
2427
+ surface[occ_dilated > 0] = 0
2428
+ surface[reject_dilated > 0] = 0
2429
+ surface[soft_covering_mask > 0] = 0
2430
+
2431
+ surface, edge_metadata = improve_surface_edge_coverage(surface, normal_edge_protected_mask)
2432
+ surface, post_edge_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2433
+ surface[occ_dilated > 0] = 0
2434
+ surface[reject_dilated > 0] = 0
2435
+ surface[soft_covering_mask > 0] = 0
2436
+ post_edge_filter_metadata = {
2437
+ f"postEdge{k[0].upper()}{k[1:]}": value
2438
+ for k, value in post_edge_filter_metadata.items()
2439
+ }
2440
+
2441
+ surface, soft_covering_metadata = expand_surface_over_soft_floor_coverings(
2442
+ surface,
2443
+ soft_covering_mask,
2444
+ hard_protected_mask,
2445
+ )
2446
+ surface, post_soft_covering_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2447
+ surface[occ_dilated > 0] = 0
2448
+ surface[reject_dilated > 0] = 0
2449
+ post_soft_covering_filter_metadata = {
2450
+ f"postSoftFloorCovering{k[0].upper()}{k[1:]}": value
2451
+ for k, value in post_soft_covering_filter_metadata.items()
2452
+ }
2453
+ return surface, {
2454
+ **geometry_filter_metadata,
2455
+ **edge_metadata,
2456
+ **post_edge_filter_metadata,
2457
+ **soft_covering_metadata,
2458
+ **post_soft_covering_filter_metadata,
2459
+ }
2460
 
2461
 
2462
  def run_segmentation(img: Image.Image, img_np: np.ndarray):
 
2859
  shade_map = lighting_maps.get("shadeMap")
2860
  showroom_shade_map = lighting_maps.get("showroomShadeMap")
2861
  reflection_map = lighting_maps.get("reflectionMap")
2862
+ print(
2863
+ "[TIMING] Lighting map construction took "
2864
+ f"{time.perf_counter() - t0:.3f} seconds "
2865
+ f"(source={lighting_source}, reflections={reflection_map is not None})",
2866
+ flush=True,
2867
+ )
2868
+
2869
+ t0 = time.perf_counter()
2870
+ floor_direction = analyze_floor_direction_for_surface_mask(img_np, surface_mask)
2871
+ print(
2872
+ "[TIMING] Floor direction analysis took "
2873
+ f"{time.perf_counter() - t0:.3f} seconds "
2874
+ f"(angle={floor_direction.get('angleDegrees')}, confidence={floor_direction.get('confidence')})",
2875
+ flush=True,
2876
+ )
2877
+
2878
+ t0 = time.perf_counter()
2879
+ segments = []
2880
+ models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
2881
 
2882
  if len(surface_indices) >= min_floor_area:
2883
  segments.append({
 
2908
  "metadata": {
2909
  "segmenter": segmenter_metadata_name(),
2910
  "segmentationModel": models["segmentation"]["name"],
2911
+ "floorPixels": int(floor_mask.sum()),
2912
+ "surfacePixels": int(surface_mask.sum()),
2913
+ "floorDirection": floor_direction,
2914
+ **sam_metadata,
2915
+ **edge_metadata,
2916
+ **mapping_metadata,
2917
  "depthEnabled": depth is not None,
2918
  "shadingEnabled": shade_map is not None,
2919
  "planeFitEnabled": ENABLE_PLANE_FIT,
 
3318
  return f"data:image/png;base64,{payload}"
3319
 
3320
 
3321
+ def floor_direction_response(result, segmentation) -> dict:
3322
+ overlay_image_base64 = None
3323
+ if result.overlay_bgr is not None:
3324
+ overlay_image_base64 = encode_png_data_url(result.overlay_bgr)
3325
 
3326
  return {
3327
  "angle_degrees": result.angle_degrees,
 
3351
  for line in result.dominant_lines
3352
  ],
3353
  "warnings": result.warnings,
3354
+ "overlay_image_base64": overlay_image_base64,
3355
+ }
3356
+
3357
+
3358
+ def floor_direction_metadata(result, segmentation) -> dict:
3359
+ return {
3360
+ "source": "backend-floor-direction",
3361
+ "angleDegrees": result.angle_degrees,
3362
+ "secondaryAngleDegrees": result.secondary_angle_degrees,
3363
+ "directionLabel": result.direction_label,
3364
+ "confidence": result.confidence,
3365
+ "floorAreaRatio": result.floor_area_ratio,
3366
+ "lineCount": result.line_count,
3367
+ "dominantLineCount": result.dominant_line_count,
3368
+ "gridPatternDetected": result.grid_pattern_detected,
3369
+ "warnings": result.warnings,
3370
+ "segmentation": {
3371
+ "label": segmentation.label,
3372
+ "confidence": segmentation.confidence,
3373
+ "polygonCount": len(segmentation.polygons),
3374
+ "sourcePath": segmentation.source_path,
3375
+ },
3376
+ }
3377
+
3378
+
3379
+ def analyze_floor_direction_for_surface_mask(
3380
+ img_np: np.ndarray,
3381
+ surface_mask: np.ndarray,
3382
+ ) -> dict:
3383
+ h, w = img_np.shape[:2]
3384
+ polygons = mask_to_polygons(
3385
+ surface_mask,
3386
+ min_area=max(32.0, float(w * h) * 0.001),
3387
+ simplify_epsilon=2.0,
3388
+ )
3389
+ floor_segmentation = parse_floor_segmentation({
3390
+ "label": "floor",
3391
+ "confidence": 1.0,
3392
+ "width": int(w),
3393
+ "height": int(h),
3394
+ "polygons": polygons,
3395
+ })
3396
+ result = analyze_floor_direction_from_segmentation(
3397
+ cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR),
3398
+ floor_segmentation,
3399
+ include_overlay=False,
3400
+ )
3401
+ return floor_direction_metadata(result, floor_segmentation)
3402
+
3403
+
3404
+ @app.post("/oneformer/polygons")
3405
+ async def oneformer_polygons(
3406
  file: UploadFile = File(...),
3407
  threshold: float = Form(0.5),
3408
  mask_threshold: float = Form(0.5),