Codex staging deploy commited on
Commit
74d091d
·
1 Parent(s): 189a33b

Fix carpet lighting transfer (GitHub 91452ed)

Browse files
Files changed (2) hide show
  1. app.py +110 -26
  2. test_floor_geometry.py +28 -0
app.py CHANGED
@@ -1022,6 +1022,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,11 +1419,12 @@ 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
- ) -> np.ndarray | None:
 
1426
  if not surface_mask.any():
1427
  return None
1428
 
@@ -1457,22 +1459,66 @@ 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[mask == 0] = 0.0
 
 
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 build_luminance_lighting_maps(
1473
- img_np: np.ndarray,
1474
- surface_mask: np.ndarray,
1475
- ) -> dict[str, np.ndarray | None] | None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1476
  if not surface_mask.any():
1477
  return None
1478
 
@@ -1491,13 +1537,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": build_showroom_shade_map_from_luminance(luminance, mask, median_lum),
1500
- "reflectionMap": build_reflection_map(img_np, surface_mask, None),
 
 
 
 
 
1501
  }
1502
 
1503
 
@@ -1706,9 +1762,10 @@ def preserve_observed_lighting(
1706
 
1707
 
1708
  def build_intrinsic_lighting_maps(
1709
- img_np: np.ndarray,
1710
- surface_mask: np.ndarray,
1711
- ) -> dict[str, np.ndarray | None] | None:
 
1712
  if not surface_mask.any() or intrinsic_models is None:
1713
  return None
1714
 
@@ -1728,7 +1785,11 @@ def build_intrinsic_lighting_maps(
1728
  if smoothed is None:
1729
  return None
1730
 
1731
- luminance_maps = build_luminance_lighting_maps(img_np, surface_mask)
 
 
 
 
1732
  if luminance_maps and luminance_maps.get("shadeMap") is not None:
1733
  observed = decode_relative_map(
1734
  luminance_maps["shadeMap"],
@@ -1737,12 +1798,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(img_np, surface_mask, smoothed),
 
 
 
 
 
1746
  }
1747
  except Exception as exc:
1748
  print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
@@ -3779,6 +3850,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3779
  t0 = time.perf_counter()
3780
  quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
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)
@@ -3866,12 +3941,20 @@ 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(img_np, surface_mask)
 
 
 
 
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(img_np, surface_mask)
 
 
 
 
3875
  if lighting_maps and lighting_maps.get("shadeMap") is not None:
3876
  lighting_source = "luminance"
3877
  if lighting_maps:
@@ -4007,6 +4090,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,
 
1022
  self._write_manifest()
1023
 
1024
  PRIMARY_FLOOR_CLASSES = {"floor", "rug", "carpet", "mat"}
1025
+ REPLACEABLE_SOFT_FLOOR_CLASSES = {"rug", "carpet", "mat"}
1026
  FLOOR_SURFACE_CLASSES = {
1027
  "floor", "road", "sidewalk", "ground", "field", "grass", "sand",
1028
  "runway", "dirt track", "land", "stairs", "step", "rug", "carpet", "mat",
 
1419
  return build_showroom_shade_map_from_relative(relative, surface_mask)
1420
 
1421
 
1422
+ def build_reflection_map(
1423
+ img_np: np.ndarray,
1424
+ surface_mask: np.ndarray,
1425
+ relative_shading: np.ndarray | None = None,
1426
+ replaced_material_mask: np.ndarray | None = None,
1427
+ ) -> np.ndarray | None:
1428
  if not surface_mask.any():
1429
  return None
1430
 
 
1459
  # A reflection is additive light. Dark source-floor detail belongs to the
1460
  # illumination map; transferring it here would turn old material color or
1461
  # texture into an artificial dark reflection on the replacement material.
1462
+ reflection = np.maximum.reduce(reflection_candidates).astype(np.float32)
1463
  if min(h, w) > 120:
1464
  sigma = max(0.6, min(h, w) / 520.0)
1465
  reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma)
1466
+ reflection = np.clip(reflection, REFLECTION_MAP_MIN, REFLECTION_MAP_MAX)
1467
+ if replaced_material_mask is not None and replaced_material_mask.shape[:2] == (h, w):
1468
+ reflection[replaced_material_mask > 0] = 0.0
1469
+ reflection[mask == 0] = 0.0
1470
  if float(np.max(np.abs(reflection[mask > 0]))) < 0.025:
1471
  return None
1472
  encoded = (reflection - REFLECTION_MAP_MIN) / (REFLECTION_MAP_MAX - REFLECTION_MAP_MIN)
1473
+ return np.round(encoded * 255.0).clip(0, 255).astype(np.uint8)
1474
+
1475
+
1476
+ def suppress_replaced_material_lighting(
1477
+ relative: np.ndarray,
1478
+ surface_mask: np.ndarray,
1479
+ replaced_material_mask: np.ndarray | None,
1480
+ ) -> np.ndarray:
1481
+ """Replace rug/carpet appearance with lighting extrapolated from nearby hard floor."""
1482
+ if replaced_material_mask is None or replaced_material_mask.shape != surface_mask.shape:
1483
+ return relative
1484
+
1485
+ replacement = (replaced_material_mask > 0) & (surface_mask > 0)
1486
+ if not replacement.any():
1487
+ return relative
1488
+
1489
+ known_surface = (surface_mask > 0) & (~replacement)
1490
+ known_values = relative[known_surface]
1491
+ known_values = known_values[np.isfinite(known_values) & (known_values > 1e-6)]
1492
+ output = relative.astype(np.float32).copy()
1493
+ if known_values.size < 64:
1494
+ output[replacement] = 1.0
1495
+ output[surface_mask == 0] = 1.0
1496
+ return output
1497
+
1498
+ median = float(np.median(known_values))
1499
+ source = output.copy()
1500
+ source[~np.isfinite(source)] = median
1501
+ source[surface_mask == 0] = median
1502
+ radius = max(3.0, min(surface_mask.shape[:2]) / 120.0)
1503
+ extrapolated = cv2.inpaint(
1504
+ source.astype(np.float32),
1505
+ replacement.astype(np.uint8),
1506
+ radius,
1507
+ cv2.INPAINT_TELEA,
1508
+ )
1509
+ sigma = max(8.0, min(surface_mask.shape[:2]) / 48.0)
1510
+ extrapolated = masked_gaussian_blur(extrapolated, surface_mask, sigma)
1511
+ output[replacement] = extrapolated[replacement]
1512
+ output = np.clip(output, SHADE_MAP_MIN, 1.65)
1513
+ output[surface_mask == 0] = 1.0
1514
+ return output
1515
+
1516
+
1517
+ def build_luminance_lighting_maps(
1518
+ img_np: np.ndarray,
1519
+ surface_mask: np.ndarray,
1520
+ replaced_material_mask: np.ndarray | None = None,
1521
+ ) -> dict[str, np.ndarray | None] | None:
1522
  if not surface_mask.any():
1523
  return None
1524
 
 
1537
 
1538
  relative = filled / median_lum
1539
  relative[~np.isfinite(relative)] = 1.0
1540
+ relative = suppress_replaced_material_lighting(
1541
+ relative,
1542
+ mask,
1543
+ replaced_material_mask,
1544
+ )
1545
  shade = smooth_relative_lighting(relative, mask)
1546
  if shade is None:
1547
  return None
1548
+ return {
1549
+ "shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX),
1550
+ "showroomShadeMap": build_showroom_shade_map_from_relative(shade, mask),
1551
+ "reflectionMap": build_reflection_map(
1552
+ img_np,
1553
+ surface_mask,
1554
+ None,
1555
+ replaced_material_mask,
1556
+ ),
1557
  }
1558
 
1559
 
 
1762
 
1763
 
1764
  def build_intrinsic_lighting_maps(
1765
+ img_np: np.ndarray,
1766
+ surface_mask: np.ndarray,
1767
+ replaced_material_mask: np.ndarray | None = None,
1768
+ ) -> dict[str, np.ndarray | None] | None:
1769
  if not surface_mask.any() or intrinsic_models is None:
1770
  return None
1771
 
 
1785
  if smoothed is None:
1786
  return None
1787
 
1788
+ luminance_maps = build_luminance_lighting_maps(
1789
+ img_np,
1790
+ surface_mask,
1791
+ replaced_material_mask,
1792
+ )
1793
  if luminance_maps and luminance_maps.get("shadeMap") is not None:
1794
  observed = decode_relative_map(
1795
  luminance_maps["shadeMap"],
 
1798
  )
1799
  smoothed = preserve_observed_lighting(smoothed, observed, surface_mask)
1800
  alignment = f"{alignment}+observed-lighting"
1801
+ smoothed = suppress_replaced_material_lighting(
1802
+ smoothed,
1803
+ surface_mask,
1804
+ replaced_material_mask,
1805
+ )
1806
  print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True)
