Add sensor fusion point cloud spine
This commit is contained in:
parent
2671f8b81a
commit
ab929ef8c6
10 changed files with 806 additions and 12 deletions
94
config/sensor-fusion.example.json
Normal file
94
config/sensor-fusion.example.json
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
{
|
||||
"fusion": {
|
||||
"max_pair_dt_ns": 25000000,
|
||||
"max_reprojection_error_px": 4.0,
|
||||
"min_confidence": 0.1,
|
||||
"cache_ttl_ns": 500000000
|
||||
},
|
||||
"cameras": [
|
||||
{
|
||||
"id": "ps3eye_left",
|
||||
"role": "tracking",
|
||||
"capture": {
|
||||
"adapter": "ffmpeg-dshow-raw-bgr",
|
||||
"device_name": "PS3 Eye Universal",
|
||||
"width": 320,
|
||||
"height": 240,
|
||||
"fps": 60
|
||||
},
|
||||
"intrinsics": {
|
||||
"width": 320,
|
||||
"height": 240,
|
||||
"camera_matrix": [
|
||||
[260.0, 0.0, 160.0],
|
||||
[0.0, 260.0, 120.0],
|
||||
[0.0, 0.0, 1.0]
|
||||
],
|
||||
"dist_coeffs": [0.0, 0.0, 0.0, 0.0, 0.0]
|
||||
},
|
||||
"world_from_sensor": [
|
||||
[1.0, 0.0, 0.0, -0.25],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0]
|
||||
],
|
||||
"latency_ms": 25.0
|
||||
},
|
||||
{
|
||||
"id": "ps3eye_right",
|
||||
"role": "tracking",
|
||||
"capture": {
|
||||
"adapter": "ffmpeg-dshow-raw-bgr",
|
||||
"device_name": "PS3 Eye Universal2",
|
||||
"width": 320,
|
||||
"height": 240,
|
||||
"fps": 60
|
||||
},
|
||||
"intrinsics": {
|
||||
"width": 320,
|
||||
"height": 240,
|
||||
"camera_matrix": [
|
||||
[260.0, 0.0, 160.0],
|
||||
[0.0, 260.0, 120.0],
|
||||
[0.0, 0.0, 1.0]
|
||||
],
|
||||
"dist_coeffs": [0.0, 0.0, 0.0, 0.0, 0.0]
|
||||
},
|
||||
"world_from_sensor": [
|
||||
[1.0, 0.0, 0.0, 0.25],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0]
|
||||
],
|
||||
"latency_ms": 25.0
|
||||
},
|
||||
{
|
||||
"id": "kiyo_rgb",
|
||||
"role": "rgb_projection",
|
||||
"capture": {
|
||||
"adapter": "opencv-dshow",
|
||||
"index": 1,
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"fps": 30
|
||||
},
|
||||
"intrinsics": {
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"camera_matrix": [
|
||||
[520.0, 0.0, 320.0],
|
||||
[0.0, 520.0, 240.0],
|
||||
[0.0, 0.0, 1.0]
|
||||
],
|
||||
"dist_coeffs": [0.0, 0.0, 0.0, 0.0, 0.0]
|
||||
},
|
||||
"world_from_sensor": [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, -0.5],
|
||||
[0.0, 0.0, 1.0, 0.2],
|
||||
[0.0, 0.0, 0.0, 1.0]
|
||||
],
|
||||
"latency_ms": 45.0
|
||||
}
|
||||
]
|
||||
}
|
||||
90
docs/sensor-fusion-architecture.md
Normal file
90
docs/sensor-fusion-architecture.md
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
# Sensor Fusion Architecture
|
||||
|
||||
## Objective
|
||||
|
||||
Produce an aligned, timestamped point cloud from the local visual rig while allowing latency, buffering, and cache convergence. The live render path can lag behind capture; it may not lie about coordinate ownership.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
The rig currently has usable capture surfaces:
|
||||
|
||||
- PS3 Eyes through FFmpeg DirectShow device names `PS3 Eye Universal` and `PS3 Eye Universal2`, verified at dual `320x240@60`.
|
||||
- Kiyo-class RGB cameras through OpenCV/DirectShow/MSMF for color evidence.
|
||||
- LeapUVC raw IR through OpenCV for near-field evidence.
|
||||
- ChArUco tooling for intrinsics capture, but no shared fusion state yet.
|
||||
|
||||
That is capture. Capture is not a world model.
|
||||
|
||||
## Invariants
|
||||
|
||||
- World coordinates own truth.
|
||||
- Capture adapters emit timestamped observations; they do not own fusion semantics.
|
||||
- Fusion core is pure and testable: calibrated camera models plus 2D observations in, 3D points/confidence out.
|
||||
- Point clouds and later brush/splat packets are cached render lowerings, not the canonical scene.
|
||||
- A missing high-detail update renders stale-but-bounded state until better evidence arrives.
|
||||
|
||||
## Intended Change
|
||||
|
||||
The first pipeline slice adds these boundaries:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Capture adapters"] --> B["FramePacket ring"]
|
||||
B --> C["Detection adapter"]
|
||||
C --> D["Observation2D"]
|
||||
E["SensorRig calibration"] --> F["Fusion core"]
|
||||
D --> F
|
||||
F --> G["TrackCache"]
|
||||
G --> H["PointCloud PLY"]
|
||||
G --> I["Future brush/splat packets"]
|
||||
```
|
||||
|
||||
## Ownership
|
||||
|
||||
- `localcast.sensor_fusion.core` owns calibrated camera models, 2D observations, DLT triangulation, reprojection gating, confidence scoring, point-cloud export, and track cache expiry.
|
||||
- `localcast.sensor_fusion.adapters` owns driver-facing frame ingress. Its first concrete adapter is an FFmpeg raw BGR reader for the PS3 Eye DirectShow path.
|
||||
- `scripts/sensor_fusion.py` owns CLI composition for offline observation files.
|
||||
- `config/sensor-fusion.example.json` owns the declarative rig shape: capture hints, intrinsics, extrinsics, latency, and fusion thresholds.
|
||||
|
||||
## Cache Discipline
|
||||
|
||||
This follows the same architectural lesson as `fractal-domains-cache-that-bites.md`: state begins as semantic claims in a named domain, then lowers into cheaper packets.
|
||||
|
||||
For this project:
|
||||
|
||||
```text
|
||||
sensor observation
|
||||
-> calibrated world ray
|
||||
-> triangulated marker claim
|
||||
-> cached track
|
||||
-> point cloud / brush packet / splat packet
|
||||
-> renderer
|
||||
```
|
||||
|
||||
The cache is not a bucket. `TrackCache` has a TTL and confidence update rule so the system can buffer and converge without pretending stale points are fresh. Later GPU buffers should mirror this shape: observation SoA, track SoA, brush packet SoA.
|
||||
|
||||
## Test Boundaries
|
||||
|
||||
The core can be tested without cameras:
|
||||
|
||||
- synthetic cameras triangulate a known point
|
||||
- timestamp windows reject stale pairs
|
||||
- track cache expiry is deterministic
|
||||
- raw-frame adapter can be tested from an in-memory byte stream
|
||||
|
||||
Those tests matter because camera drivers are not unit-test dependencies. They are weather.
|
||||
|
||||
## Next Cut
|
||||
|
||||
1. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections.
|
||||
2. Load real ChArUco intrinsics/extrinsics into `config/sensor-fusion.json`.
|
||||
3. Record an observation JSONL/JSON run from the two PS3 Eyes.
|
||||
4. Generate a live sparse PLY stream or debug preview.
|
||||
5. Lower cached tracks into brush/splat packets once the point cloud is stable.
|
||||
|
||||
## References
|
||||
|
||||
- OpenCV multi-camera calibration and triangulation are the geometry spine. See `research/visual-spatial-map/summary.md`.
|
||||
- Jacob and Haeb-Umbach 2015 motivates audio-visual coordinate alignment. See `research/visual-spatial-map/mirrors/krekovic-2015-audio-visual-geometry-calibration.pdf`.
|
||||
- Kerbl et al. 2023 and RTG-SLAM motivate splats as render packets, not state ownership. See `research/visual-spatial-map/summary.md` and `research/gpu-fusion-splatting/summary.md`.
|
||||
- `E:\Projects\gamecult-site\GameCult\Blog\fractal-domains-cache-that-bites.md` supplies the cache discipline: semantic authority first, backend packet lowering second.
|
||||
1
localcast/__init__.py
Normal file
1
localcast/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""LocalCastBridge Python helpers."""
|
||||
25
localcast/sensor_fusion/__init__.py
Normal file
25
localcast/sensor_fusion/__init__.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
"""Sensor fusion spine for the LocalCastBridge spatial rig."""
|
||||
|
||||
from .core import (
|
||||
CameraModel,
|
||||
FusionConfig,
|
||||
FusionResult,
|
||||
Observation2D,
|
||||
PointCloud,
|
||||
SensorRig,
|
||||
TrackCache,
|
||||
TriangulatedPoint,
|
||||
load_fusion_config,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CameraModel",
|
||||
"FusionConfig",
|
||||
"FusionResult",
|
||||
"Observation2D",
|
||||
"PointCloud",
|
||||
"SensorRig",
|
||||
"TrackCache",
|
||||
"TriangulatedPoint",
|
||||
"load_fusion_config",
|
||||
]
|
||||
120
localcast/sensor_fusion/adapters.py
Normal file
120
localcast/sensor_fusion/adapters.py
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import subprocess
|
||||
import time
|
||||
from typing import BinaryIO, Iterator, Protocol
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class FrameSource(Protocol):
|
||||
def frames(self) -> Iterator["FramePacket"]:
|
||||
...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FramePacket:
|
||||
sensor_id: str
|
||||
timestamp_ns: int
|
||||
sequence: int
|
||||
image_bgr: np.ndarray
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FfmpegRawVideoConfig:
|
||||
sensor_id: str
|
||||
ffmpeg_exe: str
|
||||
device_name: str
|
||||
width: int
|
||||
height: int
|
||||
fps: int
|
||||
pixel_format: str = "bgr24"
|
||||
|
||||
@property
|
||||
def frame_bytes(self) -> int:
|
||||
if self.pixel_format != "bgr24":
|
||||
raise ValueError(f"Unsupported raw pixel format: {self.pixel_format}")
|
||||
return self.width * self.height * 3
|
||||
|
||||
def command(self) -> list[str]:
|
||||
return [
|
||||
self.ffmpeg_exe,
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"warning",
|
||||
"-f",
|
||||
"dshow",
|
||||
"-video_size",
|
||||
f"{self.width}x{self.height}",
|
||||
"-framerate",
|
||||
str(self.fps),
|
||||
"-pixel_format",
|
||||
self.pixel_format,
|
||||
"-i",
|
||||
f"video={self.device_name}",
|
||||
"-an",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-",
|
||||
]
|
||||
|
||||
|
||||
class FfmpegRawVideoSource:
|
||||
"""Frame source adapter for DirectShow devices that FFmpeg negotiates better than OpenCV."""
|
||||
|
||||
def __init__(self, config: FfmpegRawVideoConfig):
|
||||
self.config = config
|
||||
self._process: subprocess.Popen[bytes] | None = None
|
||||
|
||||
def __enter__(self) -> "FfmpegRawVideoSource":
|
||||
self._process = subprocess.Popen(
|
||||
self.config.command(),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if self._process is None:
|
||||
return
|
||||
if self._process.poll() is None:
|
||||
self._process.terminate()
|
||||
try:
|
||||
self._process.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._process.kill()
|
||||
self._process = None
|
||||
|
||||
def frames(self) -> Iterator[FramePacket]:
|
||||
if self._process is None or self._process.stdout is None:
|
||||
raise RuntimeError("FfmpegRawVideoSource must be used as a context manager")
|
||||
yield from read_raw_bgr_frames(
|
||||
self._process.stdout,
|
||||
sensor_id=self.config.sensor_id,
|
||||
width=self.config.width,
|
||||
height=self.config.height,
|
||||
frame_bytes=self.config.frame_bytes,
|
||||
)
|
||||
|
||||
|
||||
def read_raw_bgr_frames(
|
||||
stream: BinaryIO,
|
||||
sensor_id: str,
|
||||
width: int,
|
||||
height: int,
|
||||
frame_bytes: int,
|
||||
) -> Iterator[FramePacket]:
|
||||
sequence = 0
|
||||
while True:
|
||||
blob = stream.read(frame_bytes)
|
||||
if not blob or len(blob) < frame_bytes:
|
||||
return
|
||||
frame = np.frombuffer(blob, dtype=np.uint8).reshape((height, width, 3)).copy()
|
||||
yield FramePacket(
|
||||
sensor_id=sensor_id,
|
||||
timestamp_ns=time.monotonic_ns(),
|
||||
sequence=sequence,
|
||||
image_bgr=frame,
|
||||
)
|
||||
sequence += 1
|
||||
274
localcast/sensor_fusion/core.py
Normal file
274
localcast/sensor_fusion/core.py
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
ArrayLike = Iterable[Iterable[float]] | Iterable[float]
|
||||
|
||||
|
||||
def _array(value: ArrayLike, shape: tuple[int, ...], name: str) -> np.ndarray:
|
||||
arr = np.asarray(value, dtype=np.float64)
|
||||
if arr.shape != shape:
|
||||
raise ValueError(f"{name} must have shape {shape}, got {arr.shape}")
|
||||
return arr
|
||||
|
||||
|
||||
def _normalize_homogeneous(point: np.ndarray) -> np.ndarray:
|
||||
if abs(point[-1]) < 1e-12:
|
||||
raise ValueError("Cannot normalize homogeneous point with near-zero W")
|
||||
return point[:-1] / point[-1]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CameraModel:
|
||||
"""Pinhole camera model with a world-from-camera transform."""
|
||||
|
||||
sensor_id: str
|
||||
camera_matrix: np.ndarray
|
||||
dist_coeffs: np.ndarray
|
||||
world_from_sensor: np.ndarray
|
||||
width: int
|
||||
height: int
|
||||
role: str = "tracking"
|
||||
latency_ms: float = 0.0
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "CameraModel":
|
||||
intrinsics = data.get("intrinsics", {})
|
||||
return CameraModel(
|
||||
sensor_id=data["id"],
|
||||
camera_matrix=_array(intrinsics["camera_matrix"], (3, 3), "camera_matrix"),
|
||||
dist_coeffs=np.asarray(intrinsics.get("dist_coeffs", []), dtype=np.float64),
|
||||
world_from_sensor=_array(data["world_from_sensor"], (4, 4), "world_from_sensor"),
|
||||
width=int(intrinsics["width"]),
|
||||
height=int(intrinsics["height"]),
|
||||
role=data.get("role", "tracking"),
|
||||
latency_ms=float(data.get("latency_ms", 0.0)),
|
||||
)
|
||||
|
||||
@property
|
||||
def sensor_from_world(self) -> np.ndarray:
|
||||
return np.linalg.inv(self.world_from_sensor)
|
||||
|
||||
@property
|
||||
def projection_matrix(self) -> np.ndarray:
|
||||
return self.camera_matrix @ self.sensor_from_world[:3, :]
|
||||
|
||||
@property
|
||||
def position_world(self) -> np.ndarray:
|
||||
return self.world_from_sensor[:3, 3]
|
||||
|
||||
def project_world(self, point_world: np.ndarray) -> np.ndarray:
|
||||
point = np.ones(4, dtype=np.float64)
|
||||
point[:3] = point_world
|
||||
uvw = self.projection_matrix @ point
|
||||
return _normalize_homogeneous(uvw)
|
||||
|
||||
def reprojection_error(self, point_world: np.ndarray, uv: np.ndarray) -> float:
|
||||
return float(np.linalg.norm(self.project_world(point_world) - uv))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Observation2D:
|
||||
sensor_id: str
|
||||
marker_id: str
|
||||
timestamp_ns: int
|
||||
uv: np.ndarray
|
||||
confidence: float = 1.0
|
||||
sequence: int | None = None
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "Observation2D":
|
||||
return Observation2D(
|
||||
sensor_id=data["sensor_id"],
|
||||
marker_id=data["marker_id"],
|
||||
timestamp_ns=int(data["timestamp_ns"]),
|
||||
uv=_array(data["uv"], (2,), "uv"),
|
||||
confidence=float(data.get("confidence", 1.0)),
|
||||
sequence=None if data.get("sequence") is None else int(data["sequence"]),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TriangulatedPoint:
|
||||
marker_id: str
|
||||
timestamp_ns: int
|
||||
xyz: np.ndarray
|
||||
confidence: float
|
||||
reprojection_error_px: float
|
||||
sensors: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FusionResult:
|
||||
points: tuple[TriangulatedPoint, ...]
|
||||
dropped: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass
|
||||
class FusionConfig:
|
||||
max_pair_dt_ns: int = 25_000_000
|
||||
max_reprojection_error_px: float = 4.0
|
||||
min_confidence: float = 0.1
|
||||
cache_ttl_ns: int = 500_000_000
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "FusionConfig":
|
||||
return FusionConfig(
|
||||
max_pair_dt_ns=int(data.get("max_pair_dt_ns", 25_000_000)),
|
||||
max_reprojection_error_px=float(data.get("max_reprojection_error_px", 4.0)),
|
||||
min_confidence=float(data.get("min_confidence", 0.1)),
|
||||
cache_ttl_ns=int(data.get("cache_ttl_ns", 500_000_000)),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SensorRig:
|
||||
cameras: dict[str, CameraModel]
|
||||
config: FusionConfig = field(default_factory=FusionConfig)
|
||||
|
||||
@staticmethod
|
||||
def from_dict(data: dict) -> "SensorRig":
|
||||
cameras = {item["id"]: CameraModel.from_dict(item) for item in data.get("cameras", [])}
|
||||
if len(cameras) < 2:
|
||||
raise ValueError("Sensor rig needs at least two cameras for triangulation")
|
||||
return SensorRig(cameras=cameras, config=FusionConfig.from_dict(data.get("fusion", {})))
|
||||
|
||||
def fuse(self, observations: Iterable[Observation2D]) -> FusionResult:
|
||||
grouped: dict[str, list[Observation2D]] = {}
|
||||
dropped: list[str] = []
|
||||
for obs in observations:
|
||||
if obs.sensor_id not in self.cameras:
|
||||
dropped.append(f"{obs.marker_id}: unknown sensor {obs.sensor_id}")
|
||||
continue
|
||||
if obs.confidence < self.config.min_confidence:
|
||||
dropped.append(f"{obs.marker_id}: low confidence from {obs.sensor_id}")
|
||||
continue
|
||||
grouped.setdefault(obs.marker_id, []).append(obs)
|
||||
|
||||
points: list[TriangulatedPoint] = []
|
||||
for marker_id, marker_obs in grouped.items():
|
||||
point = self._fuse_marker(marker_id, marker_obs)
|
||||
if point is None:
|
||||
dropped.append(f"{marker_id}: no valid camera pair")
|
||||
else:
|
||||
points.append(point)
|
||||
return FusionResult(points=tuple(points), dropped=tuple(dropped))
|
||||
|
||||
def _fuse_marker(self, marker_id: str, observations: list[Observation2D]) -> TriangulatedPoint | None:
|
||||
best: TriangulatedPoint | None = None
|
||||
ordered = sorted(observations, key=lambda item: item.confidence, reverse=True)
|
||||
for i, left in enumerate(ordered):
|
||||
for right in ordered[i + 1 :]:
|
||||
if left.sensor_id == right.sensor_id:
|
||||
continue
|
||||
dt = abs(left.timestamp_ns - right.timestamp_ns)
|
||||
if dt > self.config.max_pair_dt_ns:
|
||||
continue
|
||||
point = self._triangulate_pair(marker_id, left, right)
|
||||
if point is None:
|
||||
continue
|
||||
if best is None or point.confidence > best.confidence:
|
||||
best = point
|
||||
return best
|
||||
|
||||
def _triangulate_pair(
|
||||
self,
|
||||
marker_id: str,
|
||||
left: Observation2D,
|
||||
right: Observation2D,
|
||||
) -> TriangulatedPoint | None:
|
||||
cam_a = self.cameras[left.sensor_id]
|
||||
cam_b = self.cameras[right.sensor_id]
|
||||
xyz = triangulate_dlt(cam_a.projection_matrix, left.uv, cam_b.projection_matrix, right.uv)
|
||||
error_a = cam_a.reprojection_error(xyz, left.uv)
|
||||
error_b = cam_b.reprojection_error(xyz, right.uv)
|
||||
reprojection_error = (error_a + error_b) * 0.5
|
||||
if not math.isfinite(reprojection_error) or reprojection_error > self.config.max_reprojection_error_px:
|
||||
return None
|
||||
dt = abs(left.timestamp_ns - right.timestamp_ns)
|
||||
time_score = 1.0 - min(1.0, dt / max(1, self.config.max_pair_dt_ns))
|
||||
error_score = 1.0 - min(1.0, reprojection_error / max(1e-9, self.config.max_reprojection_error_px))
|
||||
confidence = float(min(left.confidence, right.confidence) * (0.5 + 0.5 * time_score) * (0.5 + 0.5 * error_score))
|
||||
return TriangulatedPoint(
|
||||
marker_id=marker_id,
|
||||
timestamp_ns=max(left.timestamp_ns, right.timestamp_ns),
|
||||
xyz=xyz,
|
||||
confidence=confidence,
|
||||
reprojection_error_px=float(reprojection_error),
|
||||
sensors=(left.sensor_id, right.sensor_id),
|
||||
)
|
||||
|
||||
|
||||
def triangulate_dlt(proj_a: np.ndarray, uv_a: np.ndarray, proj_b: np.ndarray, uv_b: np.ndarray) -> np.ndarray:
|
||||
"""Triangulate one point from two calibrated cameras using linear DLT."""
|
||||
|
||||
a = np.asarray(proj_a, dtype=np.float64)
|
||||
b = np.asarray(proj_b, dtype=np.float64)
|
||||
u0, v0 = np.asarray(uv_a, dtype=np.float64)
|
||||
u1, v1 = np.asarray(uv_b, dtype=np.float64)
|
||||
system = np.vstack(
|
||||
[
|
||||
u0 * a[2] - a[0],
|
||||
v0 * a[2] - a[1],
|
||||
u1 * b[2] - b[0],
|
||||
v1 * b[2] - b[1],
|
||||
]
|
||||
)
|
||||
_, _, vh = np.linalg.svd(system)
|
||||
return _normalize_homogeneous(vh[-1])
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrackCache:
|
||||
ttl_ns: int
|
||||
tracks: dict[str, TriangulatedPoint] = field(default_factory=dict)
|
||||
|
||||
def update(self, point: TriangulatedPoint) -> None:
|
||||
current = self.tracks.get(point.marker_id)
|
||||
if current is None or point.timestamp_ns >= current.timestamp_ns or point.confidence > current.confidence:
|
||||
self.tracks[point.marker_id] = point
|
||||
|
||||
def expire(self, now_ns: int) -> None:
|
||||
expired = [key for key, value in self.tracks.items() if now_ns - value.timestamp_ns > self.ttl_ns]
|
||||
for key in expired:
|
||||
del self.tracks[key]
|
||||
|
||||
def points(self) -> tuple[TriangulatedPoint, ...]:
|
||||
return tuple(sorted(self.tracks.values(), key=lambda item: item.marker_id))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PointCloud:
|
||||
points: tuple[TriangulatedPoint, ...]
|
||||
|
||||
def write_ply(self, path: Path) -> None:
|
||||
lines = [
|
||||
"ply",
|
||||
"format ascii 1.0",
|
||||
f"element vertex {len(self.points)}",
|
||||
"property float x",
|
||||
"property float y",
|
||||
"property float z",
|
||||
"property uchar red",
|
||||
"property uchar green",
|
||||
"property uchar blue",
|
||||
"property float confidence",
|
||||
"end_header",
|
||||
]
|
||||
for point in self.points:
|
||||
shade = int(max(0, min(255, round(point.confidence * 255))))
|
||||
x, y, z = point.xyz
|
||||
lines.append(f"{x:.9f} {y:.9f} {z:.9f} {shade} {shade} 255 {point.confidence:.6f}")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def load_fusion_config(path: Path) -> SensorRig:
|
||||
return SensorRig.from_dict(json.loads(path.read_text(encoding="utf-8")))
|
||||
57
scripts/sensor_fusion.py
Normal file
57
scripts/sensor_fusion.py
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from localcast.sensor_fusion import Observation2D, PointCloud, TrackCache, load_fusion_config
|
||||
|
||||
|
||||
|
||||
def load_observations(path: Path) -> list[Observation2D]:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict):
|
||||
data = data.get("observations", [])
|
||||
return [Observation2D.from_dict(item) for item in data]
|
||||
|
||||
|
||||
def fuse_file(args) -> None:
|
||||
rig = load_fusion_config(Path(args.config))
|
||||
observations = load_observations(Path(args.observations))
|
||||
result = rig.fuse(observations)
|
||||
cache = TrackCache(ttl_ns=rig.config.cache_ttl_ns)
|
||||
for point in result.points:
|
||||
cache.update(point)
|
||||
if args.now_ns is not None:
|
||||
cache.expire(args.now_ns)
|
||||
cloud = PointCloud(cache.points())
|
||||
output = Path(args.output)
|
||||
cloud.write_ply(output)
|
||||
summary = {
|
||||
"output": str(output),
|
||||
"points": len(cloud.points),
|
||||
"dropped": list(result.dropped),
|
||||
}
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Build sparse point clouds from calibrated sensor observations.")
|
||||
sub = parser.add_subparsers(required=True)
|
||||
|
||||
p = sub.add_parser("fuse-file")
|
||||
p.add_argument("--config", default=str(ROOT / "config" / "sensor-fusion.example.json"))
|
||||
p.add_argument("--observations", required=True)
|
||||
p.add_argument("--output", required=True)
|
||||
p.add_argument("--now-ns", type=int)
|
||||
p.set_defaults(func=fuse_file)
|
||||
|
||||
args = parser.parse_args()
|
||||
args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -29,3 +29,4 @@
|
|||
{"ts": "2026-05-18T14:48:48+00:00", "type": "verification", "status": "ok", "note": "PS3 Eye frame-rate squeeze: OpenCV DirectShow indices are reliable only at default 640x480@30; FFmpeg DirectShow capture by device name negotiates high-rate modes. Both PS3 Eyes simultaneously delivered 320x240@60 with 300 frames per Eye over five seconds. Dual 640x480@60 works but settles around 54-56 fps per Eye. Requests above 60 fps through the installed PS3EyeDirectShow filter do not increase delivered frame rate."}
|
||||
{"ts": "2026-05-18T14:50:58+00:00", "type": "verification", "status": "partial", "note": "Audio profile updated for actual distributed rig: local Focusrite shielded cardioid and neighbor Focusrite shotgun are dialogue anchors; Kiyo/PS Eye mics are spatial/context sources. Local PortAudio/WASAPI probe: Scarlett input accepts 48 kHz and rejects 96 kHz; Scarlett output accepts 44.1 kHz and rejects 48/96 kHz, so ASIO/native Focusrite access must be checked before high-rate calibration."}
|
||||
{"ts": "2026-05-18T14:55:13+00:00", "type": "decision", "status": "ok", "note": "Audio field live output may use bounded buffering: latency is acceptable while delay/SRO estimates settle, but cache depth must converge toward real-time. Core audio code now has testable seams for buffers, latency policy, injectable capture/alignment/encoder/sink ports, and pipeline orchestration."}
|
||||
{"ts": "2026-05-18T14:57:32+00:00", "type": "decision", "status": "ok", "note": "Sensor-fusion sidecar starts with semantic observation authority: calibrated cameras plus timestamped 2D marker observations triangulate into cached 3D point claims, then lower to PLY/brush/splat packets. Capture adapters and render lowerings stay outside the pure fusion core so unit tests can inject synthetic cameras, frames, and observations."}
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ active_subgoals:
|
|||
- Decide whether an OBS source generator or plugin investigation is justified.
|
||||
- Evaluate the Ambisonic AquaSynth path as a separate synchronized multichannel audio pipeline; do not treat heterogeneous mic feeds as raw first-order ambisonic A-format without geometry, calibration, and a shared clock.
|
||||
- Build the six-microphone/two-speaker audio-field sidecar around the actual distributed camera/Focusrite clocks, explicit geometry, speaker calibration, bounded buffering, delay/SRO alignment, testable pipeline seams, and FOA AmbiX output.
|
||||
- Build the visual sensor-fusion sidecar around timestamped observations, calibrated sensor models, bounded track caches, sparse point-cloud output, and later brush/splat packet lowering.
|
||||
|
||||
research:
|
||||
ambisonic_aquasynth:
|
||||
|
|
@ -96,7 +97,7 @@ research:
|
|||
before adding RGB projection or Gaussian splat rendering. For a
|
||||
Dreams-like volumetric brushstroke look, keep the world model as truth and
|
||||
lower semantic scene claims into cached brush/splat packets under budget.
|
||||
gpu_fusion_splatting:
|
||||
gpu_fusion_splatting:
|
||||
summary: research/gpu-fusion-splatting/summary.md
|
||||
bibliography: research/gpu-fusion-splatting/bibliography.md
|
||||
key_decision: >
|
||||
|
|
@ -105,6 +106,14 @@ research:
|
|||
GPU-shaped observation and brush packet buffers, and CUDA/Vulkan/D3D
|
||||
splat rendering with minimal readback. CPU owns orchestration and
|
||||
semantics; kernels do not own calibration truth.
|
||||
sensor_fusion_architecture:
|
||||
summary: docs/sensor-fusion-architecture.md
|
||||
key_decision: >
|
||||
The visual world model begins as timestamped sensor observations and
|
||||
calibrated camera transforms, not render packets. The first sidecar keeps
|
||||
capture adapters, detection, triangulation, track caching, and point-cloud
|
||||
export as separate testable authorities. This follows the fractal-domain
|
||||
cache rule: semantic claims first, cached backend lowerings second.
|
||||
|
||||
current_status:
|
||||
summary: >
|
||||
|
|
@ -142,15 +151,21 @@ current_status:
|
|||
live input while delay/SRO estimates settle, but cache depth must converge
|
||||
toward real-time. Core audio modules now expose testable boundaries for
|
||||
buffering, latency convergence, injectable capture/alignment/encode/sink
|
||||
ports, and pipeline orchestration.
|
||||
ports, and pipeline orchestration. The first visual sensor-fusion sidecar is
|
||||
in place: `localcast.sensor_fusion.core` owns calibrated camera models,
|
||||
timestamped 2D observations, DLT triangulation, reprojection/confidence
|
||||
gating, a TTL track cache, and PLY point-cloud export; adapters own
|
||||
FFmpeg/raw-frame ingress; `scripts/sensor_fusion.py fuse-file` can turn an
|
||||
observation file into a sparse PLY. Unit tests inject synthetic cameras and
|
||||
frames so the core does not depend on live camera drivers.
|
||||
next_action: >
|
||||
Use FFmpeg DirectShow device names `PS3 Eye Universal` and `PS3 Eye
|
||||
Universal2` for PS3 Eye tracking capture at 320x240@60, then capture
|
||||
ChArUco intrinsics for DirectShow indices 1-4. If more than 60 fps is still
|
||||
required, patch/rebuild PS3EyeDirectShow rather than asking OpenCV for a
|
||||
mode the installed filter does not expose. In parallel, create local
|
||||
config/audio-field.json, confirm local Kiyo/PS Eye/Focusrite device matches,
|
||||
confirm the neighbor Focusrite shotgun capture/transport path, replace
|
||||
placeholder mic/speaker geometry with measured world coordinates, then build
|
||||
the delay/SRO alignment stage that feeds the bounded field cache and emits
|
||||
aligned six-channel blocks for FOA encoding.
|
||||
Capture real ChArUco intrinsics/extrinsics for the PS3 Eyes and Kiyos,
|
||||
replace `config/sensor-fusion.example.json` placeholder transforms with a
|
||||
local `config/sensor-fusion.json`, then add a detector adapter that turns
|
||||
FFmpeg PS3 Eye frames into marker `Observation2D` records for the fusion
|
||||
core. In parallel, create local `config/audio-field.json`, confirm local
|
||||
Kiyo/PS Eye/Focusrite device matches, confirm the neighbor Focusrite
|
||||
shotgun capture/transport path, replace placeholder mic/speaker geometry
|
||||
with measured world coordinates, then build the delay/SRO alignment stage
|
||||
that feeds the bounded field cache and emits aligned six-channel blocks for
|
||||
FOA encoding.
|
||||
|
|
|
|||
117
tests/test_sensor_fusion.py
Normal file
117
tests/test_sensor_fusion.py
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import io
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from localcast.sensor_fusion import CameraModel, FusionConfig, Observation2D, PointCloud, SensorRig, TrackCache
|
||||
from localcast.sensor_fusion.adapters import read_raw_bgr_frames
|
||||
|
||||
|
||||
def camera(sensor_id, x):
|
||||
return CameraModel(
|
||||
sensor_id=sensor_id,
|
||||
camera_matrix=np.array([[300.0, 0.0, 160.0], [0.0, 300.0, 120.0], [0.0, 0.0, 1.0]]),
|
||||
dist_coeffs=np.zeros(5),
|
||||
world_from_sensor=np.array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, x],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
]
|
||||
),
|
||||
width=320,
|
||||
height=240,
|
||||
)
|
||||
|
||||
|
||||
class SensorFusionTests(unittest.TestCase):
|
||||
def test_triangulates_marker_from_two_calibrated_cameras(self):
|
||||
left = camera("left", -0.25)
|
||||
right = camera("right", 0.25)
|
||||
rig = SensorRig(
|
||||
cameras={"left": left, "right": right},
|
||||
config=FusionConfig(max_pair_dt_ns=30_000_000, max_reprojection_error_px=0.01),
|
||||
)
|
||||
target = np.array([0.05, 0.02, 2.0])
|
||||
observations = [
|
||||
Observation2D("left", "ball", 1_000_000_000, left.project_world(target), 0.9),
|
||||
Observation2D("right", "ball", 1_010_000_000, right.project_world(target), 0.8),
|
||||
]
|
||||
|
||||
result = rig.fuse(observations)
|
||||
|
||||
self.assertEqual(1, len(result.points))
|
||||
np.testing.assert_allclose(target, result.points[0].xyz, atol=1e-9)
|
||||
self.assertGreater(result.points[0].confidence, 0.5)
|
||||
|
||||
def test_rejects_observations_outside_time_window(self):
|
||||
left = camera("left", -0.25)
|
||||
right = camera("right", 0.25)
|
||||
rig = SensorRig(cameras={"left": left, "right": right}, config=FusionConfig(max_pair_dt_ns=5))
|
||||
target = np.array([0.0, 0.0, 2.0])
|
||||
|
||||
result = rig.fuse(
|
||||
[
|
||||
Observation2D("left", "ball", 10, left.project_world(target), 1.0),
|
||||
Observation2D("right", "ball", 100, right.project_world(target), 1.0),
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual(0, len(result.points))
|
||||
self.assertIn("ball: no valid camera pair", result.dropped)
|
||||
|
||||
def test_track_cache_expires_stale_points(self):
|
||||
left = camera("left", -0.25)
|
||||
right = camera("right", 0.25)
|
||||
target = np.array([0.0, 0.0, 2.0])
|
||||
point = SensorRig(
|
||||
cameras={"left": left, "right": right}
|
||||
).fuse(
|
||||
[
|
||||
Observation2D("left", "ball", 100, left.project_world(target), 1.0),
|
||||
Observation2D("right", "ball", 100, right.project_world(target), 1.0),
|
||||
]
|
||||
).points[0]
|
||||
cache = TrackCache(ttl_ns=50)
|
||||
|
||||
cache.update(point)
|
||||
cache.expire(120)
|
||||
self.assertEqual(1, len(cache.points()))
|
||||
cache.expire(200)
|
||||
self.assertEqual(0, len(cache.points()))
|
||||
|
||||
def test_point_cloud_writes_ply(self):
|
||||
left = camera("left", -0.25)
|
||||
right = camera("right", 0.25)
|
||||
point = SensorRig(cameras={"left": left, "right": right}).fuse(
|
||||
[
|
||||
Observation2D("left", "ball", 100, left.project_world(np.array([0.0, 0.0, 2.0])), 1.0),
|
||||
Observation2D("right", "ball", 100, right.project_world(np.array([0.0, 0.0, 2.0])), 1.0),
|
||||
]
|
||||
).points[0]
|
||||
class MemoryPath:
|
||||
parent = None
|
||||
|
||||
def __init__(self):
|
||||
self.text = ""
|
||||
|
||||
def write_text(self, text, encoding):
|
||||
self.text = text
|
||||
|
||||
sink = MemoryPath()
|
||||
sink.parent = type("Parent", (), {"mkdir": lambda self, parents, exist_ok: None})()
|
||||
PointCloud((point,)).write_ply(sink)
|
||||
self.assertIn("element vertex 1", sink.text)
|
||||
self.assertIn("end_header", sink.text)
|
||||
|
||||
def test_raw_bgr_reader_emits_timestamped_frames(self):
|
||||
stream = io.BytesIO(bytes(range(12)))
|
||||
frames = list(read_raw_bgr_frames(stream, "eye", width=2, height=2, frame_bytes=12))
|
||||
self.assertEqual(1, len(frames))
|
||||
self.assertEqual("eye", frames[0].sensor_id)
|
||||
self.assertEqual((2, 2, 3), frames[0].image_bgr.shape)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue