github-actions[bot] commited on
Commit
cb7cbc8
·
1 Parent(s): 22b3e8b

Automated Deploy: 0ae3bce641895457c296473f3a2781e302900b48

Browse files
Files changed (2) hide show
  1. app.py +106 -351
  2. test_floor_geometry.py +3 -116
app.py CHANGED
@@ -318,87 +318,21 @@ SURFACE_PLANE_DISTANCE_METERS = float(config_value(
318
  "plane_distance_threshold_meters",
319
  "0.12",
320
  ))
321
- SURFACE_PLANE_NORMAL_MIN_COS = float(config_value(
322
- "SURFACE_PLANE_NORMAL_MIN_COS",
323
- "surface_mapping",
324
- "plane_normal_min_cos",
325
- "0.45",
326
- ))
327
- SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
328
- "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO",
329
- "surface_mapping",
330
- "plane_filter_min_keep_ratio",
331
- "0.45",
332
- ))
333
- MASK_COMPILER_VERSION = str(config_value(
334
- "MASK_COMPILER_VERSION",
335
- "surface_mapping",
336
- "mask_compiler_version",
337
- "v1",
338
- ))
339
- ENABLE_MASK_COMPILER = str(config_value(
340
- "ENABLE_MASK_COMPILER",
341
- "runtime",
342
- "enable_mask_compiler",
343
- "1",
344
- )).lower() in {"1", "true", "yes", "on"}
345
- ENABLE_FOREGROUND_RISK_MASK = str(config_value(
346
- "ENABLE_FOREGROUND_RISK_MASK",
347
- "runtime",
348
- "enable_foreground_risk_mask",
349
- "1",
350
- )).lower() in {"1", "true", "yes", "on"}
351
- MASK_COMPILER_MIN_KEEP_RATIO = float(config_value(
352
- "MASK_COMPILER_MIN_KEEP_RATIO",
353
- "surface_mapping",
354
- "mask_compiler_min_keep_ratio",
355
- "0.35",
356
- ))
357
- MASK_COMPILER_BOUNDARY_RING_RATIO = float(config_value(
358
- "MASK_COMPILER_BOUNDARY_RING_RATIO",
359
- "surface_mapping",
360
- "mask_compiler_boundary_ring_ratio",
361
- "0.007",
362
- ))
363
- MASK_COMPILER_PROTECTED_DILATION_RATIO = float(config_value(
364
- "MASK_COMPILER_PROTECTED_DILATION_RATIO",
365
- "surface_mapping",
366
- "mask_compiler_protected_dilation_ratio",
367
- "0.011",
368
- ))
369
- MASK_COMPILER_COLOR_PERCENTILE = float(config_value(
370
- "MASK_COMPILER_COLOR_PERCENTILE",
371
- "surface_mapping",
372
- "mask_compiler_color_percentile",
373
- "84",
374
- ))
375
- MASK_COMPILER_DETAIL_PERCENTILE = float(config_value(
376
- "MASK_COMPILER_DETAIL_PERCENTILE",
377
- "surface_mapping",
378
- "mask_compiler_detail_percentile",
379
- "82",
380
- ))
381
- MASK_COMPILER_COLOR_DISTANCE_THRESHOLD = float(config_value(
382
- "MASK_COMPILER_COLOR_DISTANCE_THRESHOLD",
383
- "surface_mapping",
384
- "mask_compiler_color_distance_threshold",
385
- "18",
386
- ))
387
- MASK_COMPILER_DETAIL_THRESHOLD = float(config_value(
388
- "MASK_COMPILER_DETAIL_THRESHOLD",
389
- "surface_mapping",
390
- "mask_compiler_detail_threshold",
391
- "34",
392
- ))
393
- MASK_COMPILER_EDGE_REPAIR_RATIO = float(config_value(
394
- "MASK_COMPILER_EDGE_REPAIR_RATIO",
395
- "surface_mapping",
396
- "mask_compiler_edge_repair_ratio",
397
- "0.006",
398
- ))
399
-
400
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
401
- seg_processor = None
402
  seg_model = None
403
  segmentation_backend = "segformer"
404
  oneformer_polygon_processor = None
@@ -1175,253 +1109,17 @@ def wall_subtract(mask: np.ndarray, seg_map: np.ndarray, dilation: int = 1) -> n
1175
  return result
