Upload workspace snapshot
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +44 -0
- experiments/hypotheses/Bridge Floor To Wall Grazing Gap.py +38 -27
- experiments/hypotheses/Bridge Unobserved Floor With Room Scale Close.py +31 -25
- experiments/hypotheses/CV FloorClip 005.py +38 -27
- experiments/hypotheses/CV FloorClip 05.py +38 -27
- experiments/hypotheses/CV Grazing 3.py +38 -27
- experiments/hypotheses/CV Grazing 7.py +38 -27
- experiments/hypotheses/CV LenAxis 075.py +38 -27
- experiments/hypotheses/CV LenAxis 10.py +38 -27
- experiments/hypotheses/CV SOR 125.py +38 -27
- experiments/hypotheses/CV SOR 20.py +38 -27
- experiments/hypotheses/Center Compact Boxes On Point Cloud Median.py +38 -27
- experiments/hypotheses/Center Sigma 15.py +42 -28
- experiments/hypotheses/Center Sigma 25.py +42 -28
- experiments/hypotheses/Clean Box Points At Sixtieth Confidence.py +38 -27
- experiments/hypotheses/Clean Distance Path Keep Raw Size Extent.py +37 -27
- experiments/hypotheses/Clean Distance Path Raw Size Select.py +37 -27
- experiments/hypotheses/Clean Each Observation Before Extent Tight.py +38 -27
- experiments/hypotheses/Clean Each Observation Before Extent.py +38 -27
- experiments/hypotheses/Confidence Weighted Box Frames.py +43 -28
- experiments/hypotheses/Confidence Weighted Percentile Short Axes.py +45 -29
- experiments/hypotheses/Consensus Filter At Two Sigma.py +38 -27
- experiments/hypotheses/Decouple Tight Short Axes Stable Longest 030.py +38 -27
- experiments/hypotheses/Decouple Tight Short Axes Stable Longest 040.py +38 -27
- experiments/hypotheses/Decouple Tight Short Axes Stable Longest 050.py +38 -27
- experiments/hypotheses/Decouple Tight Short Axes Stable Longest 060.py +38 -27
- experiments/hypotheses/Depth Edge Bleed Cut Alone.py +41 -28
- experiments/hypotheses/Depth Edge Bleed Cut With Short Axis Median.py +41 -28
- experiments/hypotheses/Estimate Room Area From Convex Hull Of Coverage.py +34 -26
- experiments/hypotheses/Estimate Room Area From Oriented Bounding Rectangle Of Floor.py +34 -26
- experiments/hypotheses/Extend Box Height To Floor Contact.py +38 -27
- experiments/hypotheses/Extend Compact Floor Coverage To Every Object Footprint.py +31 -25
- experiments/hypotheses/Fill Object Footprint Convex Hulls.py +45 -36
- experiments/hypotheses/Floor Contact Plus Tighter Consistency.py +38 -27
- experiments/hypotheses/Fuller Robust Box By One Ninetynine Per Frame.py +38 -27
- experiments/hypotheses/Increase Compact Room Floor Area by 20 Percent.py +31 -27
- experiments/hypotheses/Keep More Floor Extent By Wider Clip.py +38 -27
- experiments/hypotheses/Keep Smaller Observed Floor Patches.py +38 -27
- experiments/hypotheses/Longest Axis Full Max Post Decouple.py +38 -27
- experiments/hypotheses/Longest Axis View Union Full Post Decouple.py +38 -27
- experiments/hypotheses/Longest Axis View Union Robust Post Decouple.py +41 -28
- experiments/hypotheses/Merge Never-Co-Observed Overlapping Same-Class Tracks.py +27 -24
- experiments/hypotheses/Merge Same-Class Instances With Contained Centers.py +27 -24
- experiments/hypotheses/Orient Compact Boxes By Minimum Area Rectangle.py +31 -25
- experiments/hypotheses/Recover Length Axis From View Union Full.py +38 -27
- experiments/hypotheses/Recover Length Axis From View Union Robust.py +41 -28
- experiments/hypotheses/Recover Length Axis Keep Robust Width Depth.py +38 -27
- experiments/hypotheses/Recover Length Axis To Full Max.py +38 -27
- experiments/hypotheses/Recover Longest Two Axes To Full Extent.py +38 -27
- experiments/hypotheses/Reject Below-Floor Compact Box Observations.py +25 -23
README.md
CHANGED
|
@@ -157,6 +157,36 @@ Important files:
|
|
| 157 |
- `encoder/launch.py`: CPU-parallel batch driver
|
| 158 |
- `encoder/ground_truth.py`: ground-truth compact/explicit code builder
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
### Symbolic Solver
|
| 161 |
|
| 162 |
```bash
|
|
@@ -411,6 +441,8 @@ Files:
|
|
| 411 |
| `README.md` | This documentation |
|
| 412 |
| `setup.sh` | Environment, package, data, model, and validation setup |
|
| 413 |
| `backup.py` | Hugging Face dataset backup utility |
|
|
|
|
|
|
|
| 414 |
| `selective_frame_counts.csv` | Static frame-count/reference data used by selection workflows |
|
| 415 |
| `bundles/spatial-codes.tar.gz` | Packed spatial-code artifact used by setup sync |
|
| 416 |
|
|
@@ -644,6 +676,18 @@ The tests mirror source folders. They are written to run without real data, resu
|
|
| 644 |
- `tests/test_encoder/test_render.py`
|
| 645 |
- `tests/test_encoder/test_run.py`
|
| 646 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 647 |
### `tests/test_harness/`
|
| 648 |
|
| 649 |
- `tests/test_harness/__init__.py`
|
|
|
|
| 157 |
- `encoder/launch.py`: CPU-parallel batch driver
|
| 158 |
- `encoder/ground_truth.py`: ground-truth compact/explicit code builder
|
| 159 |
|
| 160 |
+
### Experiments: Geometry Hypotheses
|
| 161 |
+
|
| 162 |
+
```bash
|
| 163 |
+
# List available hypothesis forks.
|
| 164 |
+
python -m experiments.run --list
|
| 165 |
+
|
| 166 |
+
# Build one hypothesis spatial code from existing caches only.
|
| 167 |
+
python -m experiments.run SCENE --hypothesis "Compute Gravity Before Building Object Instances" --depth metric --tracking tracking --input uniform --frames 64 --format explicit
|
| 168 |
+
|
| 169 |
+
# Batch all scenes with existing combined or native SAM3/DA3 caches.
|
| 170 |
+
python -m experiments.launch --hypothesis "Compute Gravity Before Building Object Instances" --depth metric --tracking tracking --input uniform --frames 64 --format explicit
|
| 171 |
+
|
| 172 |
+
# Evaluate generated experiment spatial codes with the symbolic scorer.
|
| 173 |
+
python -m experiments.evaluate --hypothesis "Compute Gravity Before Building Object Instances" --depth metric --tracking tracking --input uniform --frames 64 --format explicit --quiet --errors
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
Files:
|
| 177 |
+
|
| 178 |
+
- `experiments/__init__.py`: experiments package marker
|
| 179 |
+
- `experiments/README.md`: experiment workflow notes
|
| 180 |
+
- `experiments/EXPERIMENT FINDINGS.md`: single consolidated findings report
|
| 181 |
+
- `experiments/hypotheses.md`: hypothesis index and notes
|
| 182 |
+
- `experiments/config.py`: experiment-local path construction
|
| 183 |
+
- `experiments/adapters.py`: build-call adapter for explicit and compact hypothesis forks
|
| 184 |
+
- `experiments/loader.py`: dynamic loader for human-readable hypothesis filenames
|
| 185 |
+
- `experiments/run.py`: one-scene cache-only hypothesis spatial-code builder
|
| 186 |
+
- `experiments/launch.py`: batch launcher over scenes with existing caches
|
| 187 |
+
- `experiments/evaluate.py`: symbolic evaluation of experiment spatial codes
|
| 188 |
+
- `experiments/hypotheses/*.py`: standalone geometry hypothesis forks; each exposes `build_spatial_code()` and `dump_spatial_code()`
|
| 189 |
+
|
| 190 |
### Symbolic Solver
|
| 191 |
|
| 192 |
```bash
|
|
|
|
| 441 |
| `README.md` | This documentation |
|
| 442 |
| `setup.sh` | Environment, package, data, model, and validation setup |
|
| 443 |
| `backup.py` | Hugging Face dataset backup utility |
|
| 444 |
+
| `.gitattributes` | Git LFS attributes for large/binary artifact patterns |
|
| 445 |
+
| `.gitignore` | Excludes generated caches, notebooks, envs, and result folders |
|
| 446 |
| `selective_frame_counts.csv` | Static frame-count/reference data used by selection workflows |
|
| 447 |
| `bundles/spatial-codes.tar.gz` | Packed spatial-code artifact used by setup sync |
|
| 448 |
|
|
|
|
| 676 |
- `tests/test_encoder/test_render.py`
|
| 677 |
- `tests/test_encoder/test_run.py`
|
| 678 |
|
| 679 |
+
### `tests/test_experiments/`
|
| 680 |
+
|
| 681 |
+
- `tests/test_experiments/__init__.py`
|
| 682 |
+
- `tests/test_experiments/conftest.py`
|
| 683 |
+
- `tests/test_experiments/test_config.py`
|
| 684 |
+
- `tests/test_experiments/test_evaluate.py`
|
| 685 |
+
- `tests/test_experiments/test_experiments.py`
|
| 686 |
+
- `tests/test_experiments/test_hypotheses.py`
|
| 687 |
+
- `tests/test_experiments/test_launch.py`
|
| 688 |
+
- `tests/test_experiments/test_loader.py`
|
| 689 |
+
- `tests/test_experiments/test_run.py`
|
| 690 |
+
|
| 691 |
### `tests/test_harness/`
|
| 692 |
|
| 693 |
- `tests/test_harness/__init__.py`
|
experiments/hypotheses/Bridge Floor To Wall Grazing Gap.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1711 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1712 |
)
|
| 1713 |
full_axis_dimensions = np.array(
|
| 1714 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1715 |
)
|
| 1716 |
box_dimensions = robust_dimensions.copy()
|
| 1717 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1810,13 +1821,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1810 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1811 |
if object_points:
|
| 1812 |
stacked = [
|
| 1813 |
-
np.stack(
|
|
|
|
|
|
|
| 1814 |
for p in object_points
|
| 1815 |
if len(p)
|
| 1816 |
]
|
| 1817 |
if stacked:
|
| 1818 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1819 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1820 |
|
| 1821 |
resolution = 0.1
|
| 1822 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1977,9 +1992,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1977 |
instance["centroid"] - fragment["centroid"]
|
| 1978 |
),
|
| 1979 |
)
|
| 1980 |
-
nearest["first_time"] = min(
|
| 1981 |
-
nearest["first_time"], fragment["first_time"]
|
| 1982 |
-
)
|
| 1983 |
consolidated[class_name] = retained
|
| 1984 |
return consolidated
|
| 1985 |
|
|
@@ -2012,9 +2025,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2012 |
points, up_axis
|
| 2013 |
)
|
| 2014 |
record = dict(item)
|
| 2015 |
-
record.update(
|
| 2016 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2017 |
-
)
|
| 2018 |
measured.append(record)
|
| 2019 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2020 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1719 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1720 |
)
|
| 1721 |
full_axis_dimensions = np.array(
|
| 1722 |
+
[
|
| 1723 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1724 |
+
for axis in range(3)
|
| 1725 |
+
]
|
| 1726 |
)
|
| 1727 |
box_dimensions = robust_dimensions.copy()
|
| 1728 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1821 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1822 |
if object_points:
|
| 1823 |
stacked = [
|
| 1824 |
+
np.stack(
|
| 1825 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1826 |
+
)
|
| 1827 |
for p in object_points
|
| 1828 |
if len(p)
|
| 1829 |
]
|
| 1830 |
if stacked:
|
| 1831 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1832 |
+
footprint_points = footprint_points[
|
| 1833 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1834 |
+
]
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1992 |
instance["centroid"] - fragment["centroid"]
|
| 1993 |
),
|
| 1994 |
)
|
| 1995 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1996 |
consolidated[class_name] = retained
|
| 1997 |
return consolidated
|
| 1998 |
|
|
|
|
| 2025 |
points, up_axis
|
| 2026 |
)
|
| 2027 |
record = dict(item)
|
| 2028 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2029 |
measured.append(record)
|
| 2030 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2031 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Bridge Unobserved Floor With Room Scale Close.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
dimensions = np.asarray(dimensions)
|
| 1656 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1657 |
if len(centers) >= 4:
|
| 1658 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1659 |
median = np.median(features, axis=0)
|
| 1660 |
deviation = np.abs(features - median)
|
| 1661 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1778 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1779 |
if object_points:
|
| 1780 |
stacked = [
|
| 1781 |
-
np.stack(
|
|
|
|
|
|
|
| 1782 |
for p in object_points
|
| 1783 |
if len(p)
|
| 1784 |
]
|
| 1785 |
if stacked:
|
| 1786 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1787 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1788 |
|
| 1789 |
resolution = 0.1
|
| 1790 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1946,9 +1956,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1946 |
instance["centroid"] - fragment["centroid"]
|
| 1947 |
),
|
| 1948 |
)
|
| 1949 |
-
nearest["first_time"] = min(
|
| 1950 |
-
nearest["first_time"], fragment["first_time"]
|
| 1951 |
-
)
|
| 1952 |
consolidated[class_name] = retained
|
| 1953 |
return consolidated
|
| 1954 |
|
|
@@ -1981,9 +1989,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1981 |
points, up_axis
|
| 1982 |
)
|
| 1983 |
record = dict(item)
|
| 1984 |
-
record.update(
|
| 1985 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1986 |
-
)
|
| 1987 |
measured.append(record)
|
| 1988 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1989 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
dimensions = np.asarray(dimensions)
|
| 1660 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1661 |
if len(centers) >= 4:
|
| 1662 |
+
features = np.concatenate(
|
| 1663 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1664 |
+
)
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1784 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1785 |
if object_points:
|
| 1786 |
stacked = [
|
| 1787 |
+
np.stack(
|
| 1788 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1789 |
+
)
|
| 1790 |
for p in object_points
|
| 1791 |
if len(p)
|
| 1792 |
]
|
| 1793 |
if stacked:
|
| 1794 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1795 |
+
footprint_points = footprint_points[
|
| 1796 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1797 |
+
]
|
| 1798 |
|
| 1799 |
resolution = 0.1
|
| 1800 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1956 |
instance["centroid"] - fragment["centroid"]
|
| 1957 |
),
|
| 1958 |
)
|
| 1959 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1960 |
consolidated[class_name] = retained
|
| 1961 |
return consolidated
|
| 1962 |
|
|
|
|
| 1989 |
points, up_axis
|
| 1990 |
)
|
| 1991 |
record = dict(item)
|
| 1992 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 1993 |
measured.append(record)
|
| 1994 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1995 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV FloorClip 005.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV FloorClip 05.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV Grazing 3.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV Grazing 7.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV LenAxis 075.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.75)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV LenAxis 10.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 1.0)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV SOR 125.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/CV SOR 20.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Center Compact Boxes On Point Cloud Median.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 98, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1711 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1712 |
)
|
| 1713 |
full_axis_dimensions = np.array(
|
| 1714 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1715 |
)
|
| 1716 |
box_dimensions = robust_dimensions.copy()
|
| 1717 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1807,13 +1818,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1807 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1808 |
if object_points:
|
| 1809 |
stacked = [
|
| 1810 |
-
np.stack(
|
|
|
|
|
|
|
| 1811 |
for p in object_points
|
| 1812 |
if len(p)
|
| 1813 |
]
|
| 1814 |
if stacked:
|
| 1815 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1816 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1817 |
|
| 1818 |
resolution = 0.1
|
| 1819 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1970,9 +1985,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1970 |
instance["centroid"] - fragment["centroid"]
|
| 1971 |
),
|
| 1972 |
)
|
| 1973 |
-
nearest["first_time"] = min(
|
| 1974 |
-
nearest["first_time"], fragment["first_time"]
|
| 1975 |
-
)
|
| 1976 |
consolidated[class_name] = retained
|
| 1977 |
return consolidated
|
| 1978 |
|
|
@@ -2005,9 +2018,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2005 |
points, up_axis
|
| 2006 |
)
|
| 2007 |
record = dict(item)
|
| 2008 |
-
record.update(
|
| 2009 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2010 |
-
)
|
| 2011 |
measured.append(record)
|
| 2012 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2013 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 98, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1719 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1720 |
)
|
| 1721 |
full_axis_dimensions = np.array(
|
| 1722 |
+
[
|
| 1723 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1724 |
+
for axis in range(3)
|
| 1725 |
+
]
|
| 1726 |
)
|
| 1727 |
box_dimensions = robust_dimensions.copy()
|
| 1728 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1818 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1819 |
if object_points:
|
| 1820 |
stacked = [
|
| 1821 |
+
np.stack(
|
| 1822 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1823 |
+
)
|
| 1824 |
for p in object_points
|
| 1825 |
if len(p)
|
| 1826 |
]
|
| 1827 |
if stacked:
|
| 1828 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1829 |
+
footprint_points = footprint_points[
|
| 1830 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1831 |
+
]
|
| 1832 |
|
| 1833 |
resolution = 0.1
|
| 1834 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1985 |
instance["centroid"] - fragment["centroid"]
|
| 1986 |
),
|
| 1987 |
)
|
| 1988 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1989 |
consolidated[class_name] = retained
|
| 1990 |
return consolidated
|
| 1991 |
|
|
|
|
| 2018 |
points, up_axis
|
| 2019 |
)
|
| 2020 |
record = dict(item)
|
| 2021 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2022 |
measured.append(record)
|
| 2023 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2024 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Center Sigma 15.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1665,7 +1671,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
core_centers, core_dimensions, core_weights = centers, dimensions, weights
|
| 1667 |
if len(centers) >= 4:
|
| 1668 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1669 |
median = np.median(features, axis=0)
|
| 1670 |
deviation = np.abs(features - median)
|
| 1671 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1693,7 +1701,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1693 |
full_dimensions = full_dimensions[consistent]
|
| 1694 |
weights = weights[consistent]
|
| 1695 |
box_center_local = np.array(
|
| 1696 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1697 |
)
|
| 1698 |
# Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents,
|
| 1699 |
# not the 75th. A partial/occluded/foreshortened view of an object can only measure a
|
|
@@ -1738,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1738 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1739 |
)
|
| 1740 |
full_axis_dimensions = np.array(
|
| 1741 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1742 |
)
|
| 1743 |
box_dimensions = tight_dimensions.copy()
|
| 1744 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1837,13 +1851,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1837 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1838 |
if object_points:
|
| 1839 |
stacked = [
|
| 1840 |
-
np.stack(
|
|
|
|
|
|
|
| 1841 |
for p in object_points
|
| 1842 |
if len(p)
|
| 1843 |
]
|
| 1844 |
if stacked:
|
| 1845 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1846 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1847 |
|
| 1848 |
resolution = 0.1
|
| 1849 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2006,9 +2024,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2006 |
instance["centroid"] - fragment["centroid"]
|
| 2007 |
),
|
| 2008 |
)
|
| 2009 |
-
nearest["first_time"] = min(
|
| 2010 |
-
nearest["first_time"], fragment["first_time"]
|
| 2011 |
-
)
|
| 2012 |
consolidated[class_name] = retained
|
| 2013 |
return consolidated
|
| 2014 |
|
|
@@ -2041,9 +2057,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2041 |
points, up_axis
|
| 2042 |
)
|
| 2043 |
record = dict(item)
|
| 2044 |
-
record.update(
|
| 2045 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2046 |
-
)
|
| 2047 |
measured.append(record)
|
| 2048 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2049 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
core_centers, core_dimensions, core_weights = centers, dimensions, weights
|
| 1673 |
if len(centers) >= 4:
|
| 1674 |
+
features = np.concatenate(
|
| 1675 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1676 |
+
)
|
| 1677 |
median = np.median(features, axis=0)
|
| 1678 |
deviation = np.abs(features - median)
|
| 1679 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1701 |
full_dimensions = full_dimensions[consistent]
|
| 1702 |
weights = weights[consistent]
|
| 1703 |
box_center_local = np.array(
|
| 1704 |
+
[
|
| 1705 |
+
_weighted_quantile(core_centers[:, axis], core_weights, 0.5)
|
| 1706 |
+
for axis in range(3)
|
| 1707 |
+
]
|
| 1708 |
)
|
| 1709 |
# Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents,
|
| 1710 |
# not the 75th. A partial/occluded/foreshortened view of an object can only measure a
|
|
|
|
| 1749 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1750 |
)
|
| 1751 |
full_axis_dimensions = np.array(
|
| 1752 |
+
[
|
| 1753 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1754 |
+
for axis in range(3)
|
| 1755 |
+
]
|
| 1756 |
)
|
| 1757 |
box_dimensions = tight_dimensions.copy()
|
| 1758 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1851 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1852 |
if object_points:
|
| 1853 |
stacked = [
|
| 1854 |
+
np.stack(
|
| 1855 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1856 |
+
)
|
| 1857 |
for p in object_points
|
| 1858 |
if len(p)
|
| 1859 |
]
|
| 1860 |
if stacked:
|
| 1861 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1862 |
+
footprint_points = footprint_points[
|
| 1863 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1864 |
+
]
|
| 1865 |
|
| 1866 |
resolution = 0.1
|
| 1867 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2024 |
instance["centroid"] - fragment["centroid"]
|
| 2025 |
),
|
| 2026 |
)
|
| 2027 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2028 |
consolidated[class_name] = retained
|
| 2029 |
return consolidated
|
| 2030 |
|
|
|
|
| 2057 |
points, up_axis
|
| 2058 |
)
|
| 2059 |
record = dict(item)
|
| 2060 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2061 |
measured.append(record)
|
| 2062 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2063 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Center Sigma 25.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1665,7 +1671,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
core_centers, core_dimensions, core_weights = centers, dimensions, weights
|
| 1667 |
if len(centers) >= 4:
|
| 1668 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1669 |
median = np.median(features, axis=0)
|
| 1670 |
deviation = np.abs(features - median)
|
| 1671 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1693,7 +1701,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1693 |
full_dimensions = full_dimensions[consistent]
|
| 1694 |
weights = weights[consistent]
|
| 1695 |
box_center_local = np.array(
|
| 1696 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1697 |
)
|
| 1698 |
# Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents,
|
| 1699 |
# not the 75th. A partial/occluded/foreshortened view of an object can only measure a
|
|
@@ -1738,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1738 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1739 |
)
|
| 1740 |
full_axis_dimensions = np.array(
|
| 1741 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1742 |
)
|
| 1743 |
box_dimensions = tight_dimensions.copy()
|
| 1744 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1837,13 +1851,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1837 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1838 |
if object_points:
|
| 1839 |
stacked = [
|
| 1840 |
-
np.stack(
|
|
|
|
|
|
|
| 1841 |
for p in object_points
|
| 1842 |
if len(p)
|
| 1843 |
]
|
| 1844 |
if stacked:
|
| 1845 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1846 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1847 |
|
| 1848 |
resolution = 0.1
|
| 1849 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2006,9 +2024,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2006 |
instance["centroid"] - fragment["centroid"]
|
| 2007 |
),
|
| 2008 |
)
|
| 2009 |
-
nearest["first_time"] = min(
|
| 2010 |
-
nearest["first_time"], fragment["first_time"]
|
| 2011 |
-
)
|
| 2012 |
consolidated[class_name] = retained
|
| 2013 |
return consolidated
|
| 2014 |
|
|
@@ -2041,9 +2057,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2041 |
points, up_axis
|
| 2042 |
)
|
| 2043 |
record = dict(item)
|
| 2044 |
-
record.update(
|
| 2045 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2046 |
-
)
|
| 2047 |
measured.append(record)
|
| 2048 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2049 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
core_centers, core_dimensions, core_weights = centers, dimensions, weights
|
| 1673 |
if len(centers) >= 4:
|
| 1674 |
+
features = np.concatenate(
|
| 1675 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1676 |
+
)
|
| 1677 |
median = np.median(features, axis=0)
|
| 1678 |
deviation = np.abs(features - median)
|
| 1679 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1701 |
full_dimensions = full_dimensions[consistent]
|
| 1702 |
weights = weights[consistent]
|
| 1703 |
box_center_local = np.array(
|
| 1704 |
+
[
|
| 1705 |
+
_weighted_quantile(core_centers[:, axis], core_weights, 0.5)
|
| 1706 |
+
for axis in range(3)
|
| 1707 |
+
]
|
| 1708 |
)
|
| 1709 |
# Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents,
|
| 1710 |
# not the 75th. A partial/occluded/foreshortened view of an object can only measure a
|
|
|
|
| 1749 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1750 |
)
|
| 1751 |
full_axis_dimensions = np.array(
|
| 1752 |
+
[
|
| 1753 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1754 |
+
for axis in range(3)
|
| 1755 |
+
]
|
| 1756 |
)
|
| 1757 |
box_dimensions = tight_dimensions.copy()
|
| 1758 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1851 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1852 |
if object_points:
|
| 1853 |
stacked = [
|
| 1854 |
+
np.stack(
|
| 1855 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1856 |
+
)
|
| 1857 |
for p in object_points
|
| 1858 |
if len(p)
|
| 1859 |
]
|
| 1860 |
if stacked:
|
| 1861 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1862 |
+
footprint_points = footprint_points[
|
| 1863 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1864 |
+
]
|
| 1865 |
|
| 1866 |
resolution = 0.1
|
| 1867 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2024 |
instance["centroid"] - fragment["centroid"]
|
| 2025 |
),
|
| 2026 |
)
|
| 2027 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2028 |
consolidated[class_name] = retained
|
| 2029 |
return consolidated
|
| 2030 |
|
|
|
|
| 2057 |
points, up_axis
|
| 2058 |
)
|
| 2059 |
record = dict(item)
|
| 2060 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2061 |
measured.append(record)
|
| 2062 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2063 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Clean Box Points At Sixtieth Confidence.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -518,7 +522,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 518 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 519 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 520 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 521 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -574,7 +579,8 @@ def refine_mask(mask, rgb):
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 578 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 579 |
mask = cv2.resize(
|
| 580 |
mask.astype(np.uint8),
|
|
@@ -629,7 +635,8 @@ def backproject_frame(
|
|
| 629 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 630 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 631 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 632 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 633 |
height, width = depth_f.shape
|
| 634 |
empty = (
|
| 635 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1230,7 +1237,8 @@ def dump_spatial_code(code, path):
|
|
| 1230 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1231 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1232 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1233 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1234 |
body = dict(code)
|
| 1235 |
ao = body.pop("appearance order", None)
|
| 1236 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1612,15 +1620,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1612 |
points = _canonical_clean(instance)
|
| 1613 |
if not len(points):
|
| 1614 |
points = instance["pts"]
|
| 1615 |
-
room_points = np.stack(
|
| 1616 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1617 |
-
)
|
| 1618 |
horizontal = room_points[:, :2]
|
| 1619 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1620 |
if len(centered) > 5000:
|
| 1621 |
-
centered = centered[
|
| 1622 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1623 |
-
]
|
| 1624 |
try:
|
| 1625 |
_, _, rotation = np.linalg.svd(
|
| 1626 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
upper = np.percentile(projected, 98, axis=0)
|
| 1656 |
centers.append((lower + upper) / 2)
|
| 1657 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1658 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1659 |
weights.append(len(observation))
|
| 1660 |
if not centers:
|
| 1661 |
projected = room_points @ orientation.T
|
|
@@ -1671,7 +1677,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1671 |
full_dimensions = np.asarray(full_dimensions)
|
| 1672 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1673 |
if len(centers) >= 4:
|
| 1674 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1675 |
median = np.median(features, axis=0)
|
| 1676 |
deviation = np.abs(features - median)
|
| 1677 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1718,7 +1726,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1718 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1719 |
)
|
| 1720 |
full_axis_dimensions = np.array(
|
| 1721 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1722 |
)
|
| 1723 |
box_dimensions = robust_dimensions.copy()
|
| 1724 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1814,13 +1825,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1814 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1815 |
if object_points:
|
| 1816 |
stacked = [
|
| 1817 |
-
np.stack(
|
|
|
|
|
|
|
| 1818 |
for p in object_points
|
| 1819 |
if len(p)
|
| 1820 |
]
|
| 1821 |
if stacked:
|
| 1822 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1823 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1824 |
|
| 1825 |
resolution = 0.1
|
| 1826 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1977,9 +1992,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1977 |
instance["centroid"] - fragment["centroid"]
|
| 1978 |
),
|
| 1979 |
)
|
| 1980 |
-
nearest["first_time"] = min(
|
| 1981 |
-
nearest["first_time"], fragment["first_time"]
|
| 1982 |
-
)
|
| 1983 |
consolidated[class_name] = retained
|
| 1984 |
return consolidated
|
| 1985 |
|
|
@@ -2012,9 +2025,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2012 |
points, up_axis
|
| 2013 |
)
|
| 2014 |
record = dict(item)
|
| 2015 |
-
record.update(
|
| 2016 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2017 |
-
)
|
| 2018 |
measured.append(record)
|
| 2019 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2020 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 522 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 523 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 524 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 525 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 526 |
+
"""
|
| 527 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 528 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 529 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 579 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 580 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 581 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 582 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 583 |
+
"""
|
| 584 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 585 |
mask = cv2.resize(
|
| 586 |
mask.astype(np.uint8),
|
|
|
|
| 635 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 636 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 637 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 638 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 639 |
+
"""
|
| 640 |
height, width = depth_f.shape
|
| 641 |
empty = (
|
| 642 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1237 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1238 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1239 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1240 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1241 |
+
"""
|
| 1242 |
body = dict(code)
|
| 1243 |
ao = body.pop("appearance order", None)
|
| 1244 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1620 |
points = _canonical_clean(instance)
|
| 1621 |
if not len(points):
|
| 1622 |
points = instance["pts"]
|
| 1623 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1624 |
horizontal = room_points[:, :2]
|
| 1625 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1626 |
if len(centered) > 5000:
|
| 1627 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1628 |
try:
|
| 1629 |
_, _, rotation = np.linalg.svd(
|
| 1630 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
upper = np.percentile(projected, 98, axis=0)
|
| 1660 |
centers.append((lower + upper) / 2)
|
| 1661 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1662 |
+
full_dimensions.append(
|
| 1663 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1664 |
+
)
|
| 1665 |
weights.append(len(observation))
|
| 1666 |
if not centers:
|
| 1667 |
projected = room_points @ orientation.T
|
|
|
|
| 1677 |
full_dimensions = np.asarray(full_dimensions)
|
| 1678 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1679 |
if len(centers) >= 4:
|
| 1680 |
+
features = np.concatenate(
|
| 1681 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1682 |
+
)
|
| 1683 |
median = np.median(features, axis=0)
|
| 1684 |
deviation = np.abs(features - median)
|
| 1685 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
+
[
|
| 1730 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1731 |
+
for axis in range(3)
|
| 1732 |
+
]
|
| 1733 |
)
|
| 1734 |
box_dimensions = robust_dimensions.copy()
|
| 1735 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
+
np.stack(
|
| 1829 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1830 |
+
)
|
| 1831 |
for p in object_points
|
| 1832 |
if len(p)
|
| 1833 |
]
|
| 1834 |
if stacked:
|
| 1835 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1836 |
+
footprint_points = footprint_points[
|
| 1837 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1838 |
+
]
|
| 1839 |
|
| 1840 |
resolution = 0.1
|
| 1841 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1992 |
instance["centroid"] - fragment["centroid"]
|
| 1993 |
),
|
| 1994 |
)
|
| 1995 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1996 |
consolidated[class_name] = retained
|
| 1997 |
return consolidated
|
| 1998 |
|
|
|
|
| 2025 |
points, up_axis
|
| 2026 |
)
|
| 2027 |
record = dict(item)
|
| 2028 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2029 |
measured.append(record)
|
| 2030 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2031 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Clean Distance Path Keep Raw Size Extent.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1643,7 +1647,8 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1643 |
# extremes; cleaning only the distance path gives the distance gain without the size cost.
|
| 1644 |
raw_proj = (
|
| 1645 |
np.stack(
|
| 1646 |
-
[observation @ u, observation @ v, observation @ g - floor_level],
|
|
|
|
| 1647 |
)
|
| 1648 |
@ orientation.T
|
| 1649 |
)
|
|
@@ -1680,7 +1685,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1680 |
full_dimensions = np.asarray(full_dimensions)
|
| 1681 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1682 |
if len(centers) >= 4:
|
| 1683 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1684 |
median = np.median(features, axis=0)
|
| 1685 |
deviation = np.abs(features - median)
|
| 1686 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1742,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1742 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1743 |
)
|
| 1744 |
full_axis_dimensions = np.array(
|
| 1745 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1746 |
)
|
| 1747 |
box_dimensions = tight_dimensions.copy()
|
| 1748 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1841,13 +1851,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1841 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1842 |
if object_points:
|
| 1843 |
stacked = [
|
| 1844 |
-
np.stack(
|
|
|
|
|
|
|
| 1845 |
for p in object_points
|
| 1846 |
if len(p)
|
| 1847 |
]
|
| 1848 |
if stacked:
|
| 1849 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1850 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1851 |
|
| 1852 |
resolution = 0.1
|
| 1853 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2010,9 +2024,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2010 |
instance["centroid"] - fragment["centroid"]
|
| 2011 |
),
|
| 2012 |
)
|
| 2013 |
-
nearest["first_time"] = min(
|
| 2014 |
-
nearest["first_time"], fragment["first_time"]
|
| 2015 |
-
)
|
| 2016 |
consolidated[class_name] = retained
|
| 2017 |
return consolidated
|
| 2018 |
|
|
@@ -2045,9 +2057,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2045 |
points, up_axis
|
| 2046 |
)
|
| 2047 |
record = dict(item)
|
| 2048 |
-
record.update(
|
| 2049 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2050 |
-
)
|
| 2051 |
measured.append(record)
|
| 2052 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2053 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1647 |
# extremes; cleaning only the distance path gives the distance gain without the size cost.
|
| 1648 |
raw_proj = (
|
| 1649 |
np.stack(
|
| 1650 |
+
[observation @ u, observation @ v, observation @ g - floor_level],
|
| 1651 |
+
axis=1,
|
| 1652 |
)
|
| 1653 |
@ orientation.T
|
| 1654 |
)
|
|
|
|
| 1685 |
full_dimensions = np.asarray(full_dimensions)
|
| 1686 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1687 |
if len(centers) >= 4:
|
| 1688 |
+
features = np.concatenate(
|
| 1689 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1690 |
+
)
|
| 1691 |
median = np.median(features, axis=0)
|
| 1692 |
deviation = np.abs(features - median)
|
| 1693 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1749 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1750 |
)
|
| 1751 |
full_axis_dimensions = np.array(
|
| 1752 |
+
[
|
| 1753 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1754 |
+
for axis in range(3)
|
| 1755 |
+
]
|
| 1756 |
)
|
| 1757 |
box_dimensions = tight_dimensions.copy()
|
| 1758 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1851 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1852 |
if object_points:
|
| 1853 |
stacked = [
|
| 1854 |
+
np.stack(
|
| 1855 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1856 |
+
)
|
| 1857 |
for p in object_points
|
| 1858 |
if len(p)
|
| 1859 |
]
|
| 1860 |
if stacked:
|
| 1861 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1862 |
+
footprint_points = footprint_points[
|
| 1863 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1864 |
+
]
|
| 1865 |
|
| 1866 |
resolution = 0.1
|
| 1867 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2024 |
instance["centroid"] - fragment["centroid"]
|
| 2025 |
),
|
| 2026 |
)
|
| 2027 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2028 |
consolidated[class_name] = retained
|
| 2029 |
return consolidated
|
| 2030 |
|
|
|
|
| 2057 |
points, up_axis
|
| 2058 |
)
|
| 2059 |
record = dict(item)
|
| 2060 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2061 |
measured.append(record)
|
| 2062 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2063 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Clean Distance Path Raw Size Select.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1643,7 +1647,8 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1643 |
# extremes; cleaning only the distance path gives the distance gain without the size cost.
|
| 1644 |
raw_proj = (
|
| 1645 |
np.stack(
|
| 1646 |
-
[observation @ u, observation @ v, observation @ g - floor_level],
|
|
|
|
| 1647 |
)
|
| 1648 |
@ orientation.T
|
| 1649 |
)
|
|
@@ -1680,7 +1685,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1680 |
full_dimensions = np.asarray(full_dimensions)
|
| 1681 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1682 |
if len(centers) >= 4:
|
| 1683 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1684 |
median = np.median(features, axis=0)
|
| 1685 |
deviation = np.abs(features - median)
|
| 1686 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1742,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1742 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1743 |
)
|
| 1744 |
full_axis_dimensions = np.array(
|
| 1745 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1746 |
)
|
| 1747 |
box_dimensions = tight_dimensions.copy()
|
| 1748 |
# select the longest axis from the RAW full extent (size's own signal), NOT the cleaned
|
|
@@ -1845,13 +1855,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1845 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1846 |
if object_points:
|
| 1847 |
stacked = [
|
| 1848 |
-
np.stack(
|
|
|
|
|
|
|
| 1849 |
for p in object_points
|
| 1850 |
if len(p)
|
| 1851 |
]
|
| 1852 |
if stacked:
|
| 1853 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1854 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1855 |
|
| 1856 |
resolution = 0.1
|
| 1857 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2014,9 +2028,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2014 |
instance["centroid"] - fragment["centroid"]
|
| 2015 |
),
|
| 2016 |
)
|
| 2017 |
-
nearest["first_time"] = min(
|
| 2018 |
-
nearest["first_time"], fragment["first_time"]
|
| 2019 |
-
)
|
| 2020 |
consolidated[class_name] = retained
|
| 2021 |
return consolidated
|
| 2022 |
|
|
@@ -2049,9 +2061,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2049 |
points, up_axis
|
| 2050 |
)
|
| 2051 |
record = dict(item)
|
| 2052 |
-
record.update(
|
| 2053 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2054 |
-
)
|
| 2055 |
measured.append(record)
|
| 2056 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2057 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1647 |
# extremes; cleaning only the distance path gives the distance gain without the size cost.
|
| 1648 |
raw_proj = (
|
| 1649 |
np.stack(
|
| 1650 |
+
[observation @ u, observation @ v, observation @ g - floor_level],
|
| 1651 |
+
axis=1,
|
| 1652 |
)
|
| 1653 |
@ orientation.T
|
| 1654 |
)
|
|
|
|
| 1685 |
full_dimensions = np.asarray(full_dimensions)
|
| 1686 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1687 |
if len(centers) >= 4:
|
| 1688 |
+
features = np.concatenate(
|
| 1689 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1690 |
+
)
|
| 1691 |
median = np.median(features, axis=0)
|
| 1692 |
deviation = np.abs(features - median)
|
| 1693 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1749 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1750 |
)
|
| 1751 |
full_axis_dimensions = np.array(
|
| 1752 |
+
[
|
| 1753 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1754 |
+
for axis in range(3)
|
| 1755 |
+
]
|
| 1756 |
)
|
| 1757 |
box_dimensions = tight_dimensions.copy()
|
| 1758 |
# select the longest axis from the RAW full extent (size's own signal), NOT the cleaned
|
|
|
|
| 1855 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1856 |
if object_points:
|
| 1857 |
stacked = [
|
| 1858 |
+
np.stack(
|
| 1859 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1860 |
+
)
|
| 1861 |
for p in object_points
|
| 1862 |
if len(p)
|
| 1863 |
]
|
| 1864 |
if stacked:
|
| 1865 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1866 |
+
footprint_points = footprint_points[
|
| 1867 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1868 |
+
]
|
| 1869 |
|
| 1870 |
resolution = 0.1
|
| 1871 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2028 |
instance["centroid"] - fragment["centroid"]
|
| 2029 |
),
|
| 2030 |
)
|
| 2031 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2032 |
consolidated[class_name] = retained
|
| 2033 |
return consolidated
|
| 2034 |
|
|
|
|
| 2061 |
points, up_axis
|
| 2062 |
)
|
| 2063 |
record = dict(item)
|
| 2064 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2065 |
measured.append(record)
|
| 2066 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2067 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Clean Each Observation Before Extent Tight.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1659,7 +1663,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1659 |
upper = np.percentile(projected, 98, axis=0)
|
| 1660 |
centers.append((lower + upper) / 2)
|
| 1661 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1662 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1663 |
weights.append(len(observation))
|
| 1664 |
if not centers:
|
| 1665 |
projected = room_points @ orientation.T
|
|
@@ -1675,7 +1681,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1675 |
full_dimensions = np.asarray(full_dimensions)
|
| 1676 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1677 |
if len(centers) >= 4:
|
| 1678 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1679 |
median = np.median(features, axis=0)
|
| 1680 |
deviation = np.abs(features - median)
|
| 1681 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1737,7 +1745,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1737 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1738 |
)
|
| 1739 |
full_axis_dimensions = np.array(
|
| 1740 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1836,13 +1847,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
-
np.stack(
|
|
|
|
|
|
|
| 1840 |
for p in object_points
|
| 1841 |
if len(p)
|
| 1842 |
]
|
| 1843 |
if stacked:
|
| 1844 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1845 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1846 |
|
| 1847 |
resolution = 0.1
|
| 1848 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2005,9 +2020,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2005 |
instance["centroid"] - fragment["centroid"]
|
| 2006 |
),
|
| 2007 |
)
|
| 2008 |
-
nearest["first_time"] = min(
|
| 2009 |
-
nearest["first_time"], fragment["first_time"]
|
| 2010 |
-
)
|
| 2011 |
consolidated[class_name] = retained
|
| 2012 |
return consolidated
|
| 2013 |
|
|
@@ -2040,9 +2053,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2040 |
points, up_axis
|
| 2041 |
)
|
| 2042 |
record = dict(item)
|
| 2043 |
-
record.update(
|
| 2044 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2045 |
-
)
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1663 |
upper = np.percentile(projected, 98, axis=0)
|
| 1664 |
centers.append((lower + upper) / 2)
|
| 1665 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1666 |
+
full_dimensions.append(
|
| 1667 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1668 |
+
)
|
| 1669 |
weights.append(len(observation))
|
| 1670 |
if not centers:
|
| 1671 |
projected = room_points @ orientation.T
|
|
|
|
| 1681 |
full_dimensions = np.asarray(full_dimensions)
|
| 1682 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1683 |
if len(centers) >= 4:
|
| 1684 |
+
features = np.concatenate(
|
| 1685 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1686 |
+
)
|
| 1687 |
median = np.median(features, axis=0)
|
| 1688 |
deviation = np.abs(features - median)
|
| 1689 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1745 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1746 |
)
|
| 1747 |
full_axis_dimensions = np.array(
|
| 1748 |
+
[
|
| 1749 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1750 |
+
for axis in range(3)
|
| 1751 |
+
]
|
| 1752 |
)
|
| 1753 |
box_dimensions = tight_dimensions.copy()
|
| 1754 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1847 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1848 |
if object_points:
|
| 1849 |
stacked = [
|
| 1850 |
+
np.stack(
|
| 1851 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1852 |
+
)
|
| 1853 |
for p in object_points
|
| 1854 |
if len(p)
|
| 1855 |
]
|
| 1856 |
if stacked:
|
| 1857 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1858 |
+
footprint_points = footprint_points[
|
| 1859 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1860 |
+
]
|
| 1861 |
|
| 1862 |
resolution = 0.1
|
| 1863 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2020 |
instance["centroid"] - fragment["centroid"]
|
| 2021 |
),
|
| 2022 |
)
|
| 2023 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2024 |
consolidated[class_name] = retained
|
| 2025 |
return consolidated
|
| 2026 |
|
|
|
|
| 2053 |
points, up_axis
|
| 2054 |
)
|
| 2055 |
record = dict(item)
|
| 2056 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2057 |
measured.append(record)
|
| 2058 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2059 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Clean Each Observation Before Extent.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1659,7 +1663,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1659 |
upper = np.percentile(projected, 98, axis=0)
|
| 1660 |
centers.append((lower + upper) / 2)
|
| 1661 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1662 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1663 |
weights.append(len(observation))
|
| 1664 |
if not centers:
|
| 1665 |
projected = room_points @ orientation.T
|
|
@@ -1675,7 +1681,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1675 |
full_dimensions = np.asarray(full_dimensions)
|
| 1676 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1677 |
if len(centers) >= 4:
|
| 1678 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1679 |
median = np.median(features, axis=0)
|
| 1680 |
deviation = np.abs(features - median)
|
| 1681 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1737,7 +1745,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1737 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1738 |
)
|
| 1739 |
full_axis_dimensions = np.array(
|
| 1740 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1836,13 +1847,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
-
np.stack(
|
|
|
|
|
|
|
| 1840 |
for p in object_points
|
| 1841 |
if len(p)
|
| 1842 |
]
|
| 1843 |
if stacked:
|
| 1844 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1845 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1846 |
|
| 1847 |
resolution = 0.1
|
| 1848 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2005,9 +2020,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2005 |
instance["centroid"] - fragment["centroid"]
|
| 2006 |
),
|
| 2007 |
)
|
| 2008 |
-
nearest["first_time"] = min(
|
| 2009 |
-
nearest["first_time"], fragment["first_time"]
|
| 2010 |
-
)
|
| 2011 |
consolidated[class_name] = retained
|
| 2012 |
return consolidated
|
| 2013 |
|
|
@@ -2040,9 +2053,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2040 |
points, up_axis
|
| 2041 |
)
|
| 2042 |
record = dict(item)
|
| 2043 |
-
record.update(
|
| 2044 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2045 |
-
)
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1663 |
upper = np.percentile(projected, 98, axis=0)
|
| 1664 |
centers.append((lower + upper) / 2)
|
| 1665 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1666 |
+
full_dimensions.append(
|
| 1667 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1668 |
+
)
|
| 1669 |
weights.append(len(observation))
|
| 1670 |
if not centers:
|
| 1671 |
projected = room_points @ orientation.T
|
|
|
|
| 1681 |
full_dimensions = np.asarray(full_dimensions)
|
| 1682 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1683 |
if len(centers) >= 4:
|
| 1684 |
+
features = np.concatenate(
|
| 1685 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1686 |
+
)
|
| 1687 |
median = np.median(features, axis=0)
|
| 1688 |
deviation = np.abs(features - median)
|
| 1689 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1745 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1746 |
)
|
| 1747 |
full_axis_dimensions = np.array(
|
| 1748 |
+
[
|
| 1749 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1750 |
+
for axis in range(3)
|
| 1751 |
+
]
|
| 1752 |
)
|
| 1753 |
box_dimensions = tight_dimensions.copy()
|
| 1754 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1847 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1848 |
if object_points:
|
| 1849 |
stacked = [
|
| 1850 |
+
np.stack(
|
| 1851 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1852 |
+
)
|
| 1853 |
for p in object_points
|
| 1854 |
if len(p)
|
| 1855 |
]
|
| 1856 |
if stacked:
|
| 1857 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1858 |
+
footprint_points = footprint_points[
|
| 1859 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1860 |
+
]
|
| 1861 |
|
| 1862 |
resolution = 0.1
|
| 1863 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2020 |
instance["centroid"] - fragment["centroid"]
|
| 2021 |
),
|
| 2022 |
)
|
| 2023 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2024 |
consolidated[class_name] = retained
|
| 2025 |
return consolidated
|
| 2026 |
|
|
|
|
| 2053 |
points, up_axis
|
| 2054 |
)
|
| 2055 |
record = dict(item)
|
| 2056 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2057 |
measured.append(record)
|
| 2058 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2059 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Confidence Weighted Box Frames.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1226,7 +1233,8 @@ def dump_spatial_code(code, path):
|
|
| 1226 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1227 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1228 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1229 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1230 |
body = dict(code)
|
| 1231 |
ao = body.pop("appearance order", None)
|
| 1232 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1606,15 +1614,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1606 |
points = _canonical_clean(instance)
|
| 1607 |
if not len(points):
|
| 1608 |
points = instance["pts"]
|
| 1609 |
-
room_points = np.stack(
|
| 1610 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1611 |
-
)
|
| 1612 |
horizontal = room_points[:, :2]
|
| 1613 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1614 |
if len(centered) > 5000:
|
| 1615 |
-
centered = centered[
|
| 1616 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1617 |
-
]
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1658,9 +1662,15 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1658 |
upper = np.percentile(projected, 98, axis=0)
|
| 1659 |
centers.append((lower + upper) / 2)
|
| 1660 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1661 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1662 |
_mc = 1.0
|
| 1663 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1664 |
_cf = np.asarray(_obs_conf[_oi], np.float64)
|
| 1665 |
_cf = _cf[finite] if len(_cf) == len(finite) else _cf
|
| 1666 |
if len(_cf):
|
|
@@ -1680,7 +1690,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1680 |
full_dimensions = np.asarray(full_dimensions)
|
| 1681 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1682 |
if len(centers) >= 4:
|
| 1683 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1684 |
median = np.median(features, axis=0)
|
| 1685 |
deviation = np.abs(features - median)
|
| 1686 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1742,7 +1754,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1742 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1743 |
)
|
| 1744 |
full_axis_dimensions = np.array(
|
| 1745 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1746 |
)
|
| 1747 |
box_dimensions = tight_dimensions.copy()
|
| 1748 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1841,13 +1856,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1841 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1842 |
if object_points:
|
| 1843 |
stacked = [
|
| 1844 |
-
np.stack(
|
|
|
|
|
|
|
| 1845 |
for p in object_points
|
| 1846 |
if len(p)
|
| 1847 |
]
|
| 1848 |
if stacked:
|
| 1849 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1850 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1851 |
|
| 1852 |
resolution = 0.1
|
| 1853 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2010,9 +2029,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2010 |
instance["centroid"] - fragment["centroid"]
|
| 2011 |
),
|
| 2012 |
)
|
| 2013 |
-
nearest["first_time"] = min(
|
| 2014 |
-
nearest["first_time"], fragment["first_time"]
|
| 2015 |
-
)
|
| 2016 |
consolidated[class_name] = retained
|
| 2017 |
return consolidated
|
| 2018 |
|
|
@@ -2045,9 +2062,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2045 |
points, up_axis
|
| 2046 |
)
|
| 2047 |
record = dict(item)
|
| 2048 |
-
record.update(
|
| 2049 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2050 |
-
)
|
| 2051 |
measured.append(record)
|
| 2052 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2053 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1233 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1234 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1235 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1236 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1237 |
+
"""
|
| 1238 |
body = dict(code)
|
| 1239 |
ao = body.pop("appearance order", None)
|
| 1240 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1614 |
points = _canonical_clean(instance)
|
| 1615 |
if not len(points):
|
| 1616 |
points = instance["pts"]
|
| 1617 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1618 |
horizontal = room_points[:, :2]
|
| 1619 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1620 |
if len(centered) > 5000:
|
| 1621 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1622 |
try:
|
| 1623 |
_, _, rotation = np.linalg.svd(
|
| 1624 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1662 |
upper = np.percentile(projected, 98, axis=0)
|
| 1663 |
centers.append((lower + upper) / 2)
|
| 1664 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1665 |
+
full_dimensions.append(
|
| 1666 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1667 |
+
)
|
| 1668 |
_mc = 1.0
|
| 1669 |
+
if (
|
| 1670 |
+
_obs_conf is not None
|
| 1671 |
+
and _oi < len(_obs_conf)
|
| 1672 |
+
and _obs_conf[_oi] is not None
|
| 1673 |
+
):
|
| 1674 |
_cf = np.asarray(_obs_conf[_oi], np.float64)
|
| 1675 |
_cf = _cf[finite] if len(_cf) == len(finite) else _cf
|
| 1676 |
if len(_cf):
|
|
|
|
| 1690 |
full_dimensions = np.asarray(full_dimensions)
|
| 1691 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1692 |
if len(centers) >= 4:
|
| 1693 |
+
features = np.concatenate(
|
| 1694 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1695 |
+
)
|
| 1696 |
median = np.median(features, axis=0)
|
| 1697 |
deviation = np.abs(features - median)
|
| 1698 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1754 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1755 |
)
|
| 1756 |
full_axis_dimensions = np.array(
|
| 1757 |
+
[
|
| 1758 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1759 |
+
for axis in range(3)
|
| 1760 |
+
]
|
| 1761 |
)
|
| 1762 |
box_dimensions = tight_dimensions.copy()
|
| 1763 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1856 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1857 |
if object_points:
|
| 1858 |
stacked = [
|
| 1859 |
+
np.stack(
|
| 1860 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1861 |
+
)
|
| 1862 |
for p in object_points
|
| 1863 |
if len(p)
|
| 1864 |
]
|
| 1865 |
if stacked:
|
| 1866 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1867 |
+
footprint_points = footprint_points[
|
| 1868 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1869 |
+
]
|
| 1870 |
|
| 1871 |
resolution = 0.1
|
| 1872 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2029 |
instance["centroid"] - fragment["centroid"]
|
| 2030 |
),
|
| 2031 |
)
|
| 2032 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2033 |
consolidated[class_name] = retained
|
| 2034 |
return consolidated
|
| 2035 |
|
|
|
|
| 2062 |
points, up_axis
|
| 2063 |
)
|
| 2064 |
record = dict(item)
|
| 2065 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2066 |
measured.append(record)
|
| 2067 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2068 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Confidence Weighted Percentile Short Axes.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1226,7 +1233,8 @@ def dump_spatial_code(code, path):
|
|
| 1226 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1227 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1228 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1229 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1230 |
body = dict(code)
|
| 1231 |
ao = body.pop("appearance order", None)
|
| 1232 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1603,7 +1611,8 @@ def _weighted_quantile(values, weights, quantile):
|
|
| 1603 |
|
| 1604 |
def _weighted_percentile_axis(values, weights, q):
|
| 1605 |
"""Per-column weighted percentile of an (N,3) array; q in [0,100]. Confidence weights let
|
| 1606 |
-
low-confidence points (mask-bleed at depth boundaries) count less toward the extent.
|
|
|
|
| 1607 |
out = np.empty(values.shape[1], np.float64)
|
| 1608 |
wsum = weights.sum()
|
| 1609 |
if wsum <= 0:
|
|
@@ -1622,15 +1631,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1622 |
points = _canonical_clean(instance)
|
| 1623 |
if not len(points):
|
| 1624 |
points = instance["pts"]
|
| 1625 |
-
room_points = np.stack(
|
| 1626 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1627 |
-
)
|
| 1628 |
horizontal = room_points[:, :2]
|
| 1629 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1630 |
if len(centered) > 5000:
|
| 1631 |
-
centered = centered[
|
| 1632 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1633 |
-
]
|
| 1634 |
try:
|
| 1635 |
_, _, rotation = np.linalg.svd(
|
| 1636 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1666,7 +1671,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1666 |
)
|
| 1667 |
projected = observed @ orientation.T
|
| 1668 |
_cf = None
|
| 1669 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1670 |
_cf = np.asarray(_obs_conf[_oi], np.float64)
|
| 1671 |
_cf = _cf[finite] if len(_cf) == len(finite) else None
|
| 1672 |
if _cf is not None and len(_cf) == len(projected) and len(projected) >= 8:
|
|
@@ -1678,7 +1687,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1678 |
upper = np.percentile(projected, 98, axis=0)
|
| 1679 |
centers.append((lower + upper) / 2)
|
| 1680 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1681 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1682 |
weights.append(len(observation))
|
| 1683 |
if not centers:
|
| 1684 |
projected = room_points @ orientation.T
|
|
@@ -1694,7 +1705,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1694 |
full_dimensions = np.asarray(full_dimensions)
|
| 1695 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1696 |
if len(centers) >= 4:
|
| 1697 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1698 |
median = np.median(features, axis=0)
|
| 1699 |
deviation = np.abs(features - median)
|
| 1700 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1756,7 +1769,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1756 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1757 |
)
|
| 1758 |
full_axis_dimensions = np.array(
|
| 1759 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1760 |
)
|
| 1761 |
box_dimensions = tight_dimensions.copy()
|
| 1762 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1855,13 +1871,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1855 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1856 |
if object_points:
|
| 1857 |
stacked = [
|
| 1858 |
-
np.stack(
|
|
|
|
|
|
|
| 1859 |
for p in object_points
|
| 1860 |
if len(p)
|
| 1861 |
]
|
| 1862 |
if stacked:
|
| 1863 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1864 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1865 |
|
| 1866 |
resolution = 0.1
|
| 1867 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2024,9 +2044,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2024 |
instance["centroid"] - fragment["centroid"]
|
| 2025 |
),
|
| 2026 |
)
|
| 2027 |
-
nearest["first_time"] = min(
|
| 2028 |
-
nearest["first_time"], fragment["first_time"]
|
| 2029 |
-
)
|
| 2030 |
consolidated[class_name] = retained
|
| 2031 |
return consolidated
|
| 2032 |
|
|
@@ -2059,9 +2077,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2059 |
points, up_axis
|
| 2060 |
)
|
| 2061 |
record = dict(item)
|
| 2062 |
-
record.update(
|
| 2063 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2064 |
-
)
|
| 2065 |
measured.append(record)
|
| 2066 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2067 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1233 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1234 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1235 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1236 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1237 |
+
"""
|
| 1238 |
body = dict(code)
|
| 1239 |
ao = body.pop("appearance order", None)
|
| 1240 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1611 |
|
| 1612 |
def _weighted_percentile_axis(values, weights, q):
|
| 1613 |
"""Per-column weighted percentile of an (N,3) array; q in [0,100]. Confidence weights let
|
| 1614 |
+
low-confidence points (mask-bleed at depth boundaries) count less toward the extent.
|
| 1615 |
+
"""
|
| 1616 |
out = np.empty(values.shape[1], np.float64)
|
| 1617 |
wsum = weights.sum()
|
| 1618 |
if wsum <= 0:
|
|
|
|
| 1631 |
points = _canonical_clean(instance)
|
| 1632 |
if not len(points):
|
| 1633 |
points = instance["pts"]
|
| 1634 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1635 |
horizontal = room_points[:, :2]
|
| 1636 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1637 |
if len(centered) > 5000:
|
| 1638 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1639 |
try:
|
| 1640 |
_, _, rotation = np.linalg.svd(
|
| 1641 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1671 |
)
|
| 1672 |
projected = observed @ orientation.T
|
| 1673 |
_cf = None
|
| 1674 |
+
if (
|
| 1675 |
+
_obs_conf is not None
|
| 1676 |
+
and _oi < len(_obs_conf)
|
| 1677 |
+
and _obs_conf[_oi] is not None
|
| 1678 |
+
):
|
| 1679 |
_cf = np.asarray(_obs_conf[_oi], np.float64)
|
| 1680 |
_cf = _cf[finite] if len(_cf) == len(finite) else None
|
| 1681 |
if _cf is not None and len(_cf) == len(projected) and len(projected) >= 8:
|
|
|
|
| 1687 |
upper = np.percentile(projected, 98, axis=0)
|
| 1688 |
centers.append((lower + upper) / 2)
|
| 1689 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1690 |
+
full_dimensions.append(
|
| 1691 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1692 |
+
)
|
| 1693 |
weights.append(len(observation))
|
| 1694 |
if not centers:
|
| 1695 |
projected = room_points @ orientation.T
|
|
|
|
| 1705 |
full_dimensions = np.asarray(full_dimensions)
|
| 1706 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1707 |
if len(centers) >= 4:
|
| 1708 |
+
features = np.concatenate(
|
| 1709 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1710 |
+
)
|
| 1711 |
median = np.median(features, axis=0)
|
| 1712 |
deviation = np.abs(features - median)
|
| 1713 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1769 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1770 |
)
|
| 1771 |
full_axis_dimensions = np.array(
|
| 1772 |
+
[
|
| 1773 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1774 |
+
for axis in range(3)
|
| 1775 |
+
]
|
| 1776 |
)
|
| 1777 |
box_dimensions = tight_dimensions.copy()
|
| 1778 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1871 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1872 |
if object_points:
|
| 1873 |
stacked = [
|
| 1874 |
+
np.stack(
|
| 1875 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1876 |
+
)
|
| 1877 |
for p in object_points
|
| 1878 |
if len(p)
|
| 1879 |
]
|
| 1880 |
if stacked:
|
| 1881 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1882 |
+
footprint_points = footprint_points[
|
| 1883 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1884 |
+
]
|
| 1885 |
|
| 1886 |
resolution = 0.1
|
| 1887 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2044 |
instance["centroid"] - fragment["centroid"]
|
| 2045 |
),
|
| 2046 |
)
|
| 2047 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2048 |
consolidated[class_name] = retained
|
| 2049 |
return consolidated
|
| 2050 |
|
|
|
|
| 2077 |
points, up_axis
|
| 2078 |
)
|
| 2079 |
record = dict(item)
|
| 2080 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2081 |
measured.append(record)
|
| 2082 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2083 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Consensus Filter At Two Sigma.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2009 |
instance["centroid"] - fragment["centroid"]
|
| 2010 |
),
|
| 2011 |
)
|
| 2012 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2013 |
consolidated[class_name] = retained
|
| 2014 |
return consolidated
|
| 2015 |
|
|
|
|
| 2042 |
points, up_axis
|
| 2043 |
)
|
| 2044 |
record = dict(item)
|
| 2045 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2046 |
measured.append(record)
|
| 2047 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2048 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Decouple Tight Short Axes Stable Longest 030.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1723 |
[_weighted_quantile(dimensions[:, axis], weights, 0.3) for axis in range(3)]
|
| 1724 |
)
|
| 1725 |
full_axis_dimensions = np.array(
|
| 1726 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1727 |
)
|
| 1728 |
box_dimensions = tight_dimensions.copy()
|
| 1729 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1822 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1823 |
if object_points:
|
| 1824 |
stacked = [
|
| 1825 |
-
np.stack(
|
|
|
|
|
|
|
| 1826 |
for p in object_points
|
| 1827 |
if len(p)
|
| 1828 |
]
|
| 1829 |
if stacked:
|
| 1830 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1831 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1832 |
|
| 1833 |
resolution = 0.1
|
| 1834 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1991 |
instance["centroid"] - fragment["centroid"]
|
| 1992 |
),
|
| 1993 |
)
|
| 1994 |
-
nearest["first_time"] = min(
|
| 1995 |
-
nearest["first_time"], fragment["first_time"]
|
| 1996 |
-
)
|
| 1997 |
consolidated[class_name] = retained
|
| 1998 |
return consolidated
|
| 1999 |
|
|
@@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2026 |
points, up_axis
|
| 2027 |
)
|
| 2028 |
record = dict(item)
|
| 2029 |
-
record.update(
|
| 2030 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2031 |
-
)
|
| 2032 |
measured.append(record)
|
| 2033 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2034 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1731 |
[_weighted_quantile(dimensions[:, axis], weights, 0.3) for axis in range(3)]
|
| 1732 |
)
|
| 1733 |
full_axis_dimensions = np.array(
|
| 1734 |
+
[
|
| 1735 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1736 |
+
for axis in range(3)
|
| 1737 |
+
]
|
| 1738 |
)
|
| 1739 |
box_dimensions = tight_dimensions.copy()
|
| 1740 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1833 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1834 |
if object_points:
|
| 1835 |
stacked = [
|
| 1836 |
+
np.stack(
|
| 1837 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1838 |
+
)
|
| 1839 |
for p in object_points
|
| 1840 |
if len(p)
|
| 1841 |
]
|
| 1842 |
if stacked:
|
| 1843 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1844 |
+
footprint_points = footprint_points[
|
| 1845 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1846 |
+
]
|
| 1847 |
|
| 1848 |
resolution = 0.1
|
| 1849 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2006 |
instance["centroid"] - fragment["centroid"]
|
| 2007 |
),
|
| 2008 |
)
|
| 2009 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2010 |
consolidated[class_name] = retained
|
| 2011 |
return consolidated
|
| 2012 |
|
|
|
|
| 2039 |
points, up_axis
|
| 2040 |
)
|
| 2041 |
record = dict(item)
|
| 2042 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2043 |
measured.append(record)
|
| 2044 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2045 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Decouple Tight Short Axes Stable Longest 040.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1723 |
[_weighted_quantile(dimensions[:, axis], weights, 0.4) for axis in range(3)]
|
| 1724 |
)
|
| 1725 |
full_axis_dimensions = np.array(
|
| 1726 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1727 |
)
|
| 1728 |
box_dimensions = tight_dimensions.copy()
|
| 1729 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1822 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1823 |
if object_points:
|
| 1824 |
stacked = [
|
| 1825 |
-
np.stack(
|
|
|
|
|
|
|
| 1826 |
for p in object_points
|
| 1827 |
if len(p)
|
| 1828 |
]
|
| 1829 |
if stacked:
|
| 1830 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1831 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1832 |
|
| 1833 |
resolution = 0.1
|
| 1834 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1991 |
instance["centroid"] - fragment["centroid"]
|
| 1992 |
),
|
| 1993 |
)
|
| 1994 |
-
nearest["first_time"] = min(
|
| 1995 |
-
nearest["first_time"], fragment["first_time"]
|
| 1996 |
-
)
|
| 1997 |
consolidated[class_name] = retained
|
| 1998 |
return consolidated
|
| 1999 |
|
|
@@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2026 |
points, up_axis
|
| 2027 |
)
|
| 2028 |
record = dict(item)
|
| 2029 |
-
record.update(
|
| 2030 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2031 |
-
)
|
| 2032 |
measured.append(record)
|
| 2033 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2034 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1731 |
[_weighted_quantile(dimensions[:, axis], weights, 0.4) for axis in range(3)]
|
| 1732 |
)
|
| 1733 |
full_axis_dimensions = np.array(
|
| 1734 |
+
[
|
| 1735 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1736 |
+
for axis in range(3)
|
| 1737 |
+
]
|
| 1738 |
)
|
| 1739 |
box_dimensions = tight_dimensions.copy()
|
| 1740 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1833 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1834 |
if object_points:
|
| 1835 |
stacked = [
|
| 1836 |
+
np.stack(
|
| 1837 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1838 |
+
)
|
| 1839 |
for p in object_points
|
| 1840 |
if len(p)
|
| 1841 |
]
|
| 1842 |
if stacked:
|
| 1843 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1844 |
+
footprint_points = footprint_points[
|
| 1845 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1846 |
+
]
|
| 1847 |
|
| 1848 |
resolution = 0.1
|
| 1849 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2006 |
instance["centroid"] - fragment["centroid"]
|
| 2007 |
),
|
| 2008 |
)
|
| 2009 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2010 |
consolidated[class_name] = retained
|
| 2011 |
return consolidated
|
| 2012 |
|
|
|
|
| 2039 |
points, up_axis
|
| 2040 |
)
|
| 2041 |
record = dict(item)
|
| 2042 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2043 |
measured.append(record)
|
| 2044 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2045 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Decouple Tight Short Axes Stable Longest 050.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1723 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1724 |
)
|
| 1725 |
full_axis_dimensions = np.array(
|
| 1726 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1727 |
)
|
| 1728 |
box_dimensions = tight_dimensions.copy()
|
| 1729 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1822 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1823 |
if object_points:
|
| 1824 |
stacked = [
|
| 1825 |
-
np.stack(
|
|
|
|
|
|
|
| 1826 |
for p in object_points
|
| 1827 |
if len(p)
|
| 1828 |
]
|
| 1829 |
if stacked:
|
| 1830 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1831 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1832 |
|
| 1833 |
resolution = 0.1
|
| 1834 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1991 |
instance["centroid"] - fragment["centroid"]
|
| 1992 |
),
|
| 1993 |
)
|
| 1994 |
-
nearest["first_time"] = min(
|
| 1995 |
-
nearest["first_time"], fragment["first_time"]
|
| 1996 |
-
)
|
| 1997 |
consolidated[class_name] = retained
|
| 1998 |
return consolidated
|
| 1999 |
|
|
@@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2026 |
points, up_axis
|
| 2027 |
)
|
| 2028 |
record = dict(item)
|
| 2029 |
-
record.update(
|
| 2030 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2031 |
-
)
|
| 2032 |
measured.append(record)
|
| 2033 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2034 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1731 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1732 |
)
|
| 1733 |
full_axis_dimensions = np.array(
|
| 1734 |
+
[
|
| 1735 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1736 |
+
for axis in range(3)
|
| 1737 |
+
]
|
| 1738 |
)
|
| 1739 |
box_dimensions = tight_dimensions.copy()
|
| 1740 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1833 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1834 |
if object_points:
|
| 1835 |
stacked = [
|
| 1836 |
+
np.stack(
|
| 1837 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1838 |
+
)
|
| 1839 |
for p in object_points
|
| 1840 |
if len(p)
|
| 1841 |
]
|
| 1842 |
if stacked:
|
| 1843 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1844 |
+
footprint_points = footprint_points[
|
| 1845 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1846 |
+
]
|
| 1847 |
|
| 1848 |
resolution = 0.1
|
| 1849 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2006 |
instance["centroid"] - fragment["centroid"]
|
| 2007 |
),
|
| 2008 |
)
|
| 2009 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2010 |
consolidated[class_name] = retained
|
| 2011 |
return consolidated
|
| 2012 |
|
|
|
|
| 2039 |
points, up_axis
|
| 2040 |
)
|
| 2041 |
record = dict(item)
|
| 2042 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2043 |
measured.append(record)
|
| 2044 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2045 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Decouple Tight Short Axes Stable Longest 060.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1723 |
[_weighted_quantile(dimensions[:, axis], weights, 0.6) for axis in range(3)]
|
| 1724 |
)
|
| 1725 |
full_axis_dimensions = np.array(
|
| 1726 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1727 |
)
|
| 1728 |
box_dimensions = tight_dimensions.copy()
|
| 1729 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1822 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1823 |
if object_points:
|
| 1824 |
stacked = [
|
| 1825 |
-
np.stack(
|
|
|
|
|
|
|
| 1826 |
for p in object_points
|
| 1827 |
if len(p)
|
| 1828 |
]
|
| 1829 |
if stacked:
|
| 1830 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1831 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1832 |
|
| 1833 |
resolution = 0.1
|
| 1834 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1991 |
instance["centroid"] - fragment["centroid"]
|
| 1992 |
),
|
| 1993 |
)
|
| 1994 |
-
nearest["first_time"] = min(
|
| 1995 |
-
nearest["first_time"], fragment["first_time"]
|
| 1996 |
-
)
|
| 1997 |
consolidated[class_name] = retained
|
| 1998 |
return consolidated
|
| 1999 |
|
|
@@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2026 |
points, up_axis
|
| 2027 |
)
|
| 2028 |
record = dict(item)
|
| 2029 |
-
record.update(
|
| 2030 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2031 |
-
)
|
| 2032 |
measured.append(record)
|
| 2033 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2034 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1731 |
[_weighted_quantile(dimensions[:, axis], weights, 0.6) for axis in range(3)]
|
| 1732 |
)
|
| 1733 |
full_axis_dimensions = np.array(
|
| 1734 |
+
[
|
| 1735 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1736 |
+
for axis in range(3)
|
| 1737 |
+
]
|
| 1738 |
)
|
| 1739 |
box_dimensions = tight_dimensions.copy()
|
| 1740 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1833 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1834 |
if object_points:
|
| 1835 |
stacked = [
|
| 1836 |
+
np.stack(
|
| 1837 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1838 |
+
)
|
| 1839 |
for p in object_points
|
| 1840 |
if len(p)
|
| 1841 |
]
|
| 1842 |
if stacked:
|
| 1843 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1844 |
+
footprint_points = footprint_points[
|
| 1845 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1846 |
+
]
|
| 1847 |
|
| 1848 |
resolution = 0.1
|
| 1849 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2006 |
instance["centroid"] - fragment["centroid"]
|
| 2007 |
),
|
| 2008 |
)
|
| 2009 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2010 |
consolidated[class_name] = retained
|
| 2011 |
return consolidated
|
| 2012 |
|
|
|
|
| 2039 |
points, up_axis
|
| 2040 |
)
|
| 2041 |
record = dict(item)
|
| 2042 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2043 |
measured.append(record)
|
| 2044 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2045 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Depth Edge Bleed Cut Alone.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -64,7 +63,9 @@ CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0"))
|
|
| 64 |
DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
|
| 65 |
# cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
|
| 66 |
# -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
|
| 67 |
-
DEPTH_EDGE_REFINE =
|
|
|
|
|
|
|
| 68 |
# MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
|
| 69 |
# depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
|
| 70 |
MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
|
|
@@ -118,7 +119,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +213,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +439,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +455,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +492,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +519,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +576,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +632,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1234,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1615,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1654,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1672,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2044,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 63 |
DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
|
| 64 |
# cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
|
| 65 |
# -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
|
| 66 |
+
DEPTH_EDGE_REFINE = (
|
| 67 |
+
os.environ.get("VSI_DEPTH_EDGE_REFINE", "1") == "1"
|
| 68 |
+
) # HYPOTHESIS: ON -- cut mask-bleed at depth boundaries at the source
|
| 69 |
# MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
|
| 70 |
# depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
|
| 71 |
MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
|
|
|
|
| 119 |
):
|
| 120 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 121 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 122 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 123 |
+
"""
|
| 124 |
points = []
|
| 125 |
for f in range(0, len(depth), fstride):
|
| 126 |
height, width = depth[f].shape
|
|
|
|
| 213 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 214 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 215 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 216 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 217 |
+
"""
|
| 218 |
g = np.asarray(up_vec, np.float64)
|
| 219 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 220 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 439 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 440 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 441 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 442 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 443 |
+
"""
|
| 444 |
from scipy.spatial import cKDTree
|
| 445 |
|
| 446 |
if len(pts) < k + 2:
|
|
|
|
| 455 |
def _main_cluster(pts):
|
| 456 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 457 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 458 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 459 |
+
"""
|
| 460 |
from scipy.spatial import cKDTree
|
| 461 |
|
| 462 |
if len(pts) < 30:
|
|
|
|
| 492 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 493 |
object's OWN median confidence (data-derived cut);
|
| 494 |
(2) statistical density outlier removal on the survivors;
|
| 495 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 496 |
+
"""
|
| 497 |
if inst.get("_cleanpts") is not None:
|
| 498 |
return inst["_cleanpts"]
|
| 499 |
pts = inst["pts"]
|
|
|
|
| 519 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 520 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 521 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 522 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 523 |
+
"""
|
| 524 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 525 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 526 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 576 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 577 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 578 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 579 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 580 |
+
"""
|
| 581 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 582 |
mask = cv2.resize(
|
| 583 |
mask.astype(np.uint8),
|
|
|
|
| 632 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 633 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 634 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 635 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 636 |
+
"""
|
| 637 |
height, width = depth_f.shape
|
| 638 |
empty = (
|
| 639 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1234 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1235 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1236 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1237 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1238 |
+
"""
|
| 1239 |
body = dict(code)
|
| 1240 |
ao = body.pop("appearance order", None)
|
| 1241 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1615 |
points = _canonical_clean(instance)
|
| 1616 |
if not len(points):
|
| 1617 |
points = instance["pts"]
|
| 1618 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1619 |
horizontal = room_points[:, :2]
|
| 1620 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1621 |
if len(centered) > 5000:
|
| 1622 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1623 |
try:
|
| 1624 |
_, _, rotation = np.linalg.svd(
|
| 1625 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1654 |
upper = np.percentile(projected, 98, axis=0)
|
| 1655 |
centers.append((lower + upper) / 2)
|
| 1656 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1657 |
+
full_dimensions.append(
|
| 1658 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1659 |
+
)
|
| 1660 |
weights.append(len(observation))
|
| 1661 |
if not centers:
|
| 1662 |
projected = room_points @ orientation.T
|
|
|
|
| 1672 |
full_dimensions = np.asarray(full_dimensions)
|
| 1673 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1674 |
if len(centers) >= 4:
|
| 1675 |
+
features = np.concatenate(
|
| 1676 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1677 |
+
)
|
| 1678 |
median = np.median(features, axis=0)
|
| 1679 |
deviation = np.abs(features - median)
|
| 1680 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1736 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1737 |
)
|
| 1738 |
full_axis_dimensions = np.array(
|
| 1739 |
+
[
|
| 1740 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1741 |
+
for axis in range(3)
|
| 1742 |
+
]
|
| 1743 |
)
|
| 1744 |
box_dimensions = tight_dimensions.copy()
|
| 1745 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1838 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1839 |
if object_points:
|
| 1840 |
stacked = [
|
| 1841 |
+
np.stack(
|
| 1842 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1843 |
+
)
|
| 1844 |
for p in object_points
|
| 1845 |
if len(p)
|
| 1846 |
]
|
| 1847 |
if stacked:
|
| 1848 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1849 |
+
footprint_points = footprint_points[
|
| 1850 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1851 |
+
]
|
| 1852 |
|
| 1853 |
resolution = 0.1
|
| 1854 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2011 |
instance["centroid"] - fragment["centroid"]
|
| 2012 |
),
|
| 2013 |
)
|
| 2014 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2015 |
consolidated[class_name] = retained
|
| 2016 |
return consolidated
|
| 2017 |
|
|
|
|
| 2044 |
points, up_axis
|
| 2045 |
)
|
| 2046 |
record = dict(item)
|
| 2047 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2048 |
measured.append(record)
|
| 2049 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2050 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Depth Edge Bleed Cut With Short Axis Median.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -64,7 +63,9 @@ CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0"))
|
|
| 64 |
DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
|
| 65 |
# cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
|
| 66 |
# -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
|
| 67 |
-
DEPTH_EDGE_REFINE =
|
|
|
|
|
|
|
| 68 |
# MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
|
| 69 |
# depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
|
| 70 |
MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
|
|
@@ -118,7 +119,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +213,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +439,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +455,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +492,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +519,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +576,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +632,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1234,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1615,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1654,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1672,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1994,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1994 |
instance["centroid"] - fragment["centroid"]
|
| 1995 |
),
|
| 1996 |
)
|
| 1997 |
-
nearest["first_time"] = min(
|
| 1998 |
-
nearest["first_time"], fragment["first_time"]
|
| 1999 |
-
)
|
| 2000 |
consolidated[class_name] = retained
|
| 2001 |
return consolidated
|
| 2002 |
|
|
@@ -2029,9 +2044,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2029 |
points, up_axis
|
| 2030 |
)
|
| 2031 |
record = dict(item)
|
| 2032 |
-
record.update(
|
| 2033 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2034 |
-
)
|
| 2035 |
measured.append(record)
|
| 2036 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2037 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 63 |
DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
|
| 64 |
# cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
|
| 65 |
# -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
|
| 66 |
+
DEPTH_EDGE_REFINE = (
|
| 67 |
+
os.environ.get("VSI_DEPTH_EDGE_REFINE", "1") == "1"
|
| 68 |
+
) # HYPOTHESIS: ON -- cut mask-bleed at depth boundaries at the source
|
| 69 |
# MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
|
| 70 |
# depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
|
| 71 |
MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
|
|
|
|
| 119 |
):
|
| 120 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 121 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 122 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 123 |
+
"""
|
| 124 |
points = []
|
| 125 |
for f in range(0, len(depth), fstride):
|
| 126 |
height, width = depth[f].shape
|
|
|
|
| 213 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 214 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 215 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 216 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 217 |
+
"""
|
| 218 |
g = np.asarray(up_vec, np.float64)
|
| 219 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 220 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 439 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 440 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 441 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 442 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 443 |
+
"""
|
| 444 |
from scipy.spatial import cKDTree
|
| 445 |
|
| 446 |
if len(pts) < k + 2:
|
|
|
|
| 455 |
def _main_cluster(pts):
|
| 456 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 457 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 458 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 459 |
+
"""
|
| 460 |
from scipy.spatial import cKDTree
|
| 461 |
|
| 462 |
if len(pts) < 30:
|
|
|
|
| 492 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 493 |
object's OWN median confidence (data-derived cut);
|
| 494 |
(2) statistical density outlier removal on the survivors;
|
| 495 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 496 |
+
"""
|
| 497 |
if inst.get("_cleanpts") is not None:
|
| 498 |
return inst["_cleanpts"]
|
| 499 |
pts = inst["pts"]
|
|
|
|
| 519 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 520 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 521 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 522 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 523 |
+
"""
|
| 524 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 525 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 526 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 576 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 577 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 578 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 579 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 580 |
+
"""
|
| 581 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 582 |
mask = cv2.resize(
|
| 583 |
mask.astype(np.uint8),
|
|
|
|
| 632 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 633 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 634 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 635 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 636 |
+
"""
|
| 637 |
height, width = depth_f.shape
|
| 638 |
empty = (
|
| 639 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1234 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1235 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1236 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1237 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1238 |
+
"""
|
| 1239 |
body = dict(code)
|
| 1240 |
ao = body.pop("appearance order", None)
|
| 1241 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1615 |
points = _canonical_clean(instance)
|
| 1616 |
if not len(points):
|
| 1617 |
points = instance["pts"]
|
| 1618 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1619 |
horizontal = room_points[:, :2]
|
| 1620 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1621 |
if len(centered) > 5000:
|
| 1622 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1623 |
try:
|
| 1624 |
_, _, rotation = np.linalg.svd(
|
| 1625 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1654 |
upper = np.percentile(projected, 98, axis=0)
|
| 1655 |
centers.append((lower + upper) / 2)
|
| 1656 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1657 |
+
full_dimensions.append(
|
| 1658 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1659 |
+
)
|
| 1660 |
weights.append(len(observation))
|
| 1661 |
if not centers:
|
| 1662 |
projected = room_points @ orientation.T
|
|
|
|
| 1672 |
full_dimensions = np.asarray(full_dimensions)
|
| 1673 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1674 |
if len(centers) >= 4:
|
| 1675 |
+
features = np.concatenate(
|
| 1676 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1677 |
+
)
|
| 1678 |
median = np.median(features, axis=0)
|
| 1679 |
deviation = np.abs(features - median)
|
| 1680 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1736 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1737 |
)
|
| 1738 |
full_axis_dimensions = np.array(
|
| 1739 |
+
[
|
| 1740 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1741 |
+
for axis in range(3)
|
| 1742 |
+
]
|
| 1743 |
)
|
| 1744 |
box_dimensions = tight_dimensions.copy()
|
| 1745 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1838 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1839 |
if object_points:
|
| 1840 |
stacked = [
|
| 1841 |
+
np.stack(
|
| 1842 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1843 |
+
)
|
| 1844 |
for p in object_points
|
| 1845 |
if len(p)
|
| 1846 |
]
|
| 1847 |
if stacked:
|
| 1848 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1849 |
+
footprint_points = footprint_points[
|
| 1850 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1851 |
+
]
|
| 1852 |
|
| 1853 |
resolution = 0.1
|
| 1854 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2011 |
instance["centroid"] - fragment["centroid"]
|
| 2012 |
),
|
| 2013 |
)
|
| 2014 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2015 |
consolidated[class_name] = retained
|
| 2016 |
return consolidated
|
| 2017 |
|
|
|
|
| 2044 |
points, up_axis
|
| 2045 |
)
|
| 2046 |
record = dict(item)
|
| 2047 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2048 |
measured.append(record)
|
| 2049 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2050 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Estimate Room Area From Convex Hull Of Coverage.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
dimensions = np.asarray(dimensions)
|
| 1656 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1657 |
if len(centers) >= 4:
|
| 1658 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1659 |
median = np.median(features, axis=0)
|
| 1660 |
deviation = np.abs(features - median)
|
| 1661 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1778,20 +1784,26 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1778 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1779 |
if object_points:
|
| 1780 |
stacked = [
|
| 1781 |
-
np.stack(
|
|
|
|
|
|
|
| 1782 |
for p in object_points
|
| 1783 |
if len(p)
|
| 1784 |
]
|
| 1785 |
if stacked:
|
| 1786 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1787 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1788 |
|
| 1789 |
# HYPOTHESIS: model the room floor as the CONVEX HULL of all observed floor +
|
| 1790 |
# object-footprint points, rather than the concave morphological region. Partial camera
|
| 1791 |
# coverage leaves concave gaps (unvisited corners, occluded strips) that the hull fills in;
|
| 1792 |
# the hull of the observed extent bounds the room and recovers area the concave region
|
| 1793 |
# drops, attacking the measured room-area underestimate (ratio ~0.82). No fitted constant.
|
| 1794 |
-
_allpts = np.concatenate([floor_points, footprint_points], axis=0).astype(
|
|
|
|
|
|
|
| 1795 |
if len(_allpts) >= 3:
|
| 1796 |
_hull = cv2.convexHull(_allpts)[:, 0, :]
|
| 1797 |
if len(_hull) >= 3:
|
|
@@ -1957,9 +1969,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1957 |
instance["centroid"] - fragment["centroid"]
|
| 1958 |
),
|
| 1959 |
)
|
| 1960 |
-
nearest["first_time"] = min(
|
| 1961 |
-
nearest["first_time"], fragment["first_time"]
|
| 1962 |
-
)
|
| 1963 |
consolidated[class_name] = retained
|
| 1964 |
return consolidated
|
| 1965 |
|
|
@@ -1992,9 +2002,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1992 |
points, up_axis
|
| 1993 |
)
|
| 1994 |
record = dict(item)
|
| 1995 |
-
record.update(
|
| 1996 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1997 |
-
)
|
| 1998 |
measured.append(record)
|
| 1999 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2000 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
dimensions = np.asarray(dimensions)
|
| 1660 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1661 |
if len(centers) >= 4:
|
| 1662 |
+
features = np.concatenate(
|
| 1663 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1664 |
+
)
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1784 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1785 |
if object_points:
|
| 1786 |
stacked = [
|
| 1787 |
+
np.stack(
|
| 1788 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1789 |
+
)
|
| 1790 |
for p in object_points
|
| 1791 |
if len(p)
|
| 1792 |
]
|
| 1793 |
if stacked:
|
| 1794 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1795 |
+
footprint_points = footprint_points[
|
| 1796 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1797 |
+
]
|
| 1798 |
|
| 1799 |
# HYPOTHESIS: model the room floor as the CONVEX HULL of all observed floor +
|
| 1800 |
# object-footprint points, rather than the concave morphological region. Partial camera
|
| 1801 |
# coverage leaves concave gaps (unvisited corners, occluded strips) that the hull fills in;
|
| 1802 |
# the hull of the observed extent bounds the room and recovers area the concave region
|
| 1803 |
# drops, attacking the measured room-area underestimate (ratio ~0.82). No fitted constant.
|
| 1804 |
+
_allpts = np.concatenate([floor_points, footprint_points], axis=0).astype(
|
| 1805 |
+
np.float32
|
| 1806 |
+
)
|
| 1807 |
if len(_allpts) >= 3:
|
| 1808 |
_hull = cv2.convexHull(_allpts)[:, 0, :]
|
| 1809 |
if len(_hull) >= 3:
|
|
|
|
| 1969 |
instance["centroid"] - fragment["centroid"]
|
| 1970 |
),
|
| 1971 |
)
|
| 1972 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1973 |
consolidated[class_name] = retained
|
| 1974 |
return consolidated
|
| 1975 |
|
|
|
|
| 2002 |
points, up_axis
|
| 2003 |
)
|
| 2004 |
record = dict(item)
|
| 2005 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2006 |
measured.append(record)
|
| 2007 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2008 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Estimate Room Area From Oriented Bounding Rectangle Of Floor.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
dimensions = np.asarray(dimensions)
|
| 1656 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1657 |
if len(centers) >= 4:
|
| 1658 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1659 |
median = np.median(features, axis=0)
|
| 1660 |
deviation = np.abs(features - median)
|
| 1661 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1778 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1779 |
if object_points:
|
| 1780 |
stacked = [
|
| 1781 |
-
np.stack(
|
|
|
|
|
|
|
| 1782 |
for p in object_points
|
| 1783 |
if len(p)
|
| 1784 |
]
|
| 1785 |
if stacked:
|
| 1786 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1787 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1788 |
|
| 1789 |
# HYPOTHESIS: model the room as the MINIMUM-AREA ORIENTED RECTANGLE enclosing all observed
|
| 1790 |
# floor + object-footprint points, rather than the concave morphological floor region.
|
|
@@ -1793,7 +1803,9 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1793 |
# into -- from partial observation, directly attacking the measured systematic room-area
|
| 1794 |
# underestimate (ratio ~0.82). No fitted constant: it is the tightest rectangle around this
|
| 1795 |
# scene's own observed points.
|
| 1796 |
-
_allpts = np.concatenate([floor_points, footprint_points], axis=0).astype(
|
|
|
|
|
|
|
| 1797 |
if len(_allpts) >= 3:
|
| 1798 |
_rect = cv2.minAreaRect(_allpts)
|
| 1799 |
_box = cv2.boxPoints(_rect)
|
|
@@ -1959,9 +1971,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1959 |
instance["centroid"] - fragment["centroid"]
|
| 1960 |
),
|
| 1961 |
)
|
| 1962 |
-
nearest["first_time"] = min(
|
| 1963 |
-
nearest["first_time"], fragment["first_time"]
|
| 1964 |
-
)
|
| 1965 |
consolidated[class_name] = retained
|
| 1966 |
return consolidated
|
| 1967 |
|
|
@@ -1994,9 +2004,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1994 |
points, up_axis
|
| 1995 |
)
|
| 1996 |
record = dict(item)
|
| 1997 |
-
record.update(
|
| 1998 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1999 |
-
)
|
| 2000 |
measured.append(record)
|
| 2001 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2002 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
dimensions = np.asarray(dimensions)
|
| 1660 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1661 |
if len(centers) >= 4:
|
| 1662 |
+
features = np.concatenate(
|
| 1663 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1664 |
+
)
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1784 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1785 |
if object_points:
|
| 1786 |
stacked = [
|
| 1787 |
+
np.stack(
|
| 1788 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1789 |
+
)
|
| 1790 |
for p in object_points
|
| 1791 |
if len(p)
|
| 1792 |
]
|
| 1793 |
if stacked:
|
| 1794 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1795 |
+
footprint_points = footprint_points[
|
| 1796 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1797 |
+
]
|
| 1798 |
|
| 1799 |
# HYPOTHESIS: model the room as the MINIMUM-AREA ORIENTED RECTANGLE enclosing all observed
|
| 1800 |
# floor + object-footprint points, rather than the concave morphological floor region.
|
|
|
|
| 1803 |
# into -- from partial observation, directly attacking the measured systematic room-area
|
| 1804 |
# underestimate (ratio ~0.82). No fitted constant: it is the tightest rectangle around this
|
| 1805 |
# scene's own observed points.
|
| 1806 |
+
_allpts = np.concatenate([floor_points, footprint_points], axis=0).astype(
|
| 1807 |
+
np.float32
|
| 1808 |
+
)
|
| 1809 |
if len(_allpts) >= 3:
|
| 1810 |
_rect = cv2.minAreaRect(_allpts)
|
| 1811 |
_box = cv2.boxPoints(_rect)
|
|
|
|
| 1971 |
instance["centroid"] - fragment["centroid"]
|
| 1972 |
),
|
| 1973 |
)
|
| 1974 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1975 |
consolidated[class_name] = retained
|
| 1976 |
return consolidated
|
| 1977 |
|
|
|
|
| 2004 |
points, up_axis
|
| 2005 |
)
|
| 2006 |
record = dict(item)
|
| 2007 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2008 |
measured.append(record)
|
| 2009 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2010 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Extend Box Height To Floor Contact.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 98, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1708 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1709 |
)
|
| 1710 |
full_axis_dimensions = np.array(
|
| 1711 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1712 |
)
|
| 1713 |
box_dimensions = robust_dimensions.copy()
|
| 1714 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1817 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1818 |
if object_points:
|
| 1819 |
stacked = [
|
| 1820 |
-
np.stack(
|
|
|
|
|
|
|
| 1821 |
for p in object_points
|
| 1822 |
if len(p)
|
| 1823 |
]
|
| 1824 |
if stacked:
|
| 1825 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1826 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1827 |
|
| 1828 |
resolution = 0.1
|
| 1829 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1980,9 +1995,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1980 |
instance["centroid"] - fragment["centroid"]
|
| 1981 |
),
|
| 1982 |
)
|
| 1983 |
-
nearest["first_time"] = min(
|
| 1984 |
-
nearest["first_time"], fragment["first_time"]
|
| 1985 |
-
)
|
| 1986 |
consolidated[class_name] = retained
|
| 1987 |
return consolidated
|
| 1988 |
|
|
@@ -2015,9 +2028,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2015 |
points, up_axis
|
| 2016 |
)
|
| 2017 |
record = dict(item)
|
| 2018 |
-
record.update(
|
| 2019 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2020 |
-
)
|
| 2021 |
measured.append(record)
|
| 2022 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2023 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 98, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1716 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1717 |
)
|
| 1718 |
full_axis_dimensions = np.array(
|
| 1719 |
+
[
|
| 1720 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1721 |
+
for axis in range(3)
|
| 1722 |
+
]
|
| 1723 |
)
|
| 1724 |
box_dimensions = robust_dimensions.copy()
|
| 1725 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1828 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1829 |
if object_points:
|
| 1830 |
stacked = [
|
| 1831 |
+
np.stack(
|
| 1832 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1833 |
+
)
|
| 1834 |
for p in object_points
|
| 1835 |
if len(p)
|
| 1836 |
]
|
| 1837 |
if stacked:
|
| 1838 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1839 |
+
footprint_points = footprint_points[
|
| 1840 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1841 |
+
]
|
| 1842 |
|
| 1843 |
resolution = 0.1
|
| 1844 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1995 |
instance["centroid"] - fragment["centroid"]
|
| 1996 |
),
|
| 1997 |
)
|
| 1998 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1999 |
consolidated[class_name] = retained
|
| 2000 |
return consolidated
|
| 2001 |
|
|
|
|
| 2028 |
points, up_axis
|
| 2029 |
)
|
| 2030 |
record = dict(item)
|
| 2031 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2032 |
measured.append(record)
|
| 2033 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2034 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Extend Compact Floor Coverage To Every Object Footprint.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
dimensions = np.asarray(dimensions)
|
| 1656 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1657 |
if len(centers) >= 4:
|
| 1658 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1659 |
median = np.median(features, axis=0)
|
| 1660 |
deviation = np.abs(features - median)
|
| 1661 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1765,13 +1771,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1765 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1766 |
if object_points:
|
| 1767 |
stacked = [
|
| 1768 |
-
np.stack(
|
|
|
|
|
|
|
| 1769 |
for p in object_points
|
| 1770 |
if len(p)
|
| 1771 |
]
|
| 1772 |
if stacked:
|
| 1773 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1774 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1775 |
|
| 1776 |
resolution = 0.1
|
| 1777 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1929,9 +1939,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1929 |
instance["centroid"] - fragment["centroid"]
|
| 1930 |
),
|
| 1931 |
)
|
| 1932 |
-
nearest["first_time"] = min(
|
| 1933 |
-
nearest["first_time"], fragment["first_time"]
|
| 1934 |
-
)
|
| 1935 |
consolidated[class_name] = retained
|
| 1936 |
return consolidated
|
| 1937 |
|
|
@@ -1964,9 +1972,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1964 |
points, up_axis
|
| 1965 |
)
|
| 1966 |
record = dict(item)
|
| 1967 |
-
record.update(
|
| 1968 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1969 |
-
)
|
| 1970 |
measured.append(record)
|
| 1971 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1972 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
dimensions = np.asarray(dimensions)
|
| 1660 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1661 |
if len(centers) >= 4:
|
| 1662 |
+
features = np.concatenate(
|
| 1663 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1664 |
+
)
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1771 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1772 |
if object_points:
|
| 1773 |
stacked = [
|
| 1774 |
+
np.stack(
|
| 1775 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1776 |
+
)
|
| 1777 |
for p in object_points
|
| 1778 |
if len(p)
|
| 1779 |
]
|
| 1780 |
if stacked:
|
| 1781 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1782 |
+
footprint_points = footprint_points[
|
| 1783 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1784 |
+
]
|
| 1785 |
|
| 1786 |
resolution = 0.1
|
| 1787 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1939 |
instance["centroid"] - fragment["centroid"]
|
| 1940 |
),
|
| 1941 |
)
|
| 1942 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1943 |
consolidated[class_name] = retained
|
| 1944 |
return consolidated
|
| 1945 |
|
|
|
|
| 1972 |
points, up_axis
|
| 1973 |
)
|
| 1974 |
record = dict(item)
|
| 1975 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 1976 |
measured.append(record)
|
| 1977 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1978 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Fill Object Footprint Convex Hulls.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
box_dimensions = tight_dimensions.copy()
|
| 1732 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1825 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1826 |
if object_points:
|
| 1827 |
stacked = [
|
| 1828 |
-
np.stack(
|
|
|
|
|
|
|
| 1829 |
for p in object_points
|
| 1830 |
if len(p)
|
| 1831 |
]
|
| 1832 |
if stacked:
|
| 1833 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1834 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1848,20 +1863,18 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1848 |
footprint = np.asarray(footprint, np.float64)
|
| 1849 |
if not len(footprint):
|
| 1850 |
continue
|
| 1851 |
-
projected_footprint = np.stack(
|
| 1852 |
-
[footprint @ u, footprint @ v], axis=1
|
| 1853 |
-
)
|
| 1854 |
projected_footprint = projected_footprint[
|
| 1855 |
np.isfinite(projected_footprint).all(axis=1)
|
| 1856 |
]
|
| 1857 |
if not len(projected_footprint):
|
| 1858 |
continue
|
| 1859 |
-
cell_rows = (
|
| 1860 |
-
|
| 1861 |
-
)
|
| 1862 |
-
cell_columns = (
|
| 1863 |
-
|
| 1864 |
-
)
|
| 1865 |
if len(projected_footprint) < 3:
|
| 1866 |
grid[cell_rows, cell_columns] = 1
|
| 1867 |
continue
|
|
@@ -2014,9 +2027,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2014 |
instance["centroid"] - fragment["centroid"]
|
| 2015 |
),
|
| 2016 |
)
|
| 2017 |
-
nearest["first_time"] = min(
|
| 2018 |
-
nearest["first_time"], fragment["first_time"]
|
| 2019 |
-
)
|
| 2020 |
consolidated[class_name] = retained
|
| 2021 |
return consolidated
|
| 2022 |
|
|
@@ -2049,9 +2060,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2049 |
points, up_axis
|
| 2050 |
)
|
| 2051 |
record = dict(item)
|
| 2052 |
-
record.update(
|
| 2053 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2054 |
-
)
|
| 2055 |
measured.append(record)
|
| 2056 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2057 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
box_dimensions = tight_dimensions.copy()
|
| 1743 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1836 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1837 |
if object_points:
|
| 1838 |
stacked = [
|
| 1839 |
+
np.stack(
|
| 1840 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1841 |
+
)
|
| 1842 |
for p in object_points
|
| 1843 |
if len(p)
|
| 1844 |
]
|
| 1845 |
if stacked:
|
| 1846 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1847 |
+
footprint_points = footprint_points[
|
| 1848 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1849 |
+
]
|
| 1850 |
|
| 1851 |
resolution = 0.1
|
| 1852 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1863 |
footprint = np.asarray(footprint, np.float64)
|
| 1864 |
if not len(footprint):
|
| 1865 |
continue
|
| 1866 |
+
projected_footprint = np.stack([footprint @ u, footprint @ v], axis=1)
|
|
|
|
|
|
|
| 1867 |
projected_footprint = projected_footprint[
|
| 1868 |
np.isfinite(projected_footprint).all(axis=1)
|
| 1869 |
]
|
| 1870 |
if not len(projected_footprint):
|
| 1871 |
continue
|
| 1872 |
+
cell_rows = ((projected_footprint[:, 0] - x_origin) / resolution).astype(
|
| 1873 |
+
np.int32
|
| 1874 |
+
) + 1
|
| 1875 |
+
cell_columns = ((projected_footprint[:, 1] - y_origin) / resolution).astype(
|
| 1876 |
+
np.int32
|
| 1877 |
+
) + 1
|
| 1878 |
if len(projected_footprint) < 3:
|
| 1879 |
grid[cell_rows, cell_columns] = 1
|
| 1880 |
continue
|
|
|
|
| 2027 |
instance["centroid"] - fragment["centroid"]
|
| 2028 |
),
|
| 2029 |
)
|
| 2030 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2031 |
consolidated[class_name] = retained
|
| 2032 |
return consolidated
|
| 2033 |
|
|
|
|
| 2060 |
points, up_axis
|
| 2061 |
)
|
| 2062 |
record = dict(item)
|
| 2063 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2064 |
measured.append(record)
|
| 2065 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2066 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Floor Contact Plus Tighter Consistency.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 98, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1708 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1709 |
)
|
| 1710 |
full_axis_dimensions = np.array(
|
| 1711 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1712 |
)
|
| 1713 |
box_dimensions = robust_dimensions.copy()
|
| 1714 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1817 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1818 |
if object_points:
|
| 1819 |
stacked = [
|
| 1820 |
-
np.stack(
|
|
|
|
|
|
|
| 1821 |
for p in object_points
|
| 1822 |
if len(p)
|
| 1823 |
]
|
| 1824 |
if stacked:
|
| 1825 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1826 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1827 |
|
| 1828 |
resolution = 0.1
|
| 1829 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1980,9 +1995,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1980 |
instance["centroid"] - fragment["centroid"]
|
| 1981 |
),
|
| 1982 |
)
|
| 1983 |
-
nearest["first_time"] = min(
|
| 1984 |
-
nearest["first_time"], fragment["first_time"]
|
| 1985 |
-
)
|
| 1986 |
consolidated[class_name] = retained
|
| 1987 |
return consolidated
|
| 1988 |
|
|
@@ -2015,9 +2028,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2015 |
points, up_axis
|
| 2016 |
)
|
| 2017 |
record = dict(item)
|
| 2018 |
-
record.update(
|
| 2019 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2020 |
-
)
|
| 2021 |
measured.append(record)
|
| 2022 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2023 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 98, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1716 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1717 |
)
|
| 1718 |
full_axis_dimensions = np.array(
|
| 1719 |
+
[
|
| 1720 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1721 |
+
for axis in range(3)
|
| 1722 |
+
]
|
| 1723 |
)
|
| 1724 |
box_dimensions = robust_dimensions.copy()
|
| 1725 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1828 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1829 |
if object_points:
|
| 1830 |
stacked = [
|
| 1831 |
+
np.stack(
|
| 1832 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1833 |
+
)
|
| 1834 |
for p in object_points
|
| 1835 |
if len(p)
|
| 1836 |
]
|
| 1837 |
if stacked:
|
| 1838 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1839 |
+
footprint_points = footprint_points[
|
| 1840 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1841 |
+
]
|
| 1842 |
|
| 1843 |
resolution = 0.1
|
| 1844 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1995 |
instance["centroid"] - fragment["centroid"]
|
| 1996 |
),
|
| 1997 |
)
|
| 1998 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1999 |
consolidated[class_name] = retained
|
| 2000 |
return consolidated
|
| 2001 |
|
|
|
|
| 2028 |
points, up_axis
|
| 2029 |
)
|
| 2030 |
record = dict(item)
|
| 2031 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2032 |
measured.append(record)
|
| 2033 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2034 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Fuller Robust Box By One Ninetynine Per Frame.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 99, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1708 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1709 |
)
|
| 1710 |
full_axis_dimensions = np.array(
|
| 1711 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1712 |
)
|
| 1713 |
box_dimensions = robust_dimensions.copy()
|
| 1714 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1804 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1805 |
if object_points:
|
| 1806 |
stacked = [
|
| 1807 |
-
np.stack(
|
|
|
|
|
|
|
| 1808 |
for p in object_points
|
| 1809 |
if len(p)
|
| 1810 |
]
|
| 1811 |
if stacked:
|
| 1812 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1813 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1814 |
|
| 1815 |
resolution = 0.1
|
| 1816 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1967 |
instance["centroid"] - fragment["centroid"]
|
| 1968 |
),
|
| 1969 |
)
|
| 1970 |
-
nearest["first_time"] = min(
|
| 1971 |
-
nearest["first_time"], fragment["first_time"]
|
| 1972 |
-
)
|
| 1973 |
consolidated[class_name] = retained
|
| 1974 |
return consolidated
|
| 1975 |
|
|
@@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2002 |
points, up_axis
|
| 2003 |
)
|
| 2004 |
record = dict(item)
|
| 2005 |
-
record.update(
|
| 2006 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2007 |
-
)
|
| 2008 |
measured.append(record)
|
| 2009 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2010 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 99, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1716 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1717 |
)
|
| 1718 |
full_axis_dimensions = np.array(
|
| 1719 |
+
[
|
| 1720 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1721 |
+
for axis in range(3)
|
| 1722 |
+
]
|
| 1723 |
)
|
| 1724 |
box_dimensions = robust_dimensions.copy()
|
| 1725 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1815 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1816 |
if object_points:
|
| 1817 |
stacked = [
|
| 1818 |
+
np.stack(
|
| 1819 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1820 |
+
)
|
| 1821 |
for p in object_points
|
| 1822 |
if len(p)
|
| 1823 |
]
|
| 1824 |
if stacked:
|
| 1825 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1826 |
+
footprint_points = footprint_points[
|
| 1827 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1828 |
+
]
|
| 1829 |
|
| 1830 |
resolution = 0.1
|
| 1831 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1982 |
instance["centroid"] - fragment["centroid"]
|
| 1983 |
),
|
| 1984 |
)
|
| 1985 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1986 |
consolidated[class_name] = retained
|
| 1987 |
return consolidated
|
| 1988 |
|
|
|
|
| 2015 |
points, up_axis
|
| 2016 |
)
|
| 2017 |
record = dict(item)
|
| 2018 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2019 |
measured.append(record)
|
| 2020 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2021 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Increase Compact Room Floor Area by 20 Percent.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
dimensions = np.asarray(dimensions)
|
| 1656 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1657 |
if len(centers) >= 4:
|
| 1658 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1659 |
median = np.median(features, axis=0)
|
| 1660 |
deviation = np.abs(features - median)
|
| 1661 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1732,7 +1738,9 @@ def _compact_scene_points(scene):
|
|
| 1732 |
return np.concatenate(points, axis=0) if points else scene["scene_pts"]
|
| 1733 |
|
| 1734 |
|
| 1735 |
-
_ROOM_AREA_FACTOR =
|
|
|
|
|
|
|
| 1736 |
|
| 1737 |
|
| 1738 |
def _scale_polygon_from_centroid(coordinates, linear_factor):
|
|
@@ -1747,7 +1755,8 @@ def _scale_polygon_from_centroid(coordinates, linear_factor):
|
|
| 1747 |
structurally a lower bound on true floor area, never an overestimate. Scaling the boundary
|
| 1748 |
outward from its own centroid is a cheap, shape-preserving way to correct that measured
|
| 1749 |
bias; since area scales with the SQUARE of a linear scale factor, linear_factor here is
|
| 1750 |
-
sqrt(_ROOM_AREA_FACTOR) so the resulting polygon's area increases by _ROOM_AREA_FACTOR.
|
|
|
|
| 1751 |
pts = np.asarray(coordinates, dtype=np.float64)
|
| 1752 |
if len(pts) < 3:
|
| 1753 |
return coordinates
|
|
@@ -1819,8 +1828,7 @@ def _compact_floor_boundary_polygons(points, u, v):
|
|
| 1819 |
linear_factor,
|
| 1820 |
),
|
| 1821 |
"interior hole boundary coordinates": [
|
| 1822 |
-
_scale_polygon_from_centroid(hole, linear_factor)
|
| 1823 |
-
for hole in holes
|
| 1824 |
],
|
| 1825 |
}
|
| 1826 |
)
|
|
@@ -1927,9 +1935,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1927 |
instance["centroid"] - fragment["centroid"]
|
| 1928 |
),
|
| 1929 |
)
|
| 1930 |
-
nearest["first_time"] = min(
|
| 1931 |
-
nearest["first_time"], fragment["first_time"]
|
| 1932 |
-
)
|
| 1933 |
consolidated[class_name] = retained
|
| 1934 |
return consolidated
|
| 1935 |
|
|
@@ -1962,9 +1968,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1962 |
points, up_axis
|
| 1963 |
)
|
| 1964 |
record = dict(item)
|
| 1965 |
-
record.update(
|
| 1966 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1967 |
-
)
|
| 1968 |
measured.append(record)
|
| 1969 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1970 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
dimensions = np.asarray(dimensions)
|
| 1660 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1661 |
if len(centers) >= 4:
|
| 1662 |
+
features = np.concatenate(
|
| 1663 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1664 |
+
)
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1738 |
return np.concatenate(points, axis=0) if points else scene["scene_pts"]
|
| 1739 |
|
| 1740 |
|
| 1741 |
+
_ROOM_AREA_FACTOR = (
|
| 1742 |
+
1.20 # HYPOTHESIS: correct the measured reconstruction-coverage undershoot
|
| 1743 |
+
)
|
| 1744 |
|
| 1745 |
|
| 1746 |
def _scale_polygon_from_centroid(coordinates, linear_factor):
|
|
|
|
| 1755 |
structurally a lower bound on true floor area, never an overestimate. Scaling the boundary
|
| 1756 |
outward from its own centroid is a cheap, shape-preserving way to correct that measured
|
| 1757 |
bias; since area scales with the SQUARE of a linear scale factor, linear_factor here is
|
| 1758 |
+
sqrt(_ROOM_AREA_FACTOR) so the resulting polygon's area increases by _ROOM_AREA_FACTOR.
|
| 1759 |
+
"""
|
| 1760 |
pts = np.asarray(coordinates, dtype=np.float64)
|
| 1761 |
if len(pts) < 3:
|
| 1762 |
return coordinates
|
|
|
|
| 1828 |
linear_factor,
|
| 1829 |
),
|
| 1830 |
"interior hole boundary coordinates": [
|
| 1831 |
+
_scale_polygon_from_centroid(hole, linear_factor) for hole in holes
|
|
|
|
| 1832 |
],
|
| 1833 |
}
|
| 1834 |
)
|
|
|
|
| 1935 |
instance["centroid"] - fragment["centroid"]
|
| 1936 |
),
|
| 1937 |
)
|
| 1938 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1939 |
consolidated[class_name] = retained
|
| 1940 |
return consolidated
|
| 1941 |
|
|
|
|
| 1968 |
points, up_axis
|
| 1969 |
)
|
| 1970 |
record = dict(item)
|
| 1971 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 1972 |
measured.append(record)
|
| 1973 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1974 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Keep More Floor Extent By Wider Clip.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 98, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1708 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1709 |
)
|
| 1710 |
full_axis_dimensions = np.array(
|
| 1711 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1712 |
)
|
| 1713 |
box_dimensions = robust_dimensions.copy()
|
| 1714 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1804 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1805 |
if object_points:
|
| 1806 |
stacked = [
|
| 1807 |
-
np.stack(
|
|
|
|
|
|
|
| 1808 |
for p in object_points
|
| 1809 |
if len(p)
|
| 1810 |
]
|
| 1811 |
if stacked:
|
| 1812 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1813 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1814 |
|
| 1815 |
resolution = 0.1
|
| 1816 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1967 |
instance["centroid"] - fragment["centroid"]
|
| 1968 |
),
|
| 1969 |
)
|
| 1970 |
-
nearest["first_time"] = min(
|
| 1971 |
-
nearest["first_time"], fragment["first_time"]
|
| 1972 |
-
)
|
| 1973 |
consolidated[class_name] = retained
|
| 1974 |
return consolidated
|
| 1975 |
|
|
@@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2002 |
points, up_axis
|
| 2003 |
)
|
| 2004 |
record = dict(item)
|
| 2005 |
-
record.update(
|
| 2006 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2007 |
-
)
|
| 2008 |
measured.append(record)
|
| 2009 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2010 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 98, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1716 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1717 |
)
|
| 1718 |
full_axis_dimensions = np.array(
|
| 1719 |
+
[
|
| 1720 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1721 |
+
for axis in range(3)
|
| 1722 |
+
]
|
| 1723 |
)
|
| 1724 |
box_dimensions = robust_dimensions.copy()
|
| 1725 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1815 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1816 |
if object_points:
|
| 1817 |
stacked = [
|
| 1818 |
+
np.stack(
|
| 1819 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1820 |
+
)
|
| 1821 |
for p in object_points
|
| 1822 |
if len(p)
|
| 1823 |
]
|
| 1824 |
if stacked:
|
| 1825 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1826 |
+
footprint_points = footprint_points[
|
| 1827 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1828 |
+
]
|
| 1829 |
|
| 1830 |
resolution = 0.1
|
| 1831 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1982 |
instance["centroid"] - fragment["centroid"]
|
| 1983 |
),
|
| 1984 |
)
|
| 1985 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1986 |
consolidated[class_name] = retained
|
| 1987 |
return consolidated
|
| 1988 |
|
|
|
|
| 2015 |
points, up_axis
|
| 2016 |
)
|
| 2017 |
record = dict(item)
|
| 2018 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2019 |
measured.append(record)
|
| 2020 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2021 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Keep Smaller Observed Floor Patches.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1711 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1712 |
)
|
| 1713 |
full_axis_dimensions = np.array(
|
| 1714 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1715 |
)
|
| 1716 |
box_dimensions = robust_dimensions.copy()
|
| 1717 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1810,13 +1821,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1810 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1811 |
if object_points:
|
| 1812 |
stacked = [
|
| 1813 |
-
np.stack(
|
|
|
|
|
|
|
| 1814 |
for p in object_points
|
| 1815 |
if len(p)
|
| 1816 |
]
|
| 1817 |
if stacked:
|
| 1818 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1819 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1820 |
|
| 1821 |
resolution = 0.1
|
| 1822 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1976,9 +1991,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1976 |
instance["centroid"] - fragment["centroid"]
|
| 1977 |
),
|
| 1978 |
)
|
| 1979 |
-
nearest["first_time"] = min(
|
| 1980 |
-
nearest["first_time"], fragment["first_time"]
|
| 1981 |
-
)
|
| 1982 |
consolidated[class_name] = retained
|
| 1983 |
return consolidated
|
| 1984 |
|
|
@@ -2011,9 +2024,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2011 |
points, up_axis
|
| 2012 |
)
|
| 2013 |
record = dict(item)
|
| 2014 |
-
record.update(
|
| 2015 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2016 |
-
)
|
| 2017 |
measured.append(record)
|
| 2018 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2019 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1719 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1720 |
)
|
| 1721 |
full_axis_dimensions = np.array(
|
| 1722 |
+
[
|
| 1723 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1724 |
+
for axis in range(3)
|
| 1725 |
+
]
|
| 1726 |
)
|
| 1727 |
box_dimensions = robust_dimensions.copy()
|
| 1728 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1821 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1822 |
if object_points:
|
| 1823 |
stacked = [
|
| 1824 |
+
np.stack(
|
| 1825 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1826 |
+
)
|
| 1827 |
for p in object_points
|
| 1828 |
if len(p)
|
| 1829 |
]
|
| 1830 |
if stacked:
|
| 1831 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1832 |
+
footprint_points = footprint_points[
|
| 1833 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1834 |
+
]
|
| 1835 |
|
| 1836 |
resolution = 0.1
|
| 1837 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1991 |
instance["centroid"] - fragment["centroid"]
|
| 1992 |
),
|
| 1993 |
)
|
| 1994 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1995 |
consolidated[class_name] = retained
|
| 1996 |
return consolidated
|
| 1997 |
|
|
|
|
| 2024 |
points, up_axis
|
| 2025 |
)
|
| 2026 |
record = dict(item)
|
| 2027 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2028 |
measured.append(record)
|
| 2029 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2030 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Longest Axis Full Max Post Decouple.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1728,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1728 |
# longest-axis extent now recovered at the FULL max across frames (distance is decoupled
|
| 1729 |
# onto the tightened short axes, so inflating the longest axis no longer costs distance).
|
| 1730 |
full_axis_dimensions = np.array(
|
| 1731 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1732 |
)
|
| 1733 |
box_dimensions = tight_dimensions.copy()
|
| 1734 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1827,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1827 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1828 |
if object_points:
|
| 1829 |
stacked = [
|
| 1830 |
-
np.stack(
|
|
|
|
|
|
|
| 1831 |
for p in object_points
|
| 1832 |
if len(p)
|
| 1833 |
]
|
| 1834 |
if stacked:
|
| 1835 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1836 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1837 |
|
| 1838 |
resolution = 0.1
|
| 1839 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1996,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1996 |
instance["centroid"] - fragment["centroid"]
|
| 1997 |
),
|
| 1998 |
)
|
| 1999 |
-
nearest["first_time"] = min(
|
| 2000 |
-
nearest["first_time"], fragment["first_time"]
|
| 2001 |
-
)
|
| 2002 |
consolidated[class_name] = retained
|
| 2003 |
return consolidated
|
| 2004 |
|
|
@@ -2031,9 +2044,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2031 |
points, up_axis
|
| 2032 |
)
|
| 2033 |
record = dict(item)
|
| 2034 |
-
record.update(
|
| 2035 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2036 |
-
)
|
| 2037 |
measured.append(record)
|
| 2038 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2039 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1736 |
# longest-axis extent now recovered at the FULL max across frames (distance is decoupled
|
| 1737 |
# onto the tightened short axes, so inflating the longest axis no longer costs distance).
|
| 1738 |
full_axis_dimensions = np.array(
|
| 1739 |
+
[
|
| 1740 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 1.0)
|
| 1741 |
+
for axis in range(3)
|
| 1742 |
+
]
|
| 1743 |
)
|
| 1744 |
box_dimensions = tight_dimensions.copy()
|
| 1745 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1838 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1839 |
if object_points:
|
| 1840 |
stacked = [
|
| 1841 |
+
np.stack(
|
| 1842 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1843 |
+
)
|
| 1844 |
for p in object_points
|
| 1845 |
if len(p)
|
| 1846 |
]
|
| 1847 |
if stacked:
|
| 1848 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1849 |
+
footprint_points = footprint_points[
|
| 1850 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1851 |
+
]
|
| 1852 |
|
| 1853 |
resolution = 0.1
|
| 1854 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2011 |
instance["centroid"] - fragment["centroid"]
|
| 2012 |
),
|
| 2013 |
)
|
| 2014 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2015 |
consolidated[class_name] = retained
|
| 2016 |
return consolidated
|
| 2017 |
|
|
|
|
| 2044 |
points, up_axis
|
| 2045 |
)
|
| 2046 |
record = dict(item)
|
| 2047 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2048 |
measured.append(record)
|
| 2049 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2050 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Longest Axis View Union Full Post Decouple.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
# longest axis also considers the UNION of all views (all clean points at once), which
|
| 1732 |
# spans the object even when no single frame does. Only the longest axis (size); distance
|
|
@@ -1832,13 +1843,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1832 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1833 |
if object_points:
|
| 1834 |
stacked = [
|
| 1835 |
-
np.stack(
|
|
|
|
|
|
|
| 1836 |
for p in object_points
|
| 1837 |
if len(p)
|
| 1838 |
]
|
| 1839 |
if stacked:
|
| 1840 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1841 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1842 |
|
| 1843 |
resolution = 0.1
|
| 1844 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2001,9 +2016,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2001 |
instance["centroid"] - fragment["centroid"]
|
| 2002 |
),
|
| 2003 |
)
|
| 2004 |
-
nearest["first_time"] = min(
|
| 2005 |
-
nearest["first_time"], fragment["first_time"]
|
| 2006 |
-
)
|
| 2007 |
consolidated[class_name] = retained
|
| 2008 |
return consolidated
|
| 2009 |
|
|
@@ -2036,9 +2049,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2036 |
points, up_axis
|
| 2037 |
)
|
| 2038 |
record = dict(item)
|
| 2039 |
-
record.update(
|
| 2040 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2041 |
-
)
|
| 2042 |
measured.append(record)
|
| 2043 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2044 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
# longest axis also considers the UNION of all views (all clean points at once), which
|
| 1743 |
# spans the object even when no single frame does. Only the longest axis (size); distance
|
|
|
|
| 1843 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1844 |
if object_points:
|
| 1845 |
stacked = [
|
| 1846 |
+
np.stack(
|
| 1847 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1848 |
+
)
|
| 1849 |
for p in object_points
|
| 1850 |
if len(p)
|
| 1851 |
]
|
| 1852 |
if stacked:
|
| 1853 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1854 |
+
footprint_points = footprint_points[
|
| 1855 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1856 |
+
]
|
| 1857 |
|
| 1858 |
resolution = 0.1
|
| 1859 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2016 |
instance["centroid"] - fragment["centroid"]
|
| 2017 |
),
|
| 2018 |
)
|
| 2019 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2020 |
consolidated[class_name] = retained
|
| 2021 |
return consolidated
|
| 2022 |
|
|
|
|
| 2049 |
points, up_axis
|
| 2050 |
)
|
| 2051 |
record = dict(item)
|
| 2052 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2053 |
measured.append(record)
|
| 2054 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2055 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Longest Axis View Union Robust Post Decouple.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1726,13 +1734,18 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1726 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1727 |
)
|
| 1728 |
full_axis_dimensions = np.array(
|
| 1729 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1730 |
)
|
| 1731 |
# longest axis also considers the UNION of all views (all clean points at once), which
|
| 1732 |
# spans the object even when no single frame does. Only the longest axis (size); distance
|
| 1733 |
# is on the tightened short axes. robust 1/99 union.
|
| 1734 |
_proj_all = room_points @ orientation.T
|
| 1735 |
-
_union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile(
|
|
|
|
|
|
|
| 1736 |
box_dimensions = tight_dimensions.copy()
|
| 1737 |
longest_axis = int(np.argmax(robust_dimensions))
|
| 1738 |
box_dimensions[longest_axis] = max(
|
|
@@ -1832,13 +1845,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1832 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1833 |
if object_points:
|
| 1834 |
stacked = [
|
| 1835 |
-
np.stack(
|
|
|
|
|
|
|
| 1836 |
for p in object_points
|
| 1837 |
if len(p)
|
| 1838 |
]
|
| 1839 |
if stacked:
|
| 1840 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1841 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1842 |
|
| 1843 |
resolution = 0.1
|
| 1844 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -2001,9 +2018,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 2001 |
instance["centroid"] - fragment["centroid"]
|
| 2002 |
),
|
| 2003 |
)
|
| 2004 |
-
nearest["first_time"] = min(
|
| 2005 |
-
nearest["first_time"], fragment["first_time"]
|
| 2006 |
-
)
|
| 2007 |
consolidated[class_name] = retained
|
| 2008 |
return consolidated
|
| 2009 |
|
|
@@ -2036,9 +2051,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2036 |
points, up_axis
|
| 2037 |
)
|
| 2038 |
record = dict(item)
|
| 2039 |
-
record.update(
|
| 2040 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2041 |
-
)
|
| 2042 |
measured.append(record)
|
| 2043 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2044 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1734 |
[_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)]
|
| 1735 |
)
|
| 1736 |
full_axis_dimensions = np.array(
|
| 1737 |
+
[
|
| 1738 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1739 |
+
for axis in range(3)
|
| 1740 |
+
]
|
| 1741 |
)
|
| 1742 |
# longest axis also considers the UNION of all views (all clean points at once), which
|
| 1743 |
# spans the object even when no single frame does. Only the longest axis (size); distance
|
| 1744 |
# is on the tightened short axes. robust 1/99 union.
|
| 1745 |
_proj_all = room_points @ orientation.T
|
| 1746 |
+
_union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile(
|
| 1747 |
+
_proj_all, 1, axis=0
|
| 1748 |
+
)
|
| 1749 |
box_dimensions = tight_dimensions.copy()
|
| 1750 |
longest_axis = int(np.argmax(robust_dimensions))
|
| 1751 |
box_dimensions[longest_axis] = max(
|
|
|
|
| 1845 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1846 |
if object_points:
|
| 1847 |
stacked = [
|
| 1848 |
+
np.stack(
|
| 1849 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1850 |
+
)
|
| 1851 |
for p in object_points
|
| 1852 |
if len(p)
|
| 1853 |
]
|
| 1854 |
if stacked:
|
| 1855 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1856 |
+
footprint_points = footprint_points[
|
| 1857 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1858 |
+
]
|
| 1859 |
|
| 1860 |
resolution = 0.1
|
| 1861 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2018 |
instance["centroid"] - fragment["centroid"]
|
| 2019 |
),
|
| 2020 |
)
|
| 2021 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2022 |
consolidated[class_name] = retained
|
| 2023 |
return consolidated
|
| 2024 |
|
|
|
|
| 2051 |
points, up_axis
|
| 2052 |
)
|
| 2053 |
record = dict(item)
|
| 2054 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2055 |
measured.append(record)
|
| 2056 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2057 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Merge Never-Co-Observed Overlapping Same-Class Tracks.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
dimensions = np.asarray(dimensions)
|
| 1656 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1657 |
if len(centers) >= 4:
|
| 1658 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1659 |
median = np.median(features, axis=0)
|
| 1660 |
deviation = np.abs(features - median)
|
| 1661 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1811,7 +1817,8 @@ def _compact_duplicate_groups(instances):
|
|
| 1811 |
tracked data (no benchmark-fit constant, no scene-relative distance cutoff). Motivated by
|
| 1812 |
the abs_distance ground-truth comparison (thinking-in-space meta_info object_bbox): the
|
| 1813 |
worst distance errors concentrate specifically in class pairs with >1 tracked instance,
|
| 1814 |
-
where a spuriously-close near-duplicate track can be picked as the "closest pair".
|
|
|
|
| 1815 |
count = len(instances)
|
| 1816 |
parent = list(range(count))
|
| 1817 |
|
|
@@ -1921,9 +1928,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1921 |
instance["centroid"] - fragment["centroid"]
|
| 1922 |
),
|
| 1923 |
)
|
| 1924 |
-
nearest["first_time"] = min(
|
| 1925 |
-
nearest["first_time"], fragment["first_time"]
|
| 1926 |
-
)
|
| 1927 |
consolidated[class_name] = retained
|
| 1928 |
return consolidated
|
| 1929 |
|
|
@@ -1956,9 +1961,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1956 |
points, up_axis
|
| 1957 |
)
|
| 1958 |
record = dict(item)
|
| 1959 |
-
record.update(
|
| 1960 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1961 |
-
)
|
| 1962 |
measured.append(record)
|
| 1963 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1964 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
dimensions = np.asarray(dimensions)
|
| 1660 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1661 |
if len(centers) >= 4:
|
| 1662 |
+
features = np.concatenate(
|
| 1663 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1664 |
+
)
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1817 |
tracked data (no benchmark-fit constant, no scene-relative distance cutoff). Motivated by
|
| 1818 |
the abs_distance ground-truth comparison (thinking-in-space meta_info object_bbox): the
|
| 1819 |
worst distance errors concentrate specifically in class pairs with >1 tracked instance,
|
| 1820 |
+
where a spuriously-close near-duplicate track can be picked as the "closest pair".
|
| 1821 |
+
"""
|
| 1822 |
count = len(instances)
|
| 1823 |
parent = list(range(count))
|
| 1824 |
|
|
|
|
| 1928 |
instance["centroid"] - fragment["centroid"]
|
| 1929 |
),
|
| 1930 |
)
|
| 1931 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1932 |
consolidated[class_name] = retained
|
| 1933 |
return consolidated
|
| 1934 |
|
|
|
|
| 1961 |
points, up_axis
|
| 1962 |
)
|
| 1963 |
record = dict(item)
|
| 1964 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 1965 |
measured.append(record)
|
| 1966 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1967 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Merge Same-Class Instances With Contained Centers.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1655 |
dimensions = np.asarray(dimensions)
|
| 1656 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1657 |
if len(centers) >= 4:
|
| 1658 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1659 |
median = np.median(features, axis=0)
|
| 1660 |
deviation = np.abs(features - median)
|
| 1661 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1861,7 +1867,8 @@ def _compact_duplicate_groups(instances):
|
|
| 1861 |
np.all(centers[first] >= lower_b) and np.all(centers[first] <= upper_b)
|
| 1862 |
)
|
| 1863 |
center_b_in_a = bool(
|
| 1864 |
-
np.all(centers[second] >= lower_a)
|
|
|
|
| 1865 |
)
|
| 1866 |
if overlap >= 0.8 or center_a_in_b or center_b_in_a:
|
| 1867 |
union(first, second)
|
|
@@ -1934,9 +1941,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1934 |
instance["centroid"] - fragment["centroid"]
|
| 1935 |
),
|
| 1936 |
)
|
| 1937 |
-
nearest["first_time"] = min(
|
| 1938 |
-
nearest["first_time"], fragment["first_time"]
|
| 1939 |
-
)
|
| 1940 |
consolidated[class_name] = retained
|
| 1941 |
return consolidated
|
| 1942 |
|
|
@@ -1969,9 +1974,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1969 |
points, up_axis
|
| 1970 |
)
|
| 1971 |
record = dict(item)
|
| 1972 |
-
record.update(
|
| 1973 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1974 |
-
)
|
| 1975 |
measured.append(record)
|
| 1976 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1977 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1659 |
dimensions = np.asarray(dimensions)
|
| 1660 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1661 |
if len(centers) >= 4:
|
| 1662 |
+
features = np.concatenate(
|
| 1663 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1664 |
+
)
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1867 |
np.all(centers[first] >= lower_b) and np.all(centers[first] <= upper_b)
|
| 1868 |
)
|
| 1869 |
center_b_in_a = bool(
|
| 1870 |
+
np.all(centers[second] >= lower_a)
|
| 1871 |
+
and np.all(centers[second] <= upper_a)
|
| 1872 |
)
|
| 1873 |
if overlap >= 0.8 or center_a_in_b or center_b_in_a:
|
| 1874 |
union(first, second)
|
|
|
|
| 1941 |
instance["centroid"] - fragment["centroid"]
|
| 1942 |
),
|
| 1943 |
)
|
| 1944 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1945 |
consolidated[class_name] = retained
|
| 1946 |
return consolidated
|
| 1947 |
|
|
|
|
| 1974 |
points, up_axis
|
| 1975 |
)
|
| 1976 |
record = dict(item)
|
| 1977 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 1978 |
measured.append(record)
|
| 1979 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1980 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Orient Compact Boxes By Minimum Area Rectangle.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
# HYPOTHESIS: orient the box by the MINIMUM-AREA enclosing rectangle of the horizontal
|
| 1615 |
# footprint (cv2.minAreaRect / rotating calipers), not the SVD principal axis. The
|
| 1616 |
# tightest enclosing rectangle is the most faithful box orientation for a rigid object;
|
|
@@ -1661,7 +1665,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
dimensions = np.asarray(dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1784,13 +1790,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1784 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1785 |
if object_points:
|
| 1786 |
stacked = [
|
| 1787 |
-
np.stack(
|
|
|
|
|
|
|
| 1788 |
for p in object_points
|
| 1789 |
if len(p)
|
| 1790 |
]
|
| 1791 |
if stacked:
|
| 1792 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1793 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1794 |
|
| 1795 |
resolution = 0.1
|
| 1796 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1947,9 +1957,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1947 |
instance["centroid"] - fragment["centroid"]
|
| 1948 |
),
|
| 1949 |
)
|
| 1950 |
-
nearest["first_time"] = min(
|
| 1951 |
-
nearest["first_time"], fragment["first_time"]
|
| 1952 |
-
)
|
| 1953 |
consolidated[class_name] = retained
|
| 1954 |
return consolidated
|
| 1955 |
|
|
@@ -1982,9 +1990,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1982 |
points, up_axis
|
| 1983 |
)
|
| 1984 |
record = dict(item)
|
| 1985 |
-
record.update(
|
| 1986 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1987 |
-
)
|
| 1988 |
measured.append(record)
|
| 1989 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1990 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
# HYPOTHESIS: orient the box by the MINIMUM-AREA enclosing rectangle of the horizontal
|
| 1619 |
# footprint (cv2.minAreaRect / rotating calipers), not the SVD principal axis. The
|
| 1620 |
# tightest enclosing rectangle is the most faithful box orientation for a rigid object;
|
|
|
|
| 1665 |
dimensions = np.asarray(dimensions)
|
| 1666 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1667 |
if len(centers) >= 4:
|
| 1668 |
+
features = np.concatenate(
|
| 1669 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1670 |
+
)
|
| 1671 |
median = np.median(features, axis=0)
|
| 1672 |
deviation = np.abs(features - median)
|
| 1673 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1790 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1791 |
if object_points:
|
| 1792 |
stacked = [
|
| 1793 |
+
np.stack(
|
| 1794 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1795 |
+
)
|
| 1796 |
for p in object_points
|
| 1797 |
if len(p)
|
| 1798 |
]
|
| 1799 |
if stacked:
|
| 1800 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1801 |
+
footprint_points = footprint_points[
|
| 1802 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1803 |
+
]
|
| 1804 |
|
| 1805 |
resolution = 0.1
|
| 1806 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1957 |
instance["centroid"] - fragment["centroid"]
|
| 1958 |
),
|
| 1959 |
)
|
| 1960 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1961 |
consolidated[class_name] = retained
|
| 1962 |
return consolidated
|
| 1963 |
|
|
|
|
| 1990 |
points, up_axis
|
| 1991 |
)
|
| 1992 |
record = dict(item)
|
| 1993 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 1994 |
measured.append(record)
|
| 1995 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1996 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Recover Length Axis From View Union Full.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1711 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1712 |
)
|
| 1713 |
full_axis_dimensions = np.array(
|
| 1714 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1715 |
)
|
| 1716 |
# HYPOTHESIS: recover the longest axis from the UNION of all views, not the fullest single
|
| 1717 |
# frame. full_axis_dimensions above takes the biggest single frame's extent -- but when no
|
|
@@ -1821,13 +1832,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1821 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1822 |
if object_points:
|
| 1823 |
stacked = [
|
| 1824 |
-
np.stack(
|
|
|
|
|
|
|
| 1825 |
for p in object_points
|
| 1826 |
if len(p)
|
| 1827 |
]
|
| 1828 |
if stacked:
|
| 1829 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1830 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1831 |
|
| 1832 |
resolution = 0.1
|
| 1833 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1984,9 +1999,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1984 |
instance["centroid"] - fragment["centroid"]
|
| 1985 |
),
|
| 1986 |
)
|
| 1987 |
-
nearest["first_time"] = min(
|
| 1988 |
-
nearest["first_time"], fragment["first_time"]
|
| 1989 |
-
)
|
| 1990 |
consolidated[class_name] = retained
|
| 1991 |
return consolidated
|
| 1992 |
|
|
@@ -2019,9 +2032,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2019 |
points, up_axis
|
| 2020 |
)
|
| 2021 |
record = dict(item)
|
| 2022 |
-
record.update(
|
| 2023 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2024 |
-
)
|
| 2025 |
measured.append(record)
|
| 2026 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2027 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1719 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1720 |
)
|
| 1721 |
full_axis_dimensions = np.array(
|
| 1722 |
+
[
|
| 1723 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1724 |
+
for axis in range(3)
|
| 1725 |
+
]
|
| 1726 |
)
|
| 1727 |
# HYPOTHESIS: recover the longest axis from the UNION of all views, not the fullest single
|
| 1728 |
# frame. full_axis_dimensions above takes the biggest single frame's extent -- but when no
|
|
|
|
| 1832 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1833 |
if object_points:
|
| 1834 |
stacked = [
|
| 1835 |
+
np.stack(
|
| 1836 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1837 |
+
)
|
| 1838 |
for p in object_points
|
| 1839 |
if len(p)
|
| 1840 |
]
|
| 1841 |
if stacked:
|
| 1842 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1843 |
+
footprint_points = footprint_points[
|
| 1844 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1845 |
+
]
|
| 1846 |
|
| 1847 |
resolution = 0.1
|
| 1848 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1999 |
instance["centroid"] - fragment["centroid"]
|
| 2000 |
),
|
| 2001 |
)
|
| 2002 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2003 |
consolidated[class_name] = retained
|
| 2004 |
return consolidated
|
| 2005 |
|
|
|
|
| 2032 |
points, up_axis
|
| 2033 |
)
|
| 2034 |
record = dict(item)
|
| 2035 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2036 |
measured.append(record)
|
| 2037 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2038 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Recover Length Axis From View Union Robust.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1605 |
points = _canonical_clean(instance)
|
| 1606 |
if not len(points):
|
| 1607 |
points = instance["pts"]
|
| 1608 |
-
room_points = np.stack(
|
| 1609 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1610 |
-
)
|
| 1611 |
horizontal = room_points[:, :2]
|
| 1612 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1613 |
if len(centered) > 5000:
|
| 1614 |
-
centered = centered[
|
| 1615 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1616 |
-
]
|
| 1617 |
try:
|
| 1618 |
_, _, rotation = np.linalg.svd(
|
| 1619 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1648 |
upper = np.percentile(projected, 98, axis=0)
|
| 1649 |
centers.append((lower + upper) / 2)
|
| 1650 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1651 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1652 |
weights.append(len(observation))
|
| 1653 |
if not centers:
|
| 1654 |
projected = room_points @ orientation.T
|
|
@@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1664 |
full_dimensions = np.asarray(full_dimensions)
|
| 1665 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1666 |
if len(centers) >= 4:
|
| 1667 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1668 |
median = np.median(features, axis=0)
|
| 1669 |
deviation = np.abs(features - median)
|
| 1670 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1711 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1712 |
)
|
| 1713 |
full_axis_dimensions = np.array(
|
| 1714 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1715 |
)
|
| 1716 |
# HYPOTHESIS: recover the longest axis from the UNION of all views, not the fullest single
|
| 1717 |
# frame. full_axis_dimensions above takes the biggest single frame's extent -- but when no
|
|
@@ -1721,7 +1732,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1721 |
# straight off that combined cloud (robust 1/99 percentile span, so a stray point can't
|
| 1722 |
# inflate it). Vertical/side axes untouched, so abs_distance is unaffected.
|
| 1723 |
_proj_all = room_points @ orientation.T
|
| 1724 |
-
_union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile(
|
|
|
|
|
|
|
| 1725 |
box_dimensions = robust_dimensions.copy()
|
| 1726 |
longest_axis = int(np.argmax(robust_dimensions))
|
| 1727 |
box_dimensions[longest_axis] = max(
|
|
@@ -1821,13 +1834,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1821 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1822 |
if object_points:
|
| 1823 |
stacked = [
|
| 1824 |
-
np.stack(
|
|
|
|
|
|
|
| 1825 |
for p in object_points
|
| 1826 |
if len(p)
|
| 1827 |
]
|
| 1828 |
if stacked:
|
| 1829 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1830 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1831 |
|
| 1832 |
resolution = 0.1
|
| 1833 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1984,9 +2001,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1984 |
instance["centroid"] - fragment["centroid"]
|
| 1985 |
),
|
| 1986 |
)
|
| 1987 |
-
nearest["first_time"] = min(
|
| 1988 |
-
nearest["first_time"], fragment["first_time"]
|
| 1989 |
-
)
|
| 1990 |
consolidated[class_name] = retained
|
| 1991 |
return consolidated
|
| 1992 |
|
|
@@ -2019,9 +2034,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2019 |
points, up_axis
|
| 2020 |
)
|
| 2021 |
record = dict(item)
|
| 2022 |
-
record.update(
|
| 2023 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2024 |
-
)
|
| 2025 |
measured.append(record)
|
| 2026 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2027 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1613 |
points = _canonical_clean(instance)
|
| 1614 |
if not len(points):
|
| 1615 |
points = instance["pts"]
|
| 1616 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1617 |
horizontal = room_points[:, :2]
|
| 1618 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1619 |
if len(centered) > 5000:
|
| 1620 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1621 |
try:
|
| 1622 |
_, _, rotation = np.linalg.svd(
|
| 1623 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1652 |
upper = np.percentile(projected, 98, axis=0)
|
| 1653 |
centers.append((lower + upper) / 2)
|
| 1654 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1655 |
+
full_dimensions.append(
|
| 1656 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1657 |
+
)
|
| 1658 |
weights.append(len(observation))
|
| 1659 |
if not centers:
|
| 1660 |
projected = room_points @ orientation.T
|
|
|
|
| 1670 |
full_dimensions = np.asarray(full_dimensions)
|
| 1671 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1672 |
if len(centers) >= 4:
|
| 1673 |
+
features = np.concatenate(
|
| 1674 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1675 |
+
)
|
| 1676 |
median = np.median(features, axis=0)
|
| 1677 |
deviation = np.abs(features - median)
|
| 1678 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1719 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1720 |
)
|
| 1721 |
full_axis_dimensions = np.array(
|
| 1722 |
+
[
|
| 1723 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1724 |
+
for axis in range(3)
|
| 1725 |
+
]
|
| 1726 |
)
|
| 1727 |
# HYPOTHESIS: recover the longest axis from the UNION of all views, not the fullest single
|
| 1728 |
# frame. full_axis_dimensions above takes the biggest single frame's extent -- but when no
|
|
|
|
| 1732 |
# straight off that combined cloud (robust 1/99 percentile span, so a stray point can't
|
| 1733 |
# inflate it). Vertical/side axes untouched, so abs_distance is unaffected.
|
| 1734 |
_proj_all = room_points @ orientation.T
|
| 1735 |
+
_union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile(
|
| 1736 |
+
_proj_all, 1, axis=0
|
| 1737 |
+
)
|
| 1738 |
box_dimensions = robust_dimensions.copy()
|
| 1739 |
longest_axis = int(np.argmax(robust_dimensions))
|
| 1740 |
box_dimensions[longest_axis] = max(
|
|
|
|
| 1834 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1835 |
if object_points:
|
| 1836 |
stacked = [
|
| 1837 |
+
np.stack(
|
| 1838 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1839 |
+
)
|
| 1840 |
for p in object_points
|
| 1841 |
if len(p)
|
| 1842 |
]
|
| 1843 |
if stacked:
|
| 1844 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1845 |
+
footprint_points = footprint_points[
|
| 1846 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1847 |
+
]
|
| 1848 |
|
| 1849 |
resolution = 0.1
|
| 1850 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 2001 |
instance["centroid"] - fragment["centroid"]
|
| 2002 |
),
|
| 2003 |
)
|
| 2004 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 2005 |
consolidated[class_name] = retained
|
| 2006 |
return consolidated
|
| 2007 |
|
|
|
|
| 2034 |
points, up_axis
|
| 2035 |
)
|
| 2036 |
record = dict(item)
|
| 2037 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2038 |
measured.append(record)
|
| 2039 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2040 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Recover Length Axis Keep Robust Width Depth.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 98, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1707,7 +1715,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1707 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1708 |
)
|
| 1709 |
full_axis_dimensions = np.array(
|
| 1710 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1711 |
)
|
| 1712 |
box_dimensions = robust_dimensions.copy()
|
| 1713 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1803,13 +1814,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1803 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1804 |
if object_points:
|
| 1805 |
stacked = [
|
| 1806 |
-
np.stack(
|
|
|
|
|
|
|
| 1807 |
for p in object_points
|
| 1808 |
if len(p)
|
| 1809 |
]
|
| 1810 |
if stacked:
|
| 1811 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1812 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1813 |
|
| 1814 |
resolution = 0.1
|
| 1815 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1966,9 +1981,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1966 |
instance["centroid"] - fragment["centroid"]
|
| 1967 |
),
|
| 1968 |
)
|
| 1969 |
-
nearest["first_time"] = min(
|
| 1970 |
-
nearest["first_time"], fragment["first_time"]
|
| 1971 |
-
)
|
| 1972 |
consolidated[class_name] = retained
|
| 1973 |
return consolidated
|
| 1974 |
|
|
@@ -2001,9 +2014,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2001 |
points, up_axis
|
| 2002 |
)
|
| 2003 |
record = dict(item)
|
| 2004 |
-
record.update(
|
| 2005 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2006 |
-
)
|
| 2007 |
measured.append(record)
|
| 2008 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2009 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 98, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1715 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1716 |
)
|
| 1717 |
full_axis_dimensions = np.array(
|
| 1718 |
+
[
|
| 1719 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1720 |
+
for axis in range(3)
|
| 1721 |
+
]
|
| 1722 |
)
|
| 1723 |
box_dimensions = robust_dimensions.copy()
|
| 1724 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1814 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1815 |
if object_points:
|
| 1816 |
stacked = [
|
| 1817 |
+
np.stack(
|
| 1818 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1819 |
+
)
|
| 1820 |
for p in object_points
|
| 1821 |
if len(p)
|
| 1822 |
]
|
| 1823 |
if stacked:
|
| 1824 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1825 |
+
footprint_points = footprint_points[
|
| 1826 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1827 |
+
]
|
| 1828 |
|
| 1829 |
resolution = 0.1
|
| 1830 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1981 |
instance["centroid"] - fragment["centroid"]
|
| 1982 |
),
|
| 1983 |
)
|
| 1984 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1985 |
consolidated[class_name] = retained
|
| 1986 |
return consolidated
|
| 1987 |
|
|
|
|
| 2014 |
points, up_axis
|
| 2015 |
)
|
| 2016 |
record = dict(item)
|
| 2017 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2018 |
measured.append(record)
|
| 2019 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2020 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Recover Length Axis To Full Max.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 98, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1708 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1709 |
)
|
| 1710 |
full_axis_dimensions = np.array(
|
| 1711 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1712 |
)
|
| 1713 |
box_dimensions = robust_dimensions.copy()
|
| 1714 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
@@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1804 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1805 |
if object_points:
|
| 1806 |
stacked = [
|
| 1807 |
-
np.stack(
|
|
|
|
|
|
|
| 1808 |
for p in object_points
|
| 1809 |
if len(p)
|
| 1810 |
]
|
| 1811 |
if stacked:
|
| 1812 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1813 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1814 |
|
| 1815 |
resolution = 0.1
|
| 1816 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1967 |
instance["centroid"] - fragment["centroid"]
|
| 1968 |
),
|
| 1969 |
)
|
| 1970 |
-
nearest["first_time"] = min(
|
| 1971 |
-
nearest["first_time"], fragment["first_time"]
|
| 1972 |
-
)
|
| 1973 |
consolidated[class_name] = retained
|
| 1974 |
return consolidated
|
| 1975 |
|
|
@@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2002 |
points, up_axis
|
| 2003 |
)
|
| 2004 |
record = dict(item)
|
| 2005 |
-
record.update(
|
| 2006 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2007 |
-
)
|
| 2008 |
measured.append(record)
|
| 2009 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2010 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 98, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1716 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1717 |
)
|
| 1718 |
full_axis_dimensions = np.array(
|
| 1719 |
+
[
|
| 1720 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 1.0)
|
| 1721 |
+
for axis in range(3)
|
| 1722 |
+
]
|
| 1723 |
)
|
| 1724 |
box_dimensions = robust_dimensions.copy()
|
| 1725 |
longest_axis = int(np.argmax(robust_dimensions))
|
|
|
|
| 1815 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1816 |
if object_points:
|
| 1817 |
stacked = [
|
| 1818 |
+
np.stack(
|
| 1819 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1820 |
+
)
|
| 1821 |
for p in object_points
|
| 1822 |
if len(p)
|
| 1823 |
]
|
| 1824 |
if stacked:
|
| 1825 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1826 |
+
footprint_points = footprint_points[
|
| 1827 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1828 |
+
]
|
| 1829 |
|
| 1830 |
resolution = 0.1
|
| 1831 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1982 |
instance["centroid"] - fragment["centroid"]
|
| 1983 |
),
|
| 1984 |
)
|
| 1985 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1986 |
consolidated[class_name] = retained
|
| 1987 |
return consolidated
|
| 1988 |
|
|
|
|
| 2015 |
points, up_axis
|
| 2016 |
)
|
| 2017 |
record = dict(item)
|
| 2018 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2019 |
measured.append(record)
|
| 2020 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2021 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Recover Longest Two Axes To Full Extent.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1645 |
upper = np.percentile(projected, 98, axis=0)
|
| 1646 |
centers.append((lower + upper) / 2)
|
| 1647 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1648 |
-
full_dimensions.append(
|
|
|
|
|
|
|
| 1649 |
weights.append(len(observation))
|
| 1650 |
if not centers:
|
| 1651 |
projected = room_points @ orientation.T
|
|
@@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1661 |
full_dimensions = np.asarray(full_dimensions)
|
| 1662 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1663 |
if len(centers) >= 4:
|
| 1664 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1665 |
median = np.median(features, axis=0)
|
| 1666 |
deviation = np.abs(features - median)
|
| 1667 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1708 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1709 |
)
|
| 1710 |
full_axis_dimensions = np.array(
|
| 1711 |
-
[
|
|
|
|
|
|
|
|
|
|
| 1712 |
)
|
| 1713 |
# HYPOTHESIS variant: recover full extent on the longest TWO axes, not just the single
|
| 1714 |
# longest -- when the two largest axes are close, "which is longest" is noisy, and the size
|
|
@@ -1807,13 +1818,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
|
|
| 1807 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1808 |
if object_points:
|
| 1809 |
stacked = [
|
| 1810 |
-
np.stack(
|
|
|
|
|
|
|
| 1811 |
for p in object_points
|
| 1812 |
if len(p)
|
| 1813 |
]
|
| 1814 |
if stacked:
|
| 1815 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1816 |
-
footprint_points = footprint_points[
|
|
|
|
|
|
|
| 1817 |
|
| 1818 |
resolution = 0.1
|
| 1819 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
@@ -1970,9 +1985,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1970 |
instance["centroid"] - fragment["centroid"]
|
| 1971 |
),
|
| 1972 |
)
|
| 1973 |
-
nearest["first_time"] = min(
|
| 1974 |
-
nearest["first_time"], fragment["first_time"]
|
| 1975 |
-
)
|
| 1976 |
consolidated[class_name] = retained
|
| 1977 |
return consolidated
|
| 1978 |
|
|
@@ -2005,9 +2018,7 @@ def _compact_instances(scene, up_axis):
|
|
| 2005 |
points, up_axis
|
| 2006 |
)
|
| 2007 |
record = dict(item)
|
| 2008 |
-
record.update(
|
| 2009 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 2010 |
-
)
|
| 2011 |
measured.append(record)
|
| 2012 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2013 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1649 |
upper = np.percentile(projected, 98, axis=0)
|
| 1650 |
centers.append((lower + upper) / 2)
|
| 1651 |
dimensions.append(np.maximum(upper - lower, 0.0))
|
| 1652 |
+
full_dimensions.append(
|
| 1653 |
+
np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)
|
| 1654 |
+
)
|
| 1655 |
weights.append(len(observation))
|
| 1656 |
if not centers:
|
| 1657 |
projected = room_points @ orientation.T
|
|
|
|
| 1667 |
full_dimensions = np.asarray(full_dimensions)
|
| 1668 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1669 |
if len(centers) >= 4:
|
| 1670 |
+
features = np.concatenate(
|
| 1671 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1672 |
+
)
|
| 1673 |
median = np.median(features, axis=0)
|
| 1674 |
deviation = np.abs(features - median)
|
| 1675 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1716 |
[_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)]
|
| 1717 |
)
|
| 1718 |
full_axis_dimensions = np.array(
|
| 1719 |
+
[
|
| 1720 |
+
_weighted_quantile(full_dimensions[:, axis], weights, 0.9)
|
| 1721 |
+
for axis in range(3)
|
| 1722 |
+
]
|
| 1723 |
)
|
| 1724 |
# HYPOTHESIS variant: recover full extent on the longest TWO axes, not just the single
|
| 1725 |
# longest -- when the two largest axes are close, "which is longest" is noisy, and the size
|
|
|
|
| 1818 |
footprint_points = np.zeros((0, 2), np.float64)
|
| 1819 |
if object_points:
|
| 1820 |
stacked = [
|
| 1821 |
+
np.stack(
|
| 1822 |
+
[np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1
|
| 1823 |
+
)
|
| 1824 |
for p in object_points
|
| 1825 |
if len(p)
|
| 1826 |
]
|
| 1827 |
if stacked:
|
| 1828 |
footprint_points = np.concatenate(stacked, axis=0)
|
| 1829 |
+
footprint_points = footprint_points[
|
| 1830 |
+
np.isfinite(footprint_points).all(axis=1)
|
| 1831 |
+
]
|
| 1832 |
|
| 1833 |
resolution = 0.1
|
| 1834 |
combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0)
|
|
|
|
| 1985 |
instance["centroid"] - fragment["centroid"]
|
| 1986 |
),
|
| 1987 |
)
|
| 1988 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1989 |
consolidated[class_name] = retained
|
| 1990 |
return consolidated
|
| 1991 |
|
|
|
|
| 2018 |
points, up_axis
|
| 2019 |
)
|
| 2020 |
record = dict(item)
|
| 2021 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 2022 |
measured.append(record)
|
| 2023 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 2024 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
experiments/hypotheses/Reject Below-Floor Compact Box Observations.py
CHANGED
|
@@ -24,7 +24,6 @@ import json
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
| 27 |
-
|
| 28 |
# ==========================================================================================
|
| 29 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 30 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
@@ -118,7 +117,8 @@ def room_gravity(
|
|
| 118 |
):
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
-
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
|
|
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
@@ -211,7 +211,8 @@ def _floor_basis(up_vec):
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
-
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
|
|
|
| 215 |
g = np.asarray(up_vec, np.float64)
|
| 216 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 217 |
up_ax = int(np.argmax(np.abs(g)))
|
|
@@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax):
|
|
| 436 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 437 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 438 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 439 |
-
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
|
|
|
| 440 |
from scipy.spatial import cKDTree
|
| 441 |
|
| 442 |
if len(pts) < k + 2:
|
|
@@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 451 |
def _main_cluster(pts):
|
| 452 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 453 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 454 |
-
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
|
|
|
| 455 |
from scipy.spatial import cKDTree
|
| 456 |
|
| 457 |
if len(pts) < 30:
|
|
@@ -487,7 +490,8 @@ def _clean(inst, cap=4000):
|
|
| 487 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 488 |
object's OWN median confidence (data-derived cut);
|
| 489 |
(2) statistical density outlier removal on the survivors;
|
| 490 |
-
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
|
|
|
| 491 |
if inst.get("_cleanpts") is not None:
|
| 492 |
return inst["_cleanpts"]
|
| 493 |
pts = inst["pts"]
|
|
@@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000):
|
|
| 513 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 514 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 515 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 516 |
-
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
|
|
|
| 517 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 518 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 519 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
@@ -569,7 +574,8 @@ def refine_mask(mask, rgb):
|
|
| 569 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 570 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 571 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 572 |
-
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
|
|
|
| 573 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 574 |
mask = cv2.resize(
|
| 575 |
mask.astype(np.uint8),
|
|
@@ -624,7 +630,8 @@ def backproject_frame(
|
|
| 624 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 625 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 626 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 627 |
-
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
|
|
|
| 628 |
height, width = depth_f.shape
|
| 629 |
empty = (
|
| 630 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
@@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path):
|
|
| 1225 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1226 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1227 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1228 |
-
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
|
|
|
| 1229 |
body = dict(code)
|
| 1230 |
ao = body.pop("appearance order", None)
|
| 1231 |
text = json.dumps(body, indent=1).rstrip()
|
|
@@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1602 |
points = _canonical_clean(instance)
|
| 1603 |
if not len(points):
|
| 1604 |
points = instance["pts"]
|
| 1605 |
-
room_points = np.stack(
|
| 1606 |
-
[points @ u, points @ v, points @ g - floor_level], axis=1
|
| 1607 |
-
)
|
| 1608 |
horizontal = room_points[:, :2]
|
| 1609 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1610 |
if len(centered) > 5000:
|
| 1611 |
-
centered = centered[
|
| 1612 |
-
np.random.RandomState(0).choice(len(centered), 5000, False)
|
| 1613 |
-
]
|
| 1614 |
try:
|
| 1615 |
_, _, rotation = np.linalg.svd(
|
| 1616 |
centered - centered.mean(axis=0), full_matrices=False
|
|
@@ -1676,7 +1680,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level):
|
|
| 1676 |
dimensions = np.asarray(dimensions)
|
| 1677 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1678 |
if len(centers) >= 4:
|
| 1679 |
-
features = np.concatenate(
|
|
|
|
|
|
|
| 1680 |
median = np.median(features, axis=0)
|
| 1681 |
deviation = np.abs(features - median)
|
| 1682 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
@@ -1919,9 +1925,7 @@ def _consolidate_compact_instances(instances, stats, up_axis):
|
|
| 1919 |
instance["centroid"] - fragment["centroid"]
|
| 1920 |
),
|
| 1921 |
)
|
| 1922 |
-
nearest["first_time"] = min(
|
| 1923 |
-
nearest["first_time"], fragment["first_time"]
|
| 1924 |
-
)
|
| 1925 |
consolidated[class_name] = retained
|
| 1926 |
return consolidated
|
| 1927 |
|
|
@@ -1954,9 +1958,7 @@ def _compact_instances(scene, up_axis):
|
|
| 1954 |
points, up_axis
|
| 1955 |
)
|
| 1956 |
record = dict(item)
|
| 1957 |
-
record.update(
|
| 1958 |
-
{"centroid": centroid, "size": size, "dims": dimensions}
|
| 1959 |
-
)
|
| 1960 |
measured.append(record)
|
| 1961 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1962 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|
|
|
|
| 24 |
import numpy as np
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
# ==========================================================================================
|
| 28 |
# CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
|
| 29 |
# affect only the math below (build_instances/backproject_frame/etc.), never model inference.
|
|
|
|
| 117 |
):
|
| 118 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 119 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 120 |
+
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
|
| 121 |
+
"""
|
| 122 |
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
height, width = depth[f].shape
|
|
|
|
| 211 |
floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
|
| 212 |
differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
|
| 213 |
rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
|
| 214 |
+
all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
|
| 215 |
+
"""
|
| 216 |
g = np.asarray(up_vec, np.float64)
|
| 217 |
g = g / (np.linalg.norm(g) + 1e-12)
|
| 218 |
up_ax = int(np.argmax(np.abs(g)))
|
|
|
|
| 437 |
def _sor(pts, k=16, std=2.0, cap=4000):
|
| 438 |
"""Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
|
| 439 |
mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
|
| 440 |
+
k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
|
| 441 |
+
"""
|
| 442 |
from scipy.spatial import cKDTree
|
| 443 |
|
| 444 |
if len(pts) < k + 2:
|
|
|
|
| 453 |
def _main_cluster(pts):
|
| 454 |
"""Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
|
| 455 |
object forms a disconnected component (a gap separates two objects); the true object is the largest one.
|
| 456 |
+
Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
|
| 457 |
+
"""
|
| 458 |
from scipy.spatial import cKDTree
|
| 459 |
|
| 460 |
if len(pts) < 30:
|
|
|
|
| 490 |
(1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
|
| 491 |
object's OWN median confidence (data-derived cut);
|
| 492 |
(2) statistical density outlier removal on the survivors;
|
| 493 |
+
(3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
|
| 494 |
+
"""
|
| 495 |
if inst.get("_cleanpts") is not None:
|
| 496 |
return inst["_cleanpts"]
|
| 497 |
pts = inst["pts"]
|
|
|
|
| 517 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 518 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 519 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 520 |
+
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
|
| 521 |
+
"""
|
| 522 |
points_a = _clean(_rep(instances_a), cap=k)
|
| 523 |
points_b = _clean(_rep(instances_b), cap=k)
|
| 524 |
if len(points_a) == 0 or len(points_b) == 0:
|
|
|
|
| 574 |
"""Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
|
| 575 |
bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
|
| 576 |
cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
|
| 577 |
+
variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
|
| 578 |
+
"""
|
| 579 |
if mask.shape[:2] != rgb.shape[:2]:
|
| 580 |
mask = cv2.resize(
|
| 581 |
mask.astype(np.uint8),
|
|
|
|
| 630 |
valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
|
| 631 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 632 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 633 |
+
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
|
| 634 |
+
"""
|
| 635 |
height, width = depth_f.shape
|
| 636 |
empty = (
|
| 637 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
|
|
|
| 1232 |
"appearance order" is written as one compact line instead of one line per entry -- it's a
|
| 1233 |
single ordered sequence meant to be scanned, not structured data meant to be read field by
|
| 1234 |
field like the rest of the code. Every writer of spatial_code.json should go through this
|
| 1235 |
+
(not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
|
| 1236 |
+
"""
|
| 1237 |
body = dict(code)
|
| 1238 |
ao = body.pop("appearance order", None)
|
| 1239 |
text = json.dumps(body, indent=1).rstrip()
|
|
|
|
| 1610 |
points = _canonical_clean(instance)
|
| 1611 |
if not len(points):
|
| 1612 |
points = instance["pts"]
|
| 1613 |
+
room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
|
|
|
|
|
|
|
| 1614 |
horizontal = room_points[:, :2]
|
| 1615 |
centered = horizontal - np.median(horizontal, axis=0)
|
| 1616 |
if len(centered) > 5000:
|
| 1617 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
|
|
|
|
|
|
| 1618 |
try:
|
| 1619 |
_, _, rotation = np.linalg.svd(
|
| 1620 |
centered - centered.mean(axis=0), full_matrices=False
|
|
|
|
| 1680 |
dimensions = np.asarray(dimensions)
|
| 1681 |
weights = np.sqrt(np.asarray(weights, np.float64))
|
| 1682 |
if len(centers) >= 4:
|
| 1683 |
+
features = np.concatenate(
|
| 1684 |
+
[centers, np.log(np.maximum(dimensions, 1e-4))], axis=1
|
| 1685 |
+
)
|
| 1686 |
median = np.median(features, axis=0)
|
| 1687 |
deviation = np.abs(features - median)
|
| 1688 |
scale = 1.4826 * np.median(deviation, axis=0)
|
|
|
|
| 1925 |
instance["centroid"] - fragment["centroid"]
|
| 1926 |
),
|
| 1927 |
)
|
| 1928 |
+
nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
|
|
|
|
|
|
|
| 1929 |
consolidated[class_name] = retained
|
| 1930 |
return consolidated
|
| 1931 |
|
|
|
|
| 1958 |
points, up_axis
|
| 1959 |
)
|
| 1960 |
record = dict(item)
|
| 1961 |
+
record.update({"centroid": centroid, "size": size, "dims": dimensions})
|
|
|
|
|
|
|
| 1962 |
measured.append(record)
|
| 1963 |
instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
|
| 1964 |
instances = _consolidate_compact_instances(instances, stats, up_axis)
|