1807
 
1808
  return {
1809
  "shadeMap": encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX),
1810
  "showroomShadeMap": build_showroom_shade_map_from_relative(smoothed, surface_mask),
1811
+ "reflectionMap": build_reflection_map(
1812
+ img_np,
1813
+ surface_mask,
1814
+ smoothed,
1815
+ replaced_material_mask,
1816
+ ),
1817
  }
1818
  except Exception as exc:
1819
  print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
 
3850
  t0 = time.perf_counter()
3851
  quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
3852
  surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
3853
+ replaced_material_mask = (
3854
+ np.isin(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES))
3855
+ & (surface_mask > 0)
3856
+ ).astype(np.uint8)
3857
  surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
3858
  occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
3859
  occlusion_indices = np.flatnonzero(occlusion_mask.ravel()).astype(np.uint32)
 
3941
  if intrinsic_models is None:
3942
  _load_intrinsic_model()
3943
  if intrinsic_models is not None:
3944
+ lighting_maps = build_intrinsic_lighting_maps(
3945
+ img_np,
3946
+ surface_mask,
3947
+ replaced_material_mask,
3948
+ )
3949
  if lighting_maps and lighting_maps.get("shadeMap") is not None:
3950
  lighting_source = f"intrinsic-{INTRINSIC_MODEL_VERSION}"
3951
  intrinsic_lighting_used = True
3952
  if ENABLE_SHADING_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
3953
+ lighting_maps = build_luminance_lighting_maps(
3954
+ img_np,
3955
+ surface_mask,
3956
+ replaced_material_mask,
3957
+ )
3958
  if lighting_maps and lighting_maps.get("shadeMap") is not None:
3959
  lighting_source = "luminance"
3960
  if lighting_maps:
 
4090
  "segmentationModel": models["segmentation"]["name"],
4091
  "floorPixels": int(floor_mask.sum()),
4092
  "surfacePixels": int(surface_mask.sum()),
4093
+ "replacedSoftFloorPixels": int(replaced_material_mask.sum()),
4094
  "occlusionPixels": int(occlusion_mask.sum()),
4095
  "floorDirection": floor_direction,
4096
  **sam_metadata,
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)
 
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)