1176
 
1177
 
1178
- def scaled_odd_kernel_size(
1179
- height: int,
1180
- width: int,
1181
- ratio: float,
1182
- minimum: int = 3,
1183
- maximum: int = 31,
1184
- ) -> int:
1185
- min_side = max(3, min(height, width))
1186
- size = max(minimum, int(round(min_side * ratio)))
1187
- size = min(maximum, size)
1188
- return size | 1
1189
-
1190
-
1191
- def build_floor_boundary_mask(image_np: np.ndarray, floor_mask: np.ndarray) -> np.ndarray:
1192
- if not floor_mask.any():
1193
- return np.zeros_like(floor_mask, dtype=np.uint8)
1194
-
1195
- gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
1196
- canny_low = 48
1197
- canny_high = 150
1198
- edges = cv2.Canny(gray, canny_low, canny_high)
1199
- ring_size = scaled_odd_kernel_size(
1200
- floor_mask.shape[0],
1201
- floor_mask.shape[1],
1202
- MASK_COMPILER_BOUNDARY_RING_RATIO,
1203
- minimum=3,
1204
- )
1205
- ring_kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ring_size, ring_size))
1206
- outer = cv2.dilate(floor_mask.astype(np.uint8), ring_kern, iterations=1)
1207
- inner = cv2.erode(floor_mask.astype(np.uint8), ring_kern, iterations=1)
1208
- boundary_ring = cv2.subtract(outer, inner)
1209
- boundary_edges = cv2.bitwise_and(edges, boundary_ring)
1210
- return (boundary_edges > 0).astype(np.uint8)
1211
-
1212
-
1213
- def build_foreground_risk_mask(
1214
- image_np: np.ndarray,
1215
- floor_mask: np.ndarray,
1216
- seg_map: np.ndarray,
1217
- boundary_mask: np.ndarray,
1218
- ) -> np.ndarray:
1219
- if not ENABLE_FOREGROUND_RISK_MASK or not floor_mask.any():
1220
- return np.zeros_like(floor_mask, dtype=np.uint8)
1221
-
1222
- floor_pixels = image_np[floor_mask > 0]
1223
- if floor_pixels.size == 0:
1224
- return np.zeros_like(floor_mask, dtype=np.uint8)
1225
-
1226
- lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB).astype(np.float32)
1227
- floor_lab = lab[floor_mask > 0]
1228
- floor_mean = floor_lab.mean(axis=0)
1229
- color_distance = np.linalg.norm(lab - floor_mean[None, None, :], axis=2)
1230
-
1231
- gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY).astype(np.float32)
1232
- sobel_x = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
1233
- sobel_y = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
1234
- detail = cv2.magnitude(sobel_x, sobel_y)
1235
-
1236
- floor_color_distance = color_distance[floor_mask > 0]
1237
- floor_detail = detail[floor_mask > 0]
1238
- color_threshold = max(
1239
- MASK_COMPILER_COLOR_DISTANCE_THRESHOLD,
1240
- float(np.percentile(floor_color_distance, MASK_COMPILER_COLOR_PERCENTILE)),
1241
- )
1242
- detail_threshold = max(
1243
- MASK_COMPILER_DETAIL_THRESHOLD,
1244
- float(np.percentile(floor_detail, MASK_COMPILER_DETAIL_PERCENTILE)),
1245
- )
1246
-
1247
- risk = (color_distance >= color_threshold) | (detail >= detail_threshold)
1248
- risk = risk.astype(np.uint8)
1249
-
1250
- near_floor = cv2.dilate(
1251
- floor_mask.astype(np.uint8),
1252
- cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (scaled_odd_kernel_size(
1253
- floor_mask.shape[0],
1254
- floor_mask.shape[1],
1255
- MASK_COMPILER_PROTECTED_DILATION_RATIO,
1256
- minimum=3,
1257
- ),) * 2),
1258
- iterations=2,
1259
- )
1260
- if boundary_mask.any():
1261
- boundary_support = cv2.dilate(boundary_mask.astype(np.uint8), cv2.getStructuringElement(
1262
- cv2.MORPH_ELLIPSE,
1263
- (scaled_odd_kernel_size(
1264
- floor_mask.shape[0],
1265
- floor_mask.shape[1],
1266
- MASK_COMPILER_EDGE_REPAIR_RATIO,
1267
- minimum=3,
1268
- ),) * 2,
1269
- ), iterations=1)
1270
- near_floor = cv2.bitwise_or(near_floor, boundary_support)
1271
-
1272
- semantic_risk = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES | OCCLUDER_CLASSES)).astype(np.uint8)
1273
- semantic_risk = cv2.dilate(
1274
- semantic_risk,
1275
- cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
1276
- iterations=1,
1277
- )
1278
-
1279
- risk &= (near_floor > 0).astype(np.uint8)
1280
- risk = cv2.bitwise_or(risk, semantic_risk)
1281
- return (risk > 0).astype(np.uint8)
1282
-
1283
-
1284
- def build_completed_floor_plane_mask(
1285
- floor_mask: np.ndarray,
1286
- seg_map: np.ndarray,
1287
- quad: np.ndarray | None,
1288
- depth: np.ndarray | None,
1289
- geometry: dict | None,
1290
- plane: dict | None,
1291
- boundary_mask: np.ndarray,
1292
- protected_mask: np.ndarray,
1293
- ) -> tuple[np.ndarray, dict]:
1294
- h, w = floor_mask.shape[:2]
1295
- kernel_size = max(5, min(h, w) // 160) | 1
1296
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
1297
- completed = floor_mask.astype(np.uint8).copy()
1298
-
1299
- edge_support = boundary_mask.astype(np.uint8)
1300
- if edge_support.any():
1301
- edge_support = cv2.dilate(edge_support, kernel, iterations=2)
1302
- completed = cv2.bitwise_or(completed, edge_support)
1303
-
1304
- if quad is not None and completed.any():
1305
- plane_mask = np.zeros((h, w), dtype=np.uint8)
1306
- cv2.fillConvexPoly(plane_mask, np.round(quad).astype(np.int32), 1)
1307
- plane_mask[protected_mask > 0] = 0
1308
- near_floor = cv2.dilate(completed, kernel, iterations=6)
1309
- completed = cv2.bitwise_or(completed, cv2.bitwise_and(plane_mask, near_floor))
1310
-
1311
- if depth is not None and floor_mask.any():
1312
- floor_depth = depth[(floor_mask > 0) & np.isfinite(depth)]
1313
- if floor_depth.size > 0:
1314
- lo, hi = float(np.percentile(floor_depth, 2)), float(np.percentile(floor_depth, 98))
1315
- margin = max(0.08, (hi - lo) * 0.35)
1316
- depth_keep = (depth >= lo - margin) & (depth <= hi + margin)
1317
- completed = (completed & depth_keep.astype(np.uint8)).astype(np.uint8)
1318
- completed[floor_mask > 0] = np.maximum(completed[floor_mask > 0], 1)
1319
-
1320
- completed[protected_mask > 0] = 0
1321
- completed, geometry_filter_metadata = filter_surface_by_floor_geometry(completed, geometry, plane)
1322
- completed[protected_mask > 0] = 0
1323
- completed = clean_floor_mask(completed)
1324
- completed[protected_mask > 0] = 0
1325
-
1326
- return completed, geometry_filter_metadata
1327
-
1328
-
1329
- def compile_floor_render_mask(
1330
- image_np: np.ndarray,
1331
- seg_map: np.ndarray,
1332
- floor_mask: np.ndarray,
1333
- quad: np.ndarray | None,
1334
- depth: np.ndarray | None,
1335
- geometry: dict | None,
1336
- plane: dict | None,
1337
- ) -> tuple[np.ndarray, dict]:
1338
- if not ENABLE_MASK_COMPILER:
1339
- fallback = clean_floor_mask(floor_mask)
1340
- semantic_protected = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES | OCCLUDER_CLASSES)).astype(np.uint8)
1341
- fallback[semantic_protected > 0] = 0
1342
- fallback_pixels = int(fallback.sum())
1343
- fallback_metadata = {
1344
- "maskCompilerEnabled": False,
1345
- "maskCompilerVersion": MASK_COMPILER_VERSION,
1346
- "maskCompilerFallbackReason": "disabled",
1347
- "semanticFloorPixels": int(floor_mask.sum()),
1348
- "edgeBoundaryPixels": 0,
1349
- "foregroundRiskPixels": 0,
1350
- "protectedObjectPixels": int(semantic_protected.sum()),
1351
- "surfacePixelsBeforeEdge": fallback_pixels,
1352
- "protectedPixels": int(semantic_protected.sum()),
1353
- "completedFloorPlanePixels": fallback_pixels,
1354
- "finalFloorRenderPixels": fallback_pixels,
1355
- "renderMaskPixels": fallback_pixels,
1356
- }
1357
- return fallback, fallback_metadata
1358
-
1359
- boundary_mask = build_floor_boundary_mask(image_np, floor_mask)
1360
- foreground_risk_mask = build_foreground_risk_mask(image_np, floor_mask, seg_map, boundary_mask)
1361
- semantic_protected = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES | OCCLUDER_CLASSES)).astype(np.uint8)
1362
- semantic_protected = cv2.dilate(
1363
- semantic_protected,
1364
- cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (max(5, min(floor_mask.shape[:2]) // 80) | 1,) * 2),
1365
- iterations=2,
1366
- )
1367
- protected_mask = cv2.bitwise_or(semantic_protected, foreground_risk_mask)
1368
-
1369
- completed_plane_mask, geometry_filter_metadata = build_completed_floor_plane_mask(
1370
- floor_mask,
1371
- seg_map,
1372
- quad,
1373
- depth,
1374
- geometry,
1375
- plane,
1376
- boundary_mask,
1377
- protected_mask,
1378
- )
1379
-
1380
- final_mask = completed_plane_mask.copy()
1381
- final_mask[protected_mask > 0] = 0
1382
- surface_before_edge = int(final_mask.sum())
1383
- final_mask, edge_metadata = improve_surface_edge_coverage(final_mask, protected_mask > 0)
1384
- final_mask[protected_mask > 0] = 0
1385
- final_mask, post_edge_geometry_metadata = filter_surface_by_floor_geometry(final_mask, geometry, plane)
1386
- final_mask[protected_mask > 0] = 0
1387
- final_mask = clean_floor_mask(final_mask)
1388
- final_mask[protected_mask > 0] = 0
1389
-
1390
- semantic_floor_pixels = int(floor_mask.sum())
1391
- completed_pixels = int(completed_plane_mask.sum())
1392
- final_pixels = int(final_mask.sum())
1393
- fallback_reason = "compiled-floor-plane"
1394
- if final_pixels < SURFACE_MIN_PLANE_PIXELS or final_pixels < max(1, int(semantic_floor_pixels * MASK_COMPILER_MIN_KEEP_RATIO)):
1395
- fallback_candidate = clean_floor_mask(floor_mask)
1396
- fallback_candidate[protected_mask > 0] = 0
1397
- fallback_candidate = (fallback_candidate > 0).astype(np.uint8)
1398
- if int(fallback_candidate.sum()) >= max(1, int(semantic_floor_pixels * MASK_COMPILER_MIN_KEEP_RATIO)):
1399
- final_mask = fallback_candidate
1400
- final_pixels = int(final_mask.sum())
1401
- fallback_reason = "fallback-to-cleaned-semantic-floor"
1402
- else:
1403
- fallback_reason = "compiled-floor-plane-too-small"
1404
- final_mask = fallback_candidate
1405
- final_pixels = int(final_mask.sum())
1406
-
1407
- metadata = {
1408
- "maskCompilerEnabled": True,
1409
- "maskCompilerVersion": MASK_COMPILER_VERSION,
1410
- "maskCompilerFallbackReason": fallback_reason,
1411
- "semanticFloorPixels": semantic_floor_pixels,
1412
- "edgeBoundaryPixels": int(boundary_mask.sum()),
1413
- "foregroundRiskPixels": int(foreground_risk_mask.sum()),
1414
- "protectedObjectPixels": int(protected_mask.sum()),
1415
- "surfacePixelsBeforeEdge": surface_before_edge,
1416
- "protectedPixels": int(protected_mask.sum()),
1417
- "completedFloorPlanePixels": completed_pixels,
1418
- "finalFloorRenderPixels": final_pixels,
1419
- **geometry_filter_metadata,
1420
- **edge_metadata,
1421
- **{f"postEdge{k[0].upper()}{k[1:]}": value for k, value in post_edge_geometry_metadata.items()},
1422
- "renderMaskPixels": final_pixels,
1423
- }
1424
- return final_mask, metadata
1425
 
1426
 
1427
  def improve_surface_edge_coverage(
@@ -2579,25 +2277,82 @@ def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray, geometry: dict |
2579
  return homography, plane
2580
 
2581
 
2582
- def build_floor_surface_mask(
2583
- image_np: np.ndarray,
2584
- floor_mask: np.ndarray,
2585
- seg_map: np.ndarray,
2586
- quad: np.ndarray | None,
2587
- depth: np.ndarray | None,
2588
- geometry: dict | None,
2589
- plane: dict | None,
2590
- ):
2591
- render_mask, compiler_metadata = compile_floor_render_mask(
2592
- image_np=image_np,
2593
- seg_map=seg_map,
2594
- floor_mask=floor_mask,
2595
- quad=quad,
2596
- depth=depth,
2597
- geometry=geometry,
2598
- plane=plane,
2599
- )
2600
- return render_mask, compiler_metadata
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2601
 
2602
 
2603
  def run_segmentation(img: Image.Image, img_np: np.ndarray):
@@ -2936,10 +2691,10 @@ def build_segmentation_bundle(contents: bytes):
2936
  homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
2937
  print(f"[TIMING] Plane fitting / homography calculation took {time.perf_counter() - t0:.3f} seconds", flush=True)
2938
 
2939
- t0 = time.perf_counter()
2940
- quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
2941
- surface_mask, edge_metadata = build_floor_surface_mask(img_np, floor_mask, seg_map, quad, depth, geometry, plane)
2942
- surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
2943
  print(f"[TIMING] Surface masking took {time.perf_counter() - t0:.3f} seconds", flush=True)
2944
 
2945
  t0 = time.perf_counter()
 
318
  "plane_distance_threshold_meters",
319
  "0.12",
320
  ))
321
+ SURFACE_PLANE_NORMAL_MIN_COS = float(config_value(
322
+ "SURFACE_PLANE_NORMAL_MIN_COS",
323
+ "surface_mapping",
324
+ "plane_normal_min_cos",
325
+ "0.45",
326
+ ))
327
+ SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
328
+ "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO",
329
+ "surface_mapping",
330
+ "plane_filter_min_keep_ratio",
331
+ "0.45",
332
+ ))
333
+
334
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
335
+ seg_processor = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  seg_model = None
337
  segmentation_backend = "segformer"
338
  oneformer_polygon_processor = None
 
1109
  return result
1110
 
1111
 
1112
+ def scaled_odd_kernel_size(
1113
+ height: int,
1114
+ width: int,
1115
+ ratio: float,
1116
+ minimum: int = 3,
1117
+ maximum: int = 31,
1118
+ ) -> int:
1119
+ min_side = max(3, min(height, width))
1120
+ size = max(minimum, int(round(min_side * ratio)))
1121
+ size = min(maximum, size)
1122
+ return size | 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1123
 
1124
 
1125
  def improve_surface_edge_coverage(
 
2277
  return homography, plane
2278
 
2279
 
2280
+ def build_floor_surface_mask(
2281
+ floor_mask: np.ndarray,
2282
+ seg_map: np.ndarray,
2283
+ quad: np.ndarray | None,
2284
+ depth: np.ndarray | None,
2285
+ geometry: dict | None,
2286
+ plane: dict | None,
2287
+ ):
2288
+ h, w = floor_mask.shape[:2]
2289
+ kern_size = max(5, min(h, w) // 160) | 1
2290
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size))
2291
+ occluder_mask = np.isin(seg_map, class_ids(OCCLUDER_CLASSES)).astype(np.uint8)
2292
+ occ_dilated = cv2.dilate(occluder_mask, kern, iterations=2)
2293
+ reject_mask = np.isin(seg_map, class_ids(REJECT_SURFACE_CLASSES)).astype(np.uint8)
2294
+ reject_dilated = cv2.dilate(reject_mask, kern, iterations=2)
2295
+
2296
+ surface = floor_mask.copy()
2297
+ surface[reject_dilated > 0] = 0
2298
+ if not surface.any():
2299
+ surface = floor_mask.copy()
2300
+
2301
+ contours, _ = cv2.findContours(surface, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
2302
+ if contours:
2303
+ filled = np.zeros((h, w), dtype=np.uint8)
2304
+ cv2.drawContours(filled, contours, -1, 1, cv2.FILLED)
2305
+ filled[reject_dilated > 0] = 0
2306
+ surface = filled
2307
+
2308
+ if quad is not None and surface.any():
2309
+ plane_mask = np.zeros((h, w), dtype=np.uint8)
2310
+ cv2.fillConvexPoly(plane_mask, np.round(quad).astype(np.int32), 1)
2311
+ plane_mask[reject_dilated > 0] = 0
2312
+ near_floor = cv2.dilate(surface, kern, iterations=6)
2313
+ surface = cv2.bitwise_or(surface, cv2.bitwise_and(plane_mask, near_floor))
2314
+
2315
+ surface[occ_dilated > 0] = 0
2316
+ if depth is not None and floor_mask.any():
2317
+ floor_depth = depth[(floor_mask > 0) & np.isfinite(depth)]
2318
+ if floor_depth.size == 0:
2319
+ floor_depth = None
2320
+ else:
2321
+ floor_depth = None
2322
+ if floor_depth is not None:
2323
+ lo, hi = float(np.percentile(floor_depth, 2)), float(np.percentile(floor_depth, 98))
2324
+ margin = max(0.08, (hi - lo) * 0.35)
2325
+ depth_keep = (depth >= lo - margin) & (depth <= hi + margin)
2326
+ surface = (surface & depth_keep.astype(np.uint8)).astype(np.uint8)
2327
+ surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1)
2328
+ surface[occ_dilated > 0] = 0
2329
+ surface[reject_dilated > 0] = 0
2330
+
2331
+ surface, geometry_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2332
+ surface[occ_dilated > 0] = 0
2333
+ surface[reject_dilated > 0] = 0
2334
+
2335
+ surface = clean_floor_mask(surface)
2336
+ surface[occ_dilated > 0] = 0
2337
+ surface[reject_dilated > 0] = 0
2338
+
2339
+ protected_mask = (occ_dilated > 0) | (reject_dilated > 0)
2340
+ surface_before_edge = int(surface.sum())
2341
+ surface, edge_metadata = improve_surface_edge_coverage(surface, protected_mask)
2342
+ surface, post_edge_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
2343
+ surface[occ_dilated > 0] = 0
2344
+ surface[reject_dilated > 0] = 0
2345
+ post_edge_filter_metadata = {
2346
+ f"postEdge{k[0].upper()}{k[1:]}": value
2347
+ for k, value in post_edge_filter_metadata.items()
2348
+ }
2349
+ mask_metadata = {
2350
+ "visibleFloorPixels": int(floor_mask.sum()),
2351
+ "surfacePixelsBeforeEdge": surface_before_edge,
2352
+ "protectedPixels": int(protected_mask.sum()),
2353
+ "renderMaskPixels": int(surface.sum()),
2354
+ }
2355
+ return surface, {**geometry_filter_metadata, **edge_metadata, **post_edge_filter_metadata, **mask_metadata}
2356
 
2357
 
2358
  def run_segmentation(img: Image.Image, img_np: np.ndarray):
 
2691
  homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
2692
  print(f"[TIMING] Plane fitting / homography calculation took {time.perf_counter() - t0:.3f} seconds", flush=True)
2693
 
2694
+ t0 = time.perf_counter()
2695
+ quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
2696
+ surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
2697
+ surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
2698
  print(f"[TIMING] Surface masking took {time.perf_counter() - t0:.3f} seconds", flush=True)
2699
 
2700
  t0 = time.perf_counter()
test_floor_geometry.py CHANGED
@@ -156,121 +156,9 @@ class MetricFloorGeometryTests(unittest.TestCase):
156
  self.assertFalse(repaired[protected].any())
157
  self.assertEqual(int(repaired[42, 99]), 0)
158
 
159
- def test_mask_compiler_protects_foreground_objects(self):
160
- height, width = 120, 160
161
- image = np.full((height, width, 3), 180, dtype=np.uint8)
162
- image[78:108, 40:120] = np.array([165, 150, 135], dtype=np.uint8)
163
- image[88:102, 65:95] = np.array([40, 40, 40], dtype=np.uint8)
164
-
165
- floor_mask = np.zeros((height, width), dtype=np.uint8)
166
- floor_mask[72:116, 24:136] = 1
167
-
168
- seg_map = np.full((height, width), app.class_ids({"floor"})[0], dtype=np.uint8)
169
- seg_map[88:102, 65:95] = app.class_ids({"chair"})[0]
170
-
171
- surface, metadata = app.build_floor_surface_mask(
172
- image,
173
- floor_mask,
174
- seg_map,
175
- quad=None,
176
- depth=None,
177
- geometry=None,
178
- plane=None,
179
- )
180
-
181
- self.assertTrue(metadata["maskCompilerEnabled"])
182
- self.assertGreater(metadata["protectedObjectPixels"], 0)
183
- self.assertEqual(metadata["maskCompilerFallbackReason"], "compiled-floor-plane")
184
- self.assertEqual(int(surface[88:102, 65:95].sum()), 0)
185
- self.assertGreater(int(surface.sum()), int(floor_mask.sum()) // 2)
186
-
187
- def test_mask_compiler_completes_floor_plane_without_readding_protected_pixels(self):
188
- height, width = 120, 160
189
- yy, xx = np.mgrid[0:height, 0:width]
190
- image = np.full((height, width, 3), 170, dtype=np.uint8)
191
- image[76:112, 52:124] = np.array([155, 147, 132], dtype=np.uint8)
192
- image[86:100, 74:96] = np.array([30, 30, 30], dtype=np.uint8)
193
-
194
- floor_mask = np.zeros((height, width), dtype=np.uint8)
195
- floor_mask[82:112, 58:118] = 1
196
-
197
- seg_map = np.full((height, width), app.class_ids({"floor"})[0], dtype=np.uint8)
198
- seg_map[86:100, 74:96] = app.class_ids({"table"})[0]
199
-
200
- points = np.zeros((height, width, 3), dtype=np.float32)
201
- points[:, :, 0] = (xx - width / 2) / 60.0
202
- points[:, :, 1] = 0.0
203
- points[:, :, 2] = (yy - 82) / 60.0 + 1.0
204
- normals = np.zeros_like(points)
205
- normals[:, :, 1] = 1.0
206
- geometry = {
207
- "provider": "synthetic",
208
- "points": points,
209
- "normals": normals,
210
- "validMask": np.ones((height, width), dtype=bool),
211
- "intrinsics": np.eye(3, dtype=np.float32),
212
- }
213
- plane = {
214
- "planeNormal": [0.0, 1.0, 0.0],
215
- "planeOrigin": [0.0, 0.0, 0.0],
216
- }
217
- quad = np.array([[50, 78], [126, 78], [136, 116], [44, 116]], dtype=np.float32)
218
-
219
- original_filter = app.ENABLE_GEOMETRY_SURFACE_FILTER
220
- original_min = app.SURFACE_MIN_PLANE_PIXELS
221
- try:
222
- app.ENABLE_GEOMETRY_SURFACE_FILTER = True
223
- app.SURFACE_MIN_PLANE_PIXELS = 200
224
- surface, metadata = app.build_floor_surface_mask(
225
- image,
226
- floor_mask,
227
- seg_map,
228
- quad=quad,
229
- depth=None,
230
- geometry=geometry,
231
- plane=plane,
232
- )
233
- finally:
234
- app.ENABLE_GEOMETRY_SURFACE_FILTER = original_filter
235
- app.SURFACE_MIN_PLANE_PIXELS = original_min
236
-
237
- self.assertGreater(metadata["completedFloorPlanePixels"], int(floor_mask.sum()))
238
- self.assertTrue(metadata["maskCompilerEnabled"])
239
- self.assertEqual(metadata["maskCompilerFallbackReason"], "compiled-floor-plane")
240
- self.assertEqual(int(surface[86:100, 74:96].sum()), 0)
241
- self.assertGreater(int(surface.sum()), int(floor_mask.sum()))
242
-
243
- def test_mask_compiler_flags_color_detail_risk_on_floor_patch(self):
244
- height, width = 140, 180
245
- image = np.full((height, width, 3), 176, dtype=np.uint8)
246
- patch = np.indices((24, 24)).sum(axis=0) % 2
247
- checker = np.where(patch[..., None] == 0, np.array([26, 26, 26], dtype=np.uint8), np.array([246, 246, 246], dtype=np.uint8))
248
- image[86:110, 68:92] = checker
249
-
250
- floor_mask = np.zeros((height, width), dtype=np.uint8)
251
- floor_mask[72:, :] = 1
252
- seg_map = np.full((height, width), app.class_ids({"floor"})[0], dtype=np.uint8)
253
-
254
- boundary_mask = app.build_floor_boundary_mask(image, floor_mask)
255
- risk_mask = app.build_foreground_risk_mask(image, floor_mask, seg_map, boundary_mask)
256
- surface, metadata = app.build_floor_surface_mask(
257
- image,
258
- floor_mask,
259
- seg_map,
260
- quad=None,
261
- depth=None,
262
- geometry=None,
263
- plane=None,
264
- )
265
-
266
- self.assertGreater(int(risk_mask.sum()), 0)
267
- self.assertGreater(metadata["foregroundRiskPixels"], 0)
268
- self.assertLess(int(surface[86:110, 68:92].sum()), 24 * 24)
269
-
270
  def test_floor_surface_mask_does_not_readd_off_plane_edge_pixels(self):
271
  height, width = 80, 120
272
  yy, xx = np.mgrid[0:height, 0:width]
273
- image = np.full((height, width, 3), 180, dtype=np.uint8)
274
  floor_mask = np.zeros((height, width), dtype=np.uint8)
275
  floor_mask[45:74, 22:98] = 1
276
  seg_map = np.full((height, width), app.class_ids({"floor"})[0], dtype=np.uint8)
@@ -297,19 +185,18 @@ class MetricFloorGeometryTests(unittest.TestCase):
297
  original_filter = app.ENABLE_GEOMETRY_SURFACE_FILTER
298
  original_min = app.SURFACE_MIN_PLANE_PIXELS
299
  original_distance = app.SURFACE_PLANE_DISTANCE_METERS
300
- try:
301
  app.ENABLE_GEOMETRY_SURFACE_FILTER = True
302
  app.SURFACE_MIN_PLANE_PIXELS = 250
303
  app.SURFACE_PLANE_DISTANCE_METERS = 0.12
304
  surface, metadata = app.build_floor_surface_mask(
305
- image,
306
  floor_mask,
307
  seg_map,
308
  quad=None,
309
  depth=None,
310
  geometry=geometry,
311
- plane=plane,
312
- )
313
  finally:
314
  app.ENABLE_GEOMETRY_SURFACE_FILTER = original_filter
315
  app.SURFACE_MIN_PLANE_PIXELS = original_min
 
156
  self.assertFalse(repaired[protected].any())
157
  self.assertEqual(int(repaired[42, 99]), 0)
158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  def test_floor_surface_mask_does_not_readd_off_plane_edge_pixels(self):
160
  height, width = 80, 120
161
  yy, xx = np.mgrid[0:height, 0:width]
 
162
  floor_mask = np.zeros((height, width), dtype=np.uint8)
163
  floor_mask[45:74, 22:98] = 1
164
  seg_map = np.full((height, width), app.class_ids({"floor"})[0], dtype=np.uint8)
 
185
  original_filter = app.ENABLE_GEOMETRY_SURFACE_FILTER
186
  original_min = app.SURFACE_MIN_PLANE_PIXELS
187
  original_distance = app.SURFACE_PLANE_DISTANCE_METERS
188
+ try:
189
  app.ENABLE_GEOMETRY_SURFACE_FILTER = True
190
  app.SURFACE_MIN_PLANE_PIXELS = 250
191
  app.SURFACE_PLANE_DISTANCE_METERS = 0.12
192
  surface, metadata = app.build_floor_surface_mask(
 
193
  floor_mask,
194
  seg_map,
195
  quad=None,
196
  depth=None,
197
  geometry=geometry,
198
+ plane=plane,
199
+ )
200
  finally:
201
  app.ENABLE_GEOMETRY_SURFACE_FILTER = original_filter
202
  app.SURFACE_MIN_PLANE_PIXELS = original_min