Document anonymized videos and publish SDK-free processor
Browse files- README.md +20 -9
- processing_code/processor.py +30 -21
- processing_code/requirements.txt +0 -5
- processing_code/utils/extract_camera_data.py +64 -172
- processing_code/utils/extract_dji_data.py +3 -4
- processing_code/utils/sync_timestamps.py +507 -496
README.md
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
---
|
| 2 |
pretty_name: GRADE Raw Multimodal Dataset
|
|
|
|
| 3 |
---
|
| 4 |
|
| 5 |
# GRADE dataset
|
| 6 |
|
| 7 |
This dataset release contains raw recordings for **GRADE: Single-Frame Generative Radar Depth Estimation Under Visual Degradation**, accepted to **ACM MobiCom 2026**. See the [paper](https://arxiv.org/abs/2609.10756) and [project website](https://phi-lab-rice.github.io/GRADE/).
|
| 8 |
|
| 9 |
-
The recordings were made with a TI IWR1843BOOST radar (with DCA1000EVM), a ZED 2i stereo camera, and a DJI Action 5 Pro camera. Evaluation sequences also used a MAX30105 smoke sensor. **
|
| 10 |
|
| 11 |
## Folders and splits
|
| 12 |
|
|
@@ -18,7 +19,7 @@ processing_code/ processor.py, requirements.txt, and utils/
|
|
| 18 |
|
| 19 |
**Split rule:** Within `GRADE_Train_Raw`, the 10 folders with `Dell` or `Keck` in their names are for **validation**, not model training. This includes the `Smoke-Dell-*` and `Smoke-keck-*` folders. The other 40 folders are for **training**. All 20 folders in `GRADE_Eval_Raw` are for **evaluation**. Do not treat every folder under `GRADE_Train_Raw` as training data.
|
| 20 |
|
| 21 |
-
Each sequence folder
|
| 22 |
|
| 23 |
```text
|
| 24 |
radar_*.h5 raw radar samples and timestamps
|
|
@@ -29,24 +30,34 @@ max30105_*.h5 MAX30105 samples and timestamps (evaluation only)
|
|
| 29 |
|
| 30 |
Training sequences have no MAX30105 file. The processor handles that automatically.
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
## Process a sequence
|
| 33 |
|
| 34 |
-
`processing_code/processor.py` matches the sensor timestamps and saves one output folder per sequence. `processing_code/utils/` contains the sensor extractors, radar processing, synchronization, and point-cloud code.
|
| 35 |
|
| 36 |
-
1.
|
| 37 |
-
2. From this repository's root folder, create a Python environment and install the dependencies:
|
| 38 |
|
| 39 |
```bash
|
| 40 |
python3.12 -m venv .venv
|
| 41 |
source .venv/bin/activate
|
| 42 |
python -m pip install -r processing_code/requirements.txt
|
| 43 |
-
python /usr/local/zed/get_python_api.py
|
| 44 |
-
python -c 'import pyzed.sl as sl; print(sl.Camera.get_sdk_version())'
|
| 45 |
```
|
| 46 |
|
| 47 |
-
|
| 48 |
|
| 49 |
-
|
| 50 |
|
| 51 |
```bash
|
| 52 |
python processing_code/processor.py \
|
|
|
|
| 1 |
---
|
| 2 |
pretty_name: GRADE Raw Multimodal Dataset
|
| 3 |
+
viewer: false
|
| 4 |
---
|
| 5 |
|
| 6 |
# GRADE dataset
|
| 7 |
|
| 8 |
This dataset release contains raw recordings for **GRADE: Single-Frame Generative Radar Depth Estimation Under Visual Degradation**, accepted to **ACM MobiCom 2026**. See the [paper](https://arxiv.org/abs/2609.10756) and [project website](https://phi-lab-rice.github.io/GRADE/).
|
| 9 |
|
| 10 |
+
The recordings were made with a TI IWR1843BOOST radar (with DCA1000EVM), a ZED 2i stereo camera, and a DJI Action 5 Pro camera. Evaluation sequences also used a MAX30105 smoke sensor. **All 70 public sequences now include anonymized ZED and DJI RGB videos.** The original ZED SVO2 and DJI recordings are not published.
|
| 11 |
|
| 12 |
## Folders and splits
|
| 13 |
|
|
|
|
| 19 |
|
| 20 |
**Split rule:** Within `GRADE_Train_Raw`, the 10 folders with `Dell` or `Keck` in their names are for **validation**, not model training. This includes the `Smoke-Dell-*` and `Smoke-keck-*` folders. The other 40 folders are for **training**. All 20 folders in `GRADE_Eval_Raw` are for **evaluation**. Do not treat every folder under `GRADE_Train_Raw` as training data.
|
| 21 |
|
| 22 |
+
Each sequence folder contains these timestamp and radar files:
|
| 23 |
|
| 24 |
```text
|
| 25 |
radar_*.h5 raw radar samples and timestamps
|
|
|
|
| 30 |
|
| 31 |
Training sequences have no MAX30105 file. The processor handles that automatically.
|
| 32 |
|
| 33 |
+
Each sequence folder on the Hub also has:
|
| 34 |
+
|
| 35 |
+
```text
|
| 36 |
+
zed_video_anonymized.mkv calibrated rectified-left ZED RGB, defaced, 1280x720
|
| 37 |
+
dji_video_anonymized.mkv fisheye-corrected and cropped DJI RGB, defaced, 1280x720
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Both videos use **lossy H.265/HEVC Main profile at CRF 14**, with 8-bit YUV 4:2:0 pixels in Matroska. Faces were blurred before this encoding. The original anonymized lossless RGB files were used as the transcoding inputs. Three original DJI recordings (`brk-2`, `brk-3`, and `brk-basement`) have 8, 3, and 6 untimed terminal video frames, respectively. Their anonymized videos omit those frames during CRF encoding, so every released DJI frame has a matching entry in its original DJI timestamp H5. No timestamps were removed from the H5 files.
|
| 41 |
+
|
| 42 |
+
The SDK-free processor also requires `zed_depth.h5`: full-frame ZED depth aligned with the ZED RGB video at 1280×720. **This depth file has not yet been uploaded to the Hub.** The local prepared file has a `depth_mm` dataset of shape `(frames, 720, 1280)`, dtype `uint16`, with no HDF5 compression, matching the radar H5 compression setting. Zero marks invalid depth; positive values are millimeters rounded to 1 mm. Depth was computed from the original SVO2 before RGB face blurring. The ZED camera clock is `camera_timestamps_*.h5`; there is no separate SVO2 timestamp file. Frame index `i` in that H5 corresponds to frame `i` in the ZED video and depth H5, up to the exported frame count. The processor trims surplus terminal timestamps to that count.
|
| 43 |
+
|
| 44 |
+
The local preparation folders retain the original DJI recordings and ZED SVO2 files for preservation. **Do not include those originals in a public upload.**
|
| 45 |
+
|
| 46 |
## Process a sequence
|
| 47 |
|
| 48 |
+
`processing_code/processor.py` first matches the H5 sensor timestamps, then extracts synchronized radar, ZED RGB/depth, and DJI RGB frames. It saves one output folder per sequence. `processing_code/utils/` contains the sensor extractors, radar processing, synchronization, and point-cloud code. The processor requires both anonymized videos and the matching `zed_depth.h5`; because the depth H5 is not on the Hub yet, the current public download alone cannot run the full camera pipeline.
|
| 49 |
|
| 50 |
+
1. From this repository's root folder, create a Python environment and install the dependencies:
|
|
|
|
| 51 |
|
| 52 |
```bash
|
| 53 |
python3.12 -m venv .venv
|
| 54 |
source .venv/bin/activate
|
| 55 |
python -m pip install -r processing_code/requirements.txt
|
|
|
|
|
|
|
| 56 |
```
|
| 57 |
|
| 58 |
+
The public processor does not require the ZED SDK or an NVIDIA GPU. It uses OpenCV to decode the HEVC videos and h5py to read precomputed metric depth.
|
| 59 |
|
| 60 |
+
2. Process one evaluation sequence after its prepared camera files are available:
|
| 61 |
|
| 62 |
```bash
|
| 63 |
python processing_code/processor.py \
|
processing_code/processor.py
CHANGED
|
@@ -14,7 +14,6 @@ from utils.sync_timestamps import (
|
|
| 14 |
synchronize_timestamps_3way,
|
| 15 |
save_sync_csv,
|
| 16 |
_pick_latest_file,
|
| 17 |
-
_pick_latest_file_multi_ext,
|
| 18 |
SyncResult3Way,
|
| 19 |
)
|
| 20 |
from utils.extract_camera_data import extract_camera_data
|
|
@@ -108,7 +107,7 @@ def save_processed_optimized(
|
|
| 108 |
|
| 109 |
File structure:
|
| 110 |
- radar.npy: Radar data (complex64)
|
| 111 |
-
- dji_rgb.npy: DJI RGB (N, 504, 896, 3) uint8, resized from
|
| 112 |
- zed_rgb.npy: ZED RGB (N, 504, 896, 3) uint8, resized from original
|
| 113 |
- zed_depth.npy: ZED depth (uint16 millimeters)
|
| 114 |
- metadata.json: Shapes, dtypes, timestamps, sync indices, and other metadata
|
|
@@ -153,7 +152,7 @@ def save_processed_optimized(
|
|
| 153 |
if log:
|
| 154 |
log.info(f" Radar: {radar_cube.shape} {radar_cube.dtype} -> {radar_filename}")
|
| 155 |
|
| 156 |
-
# Save DJI RGB
|
| 157 |
if dji_rgb is not None:
|
| 158 |
dji_rgb_resized = _resize_rgb_to(dji_rgb, (896, 504), log=log)
|
| 159 |
dji_path = os.path.join(output_dir, "dji_rgb.npy")
|
|
@@ -191,7 +190,7 @@ def save_processed_optimized(
|
|
| 191 |
if zed_timestamps is not None:
|
| 192 |
meta_dict["zed_rgb"]["timestamps_ms"] = [float(t) for t in zed_timestamps]
|
| 193 |
if log:
|
| 194 |
-
log.info(f" ZED RGB: {zed_rgb.shape} {zed_rgb.dtype}
|
| 195 |
|
| 196 |
# Save ZED depth as uint16 npy
|
| 197 |
if zed_depth_mm is not None:
|
|
@@ -277,8 +276,6 @@ def process_sequence(
|
|
| 277 |
# Fixed parameters
|
| 278 |
tolerance_ms = 50.0
|
| 279 |
enforce_one_to_one = True
|
| 280 |
-
depth_confidence = 100
|
| 281 |
-
depth_texture_confidence = 100
|
| 282 |
|
| 283 |
log.info("="*80)
|
| 284 |
log.info(f"Processing sequence: {sequence_dir}")
|
|
@@ -306,13 +303,15 @@ def process_sequence(
|
|
| 306 |
log.info(f"Scanning directory: {sequence_dir}")
|
| 307 |
radar_h5 = _pick_latest_file(sequence_dir, "radar_*.h5")
|
| 308 |
zed_timestamps_h5 = _pick_latest_file(sequence_dir, "camera_timestamps_*.h5")
|
| 309 |
-
|
|
|
|
| 310 |
dji_timestamps_h5 = _pick_latest_file(sequence_dir, "dji_timestamps_*.h5")
|
| 311 |
-
dji_video_path =
|
| 312 |
|
| 313 |
log.info(f"Radar H5: {radar_h5}")
|
| 314 |
log.info(f"ZED timestamps: {zed_timestamps_h5}")
|
| 315 |
-
log.info(f"ZED
|
|
|
|
| 316 |
log.info(f"DJI timestamps: {dji_timestamps_h5}")
|
| 317 |
log.info(f"DJI video: {dji_video_path}")
|
| 318 |
|
|
@@ -321,6 +320,16 @@ def process_sequence(
|
|
| 321 |
output_dir = os.path.join(base_output_dir, sequence_basename)
|
| 322 |
os.makedirs(output_dir, exist_ok=True)
|
| 323 |
log.info(f"Output directory: {output_dir}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
# Step 1: Synchronize timestamps (3-way)
|
| 326 |
log.info("Synchronizing timestamps (3-way: radar + ZED + DJI)...")
|
|
@@ -332,8 +341,8 @@ def process_sequence(
|
|
| 332 |
dji_timestamps_h5=dji_timestamps_h5,
|
| 333 |
tolerance_ms=tolerance_ms,
|
| 334 |
enforce_one_to_one=enforce_one_to_one,
|
| 335 |
-
|
| 336 |
-
|
| 337 |
)
|
| 338 |
except (OSError, ValueError) as e:
|
| 339 |
err = f"Timestamp file corrupt or truncated: {e}"
|
|
@@ -436,13 +445,11 @@ def process_sequence(
|
|
| 436 |
|
| 437 |
# Step 3: Extract ZED RGB and depth
|
| 438 |
if not no_camera:
|
| 439 |
-
log.info(f"Extracting {len(zed_indices)} ZED RGB+depth frames from
|
| 440 |
zed_rgb, zed_depth_mm, _intrinsics = extract_camera_data(
|
| 441 |
-
|
|
|
|
| 442 |
frame_indices=zed_indices,
|
| 443 |
-
depth_mode="NEURAL_PLUS",
|
| 444 |
-
confidence_threshold=depth_confidence,
|
| 445 |
-
texture_confidence_threshold=depth_texture_confidence,
|
| 446 |
)
|
| 447 |
log.info(f"ZED RGB shape: {zed_rgb.shape}, dtype: {zed_rgb.dtype}")
|
| 448 |
log.info(f"ZED depth shape: {zed_depth_mm.shape}, dtype: {zed_depth_mm.dtype}")
|
|
@@ -467,8 +474,9 @@ def process_sequence(
|
|
| 467 |
'sequence_dir': sequence_dir,
|
| 468 |
'tolerance_ms': tolerance_ms,
|
| 469 |
'enforce_one_to_one': enforce_one_to_one,
|
| 470 |
-
'depth_confidence':
|
| 471 |
-
'depth_texture_confidence':
|
|
|
|
| 472 |
'no_doppler': no_doppler,
|
| 473 |
}
|
| 474 |
|
|
@@ -515,9 +523,10 @@ def main(
|
|
| 515 |
1. Auto-detect files in sequence directory:
|
| 516 |
- radar_*.h5 (AWR1843 MIMO radar)
|
| 517 |
- camera_timestamps_*.h5 (ZED camera timestamps)
|
| 518 |
-
-
|
|
|
|
| 519 |
- dji_timestamps_*.h5 (DJI action camera timestamps)
|
| 520 |
-
-
|
| 521 |
|
| 522 |
2. Synchronize timestamps (3-way: radar + ZED + DJI)
|
| 523 |
- tolerance_ms: 50ms (fixed)
|
|
@@ -531,7 +540,7 @@ def main(
|
|
| 531 |
Output saved to: <output_dir>/<sequence_name>/
|
| 532 |
- radar.npy: Full Range-Doppler-Angle radar data (complex64)
|
| 533 |
- radar_no_doppler.npy: First-chirp Range-Angle data (--no-doppler)
|
| 534 |
-
- dji_rgb.npy: DJI RGB (N, 504, 896, 3) uint8, resized from
|
| 535 |
- zed_rgb.npy: ZED RGB (N, 504, 896, 3) uint8, resized from original
|
| 536 |
- zed_depth.npy: ZED depth (uint16 millimeters)
|
| 537 |
- max30105.npy: MAX30105 samples_uint32 aligned to radar timestamps
|
|
|
|
| 14 |
synchronize_timestamps_3way,
|
| 15 |
save_sync_csv,
|
| 16 |
_pick_latest_file,
|
|
|
|
| 17 |
SyncResult3Way,
|
| 18 |
)
|
| 19 |
from utils.extract_camera_data import extract_camera_data
|
|
|
|
| 107 |
|
| 108 |
File structure:
|
| 109 |
- radar.npy: Radar data (complex64)
|
| 110 |
+
- dji_rgb.npy: DJI RGB (N, 504, 896, 3) uint8, resized from prepared 1280x720
|
| 111 |
- zed_rgb.npy: ZED RGB (N, 504, 896, 3) uint8, resized from original
|
| 112 |
- zed_depth.npy: ZED depth (uint16 millimeters)
|
| 113 |
- metadata.json: Shapes, dtypes, timestamps, sync indices, and other metadata
|
|
|
|
| 152 |
if log:
|
| 153 |
log.info(f" Radar: {radar_cube.shape} {radar_cube.dtype} -> {radar_filename}")
|
| 154 |
|
| 155 |
+
# Save prepared 1280x720 DJI RGB at the historical 896x504 output size.
|
| 156 |
if dji_rgb is not None:
|
| 157 |
dji_rgb_resized = _resize_rgb_to(dji_rgb, (896, 504), log=log)
|
| 158 |
dji_path = os.path.join(output_dir, "dji_rgb.npy")
|
|
|
|
| 190 |
if zed_timestamps is not None:
|
| 191 |
meta_dict["zed_rgb"]["timestamps_ms"] = [float(t) for t in zed_timestamps]
|
| 192 |
if log:
|
| 193 |
+
log.info(f" ZED RGB: {zed_rgb.shape} {zed_rgb.dtype} -> zed_rgb.npy")
|
| 194 |
|
| 195 |
# Save ZED depth as uint16 npy
|
| 196 |
if zed_depth_mm is not None:
|
|
|
|
| 276 |
# Fixed parameters
|
| 277 |
tolerance_ms = 50.0
|
| 278 |
enforce_one_to_one = True
|
|
|
|
|
|
|
| 279 |
|
| 280 |
log.info("="*80)
|
| 281 |
log.info(f"Processing sequence: {sequence_dir}")
|
|
|
|
| 303 |
log.info(f"Scanning directory: {sequence_dir}")
|
| 304 |
radar_h5 = _pick_latest_file(sequence_dir, "radar_*.h5")
|
| 305 |
zed_timestamps_h5 = _pick_latest_file(sequence_dir, "camera_timestamps_*.h5")
|
| 306 |
+
zed_video_path = _pick_latest_file(sequence_dir, "zed_video_anonymized.mkv")
|
| 307 |
+
zed_depth_h5 = _pick_latest_file(sequence_dir, "zed_depth.h5")
|
| 308 |
dji_timestamps_h5 = _pick_latest_file(sequence_dir, "dji_timestamps_*.h5")
|
| 309 |
+
dji_video_path = _pick_latest_file(sequence_dir, "dji_video_anonymized.mkv")
|
| 310 |
|
| 311 |
log.info(f"Radar H5: {radar_h5}")
|
| 312 |
log.info(f"ZED timestamps: {zed_timestamps_h5}")
|
| 313 |
+
log.info(f"ZED RGB video: {zed_video_path}")
|
| 314 |
+
log.info(f"ZED depth H5: {zed_depth_h5}")
|
| 315 |
log.info(f"DJI timestamps: {dji_timestamps_h5}")
|
| 316 |
log.info(f"DJI video: {dji_video_path}")
|
| 317 |
|
|
|
|
| 320 |
output_dir = os.path.join(base_output_dir, sequence_basename)
|
| 321 |
os.makedirs(output_dir, exist_ok=True)
|
| 322 |
log.info(f"Output directory: {output_dir}")
|
| 323 |
+
|
| 324 |
+
with h5py.File(zed_depth_h5, "r") as depth_file:
|
| 325 |
+
zed_frame_count = depth_file["depth_mm"].shape[0]
|
| 326 |
+
dji_capture = cv2.VideoCapture(dji_video_path)
|
| 327 |
+
try:
|
| 328 |
+
dji_frame_count = int(dji_capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 329 |
+
finally:
|
| 330 |
+
dji_capture.release()
|
| 331 |
+
if dji_frame_count <= 0:
|
| 332 |
+
raise ValueError(f"Could not read DJI frame count: {dji_video_path}")
|
| 333 |
|
| 334 |
# Step 1: Synchronize timestamps (3-way)
|
| 335 |
log.info("Synchronizing timestamps (3-way: radar + ZED + DJI)...")
|
|
|
|
| 341 |
dji_timestamps_h5=dji_timestamps_h5,
|
| 342 |
tolerance_ms=tolerance_ms,
|
| 343 |
enforce_one_to_one=enforce_one_to_one,
|
| 344 |
+
zed_frame_count=zed_frame_count,
|
| 345 |
+
dji_frame_count=dji_frame_count,
|
| 346 |
)
|
| 347 |
except (OSError, ValueError) as e:
|
| 348 |
err = f"Timestamp file corrupt or truncated: {e}"
|
|
|
|
| 445 |
|
| 446 |
# Step 3: Extract ZED RGB and depth
|
| 447 |
if not no_camera:
|
| 448 |
+
log.info(f"Extracting {len(zed_indices)} ZED RGB+depth frames from video and H5...")
|
| 449 |
zed_rgb, zed_depth_mm, _intrinsics = extract_camera_data(
|
| 450 |
+
rgb_video_path=zed_video_path,
|
| 451 |
+
depth_h5_path=zed_depth_h5,
|
| 452 |
frame_indices=zed_indices,
|
|
|
|
|
|
|
|
|
|
| 453 |
)
|
| 454 |
log.info(f"ZED RGB shape: {zed_rgb.shape}, dtype: {zed_rgb.dtype}")
|
| 455 |
log.info(f"ZED depth shape: {zed_depth_mm.shape}, dtype: {zed_depth_mm.dtype}")
|
|
|
|
| 474 |
'sequence_dir': sequence_dir,
|
| 475 |
'tolerance_ms': tolerance_ms,
|
| 476 |
'enforce_one_to_one': enforce_one_to_one,
|
| 477 |
+
'depth_confidence': 100,
|
| 478 |
+
'depth_texture_confidence': 100,
|
| 479 |
+
'zed_intrinsics_fx_fy_cx_cy': _intrinsics.tolist() if not no_camera else None,
|
| 480 |
'no_doppler': no_doppler,
|
| 481 |
}
|
| 482 |
|
|
|
|
| 523 |
1. Auto-detect files in sequence directory:
|
| 524 |
- radar_*.h5 (AWR1843 MIMO radar)
|
| 525 |
- camera_timestamps_*.h5 (ZED camera timestamps)
|
| 526 |
+
- zed_video_anonymized.mkv (rectified-left ZED RGB, HEVC Main CRF 14)
|
| 527 |
+
- zed_depth.h5 (aligned uint16-mm depth for every ZED frame)
|
| 528 |
- dji_timestamps_*.h5 (DJI action camera timestamps)
|
| 529 |
+
- dji_video_anonymized.mkv (HEVC Main CRF 14)
|
| 530 |
|
| 531 |
2. Synchronize timestamps (3-way: radar + ZED + DJI)
|
| 532 |
- tolerance_ms: 50ms (fixed)
|
|
|
|
| 540 |
Output saved to: <output_dir>/<sequence_name>/
|
| 541 |
- radar.npy: Full Range-Doppler-Angle radar data (complex64)
|
| 542 |
- radar_no_doppler.npy: First-chirp Range-Angle data (--no-doppler)
|
| 543 |
+
- dji_rgb.npy: DJI RGB (N, 504, 896, 3) uint8, resized from prepared 1280x720
|
| 544 |
- zed_rgb.npy: ZED RGB (N, 504, 896, 3) uint8, resized from original
|
| 545 |
- zed_depth.npy: ZED depth (uint16 millimeters)
|
| 546 |
- max30105.npy: MAX30105 samples_uint32 aligned to radar timestamps
|
processing_code/requirements.txt
CHANGED
|
@@ -5,8 +5,3 @@ h5py>=3.10
|
|
| 5 |
tyro>=0.8
|
| 6 |
rich>=13.0
|
| 7 |
tqdm>=4.66
|
| 8 |
-
|
| 9 |
-
# ZED SDK requirement (not installed through pip):
|
| 10 |
-
# Install the Stereolabs ZED SDK for your platform, including its Python API.
|
| 11 |
-
# It must make `import pyzed.sl` work in the Python environment used here.
|
| 12 |
-
# Download: https://www.stereolabs.com/developers/release/
|
|
|
|
| 5 |
tyro>=0.8
|
| 6 |
rich>=13.0
|
| 7 |
tqdm>=4.66
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
processing_code/utils/extract_camera_data.py
CHANGED
|
@@ -1,172 +1,64 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
from typing import Iterable, Tuple
|
| 4 |
-
|
| 5 |
-
import cv2
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
from tqdm import tqdm
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
init.depth_mode = getattr(sl.DEPTH_MODE, depth_mode.upper().replace(" ", "_"), sl.DEPTH_MODE.NEURAL)
|
| 66 |
-
init.coordinate_units = sl.UNIT.MILLIMETER # depth in millimeters
|
| 67 |
-
|
| 68 |
-
zed = sl.Camera()
|
| 69 |
-
status = zed.open(init)
|
| 70 |
-
if status != sl.ERROR_CODE.SUCCESS:
|
| 71 |
-
raise RuntimeError(f"Failed to open SVO: {status}")
|
| 72 |
-
|
| 73 |
-
log.info(f"Opened SVO with depth mode: {depth_mode}")
|
| 74 |
-
|
| 75 |
-
# Validate camera calibration and resolution to ensure 1:1 RGB-Depth alignment
|
| 76 |
-
cam_info = zed.get_camera_information()
|
| 77 |
-
resolution = cam_info.camera_configuration.resolution
|
| 78 |
-
calib = cam_info.camera_configuration.calibration_parameters.left_cam
|
| 79 |
-
|
| 80 |
-
log.info(f"Camera resolution: {resolution.width}x{resolution.height}")
|
| 81 |
-
log.info(f"Left camera calibration - fx={calib.fx:.2f}, fy={calib.fy:.2f}, cx={calib.cx:.2f}, cy={calib.cy:.2f}")
|
| 82 |
-
intrinsics = np.array(
|
| 83 |
-
[calib.fx, calib.fy, calib.cx, calib.cy],
|
| 84 |
-
dtype=np.float32,
|
| 85 |
-
)
|
| 86 |
-
|
| 87 |
-
# Configure runtime parameters for depth estimation
|
| 88 |
-
runtime_params = sl.RuntimeParameters()
|
| 89 |
-
runtime_params.confidence_threshold = confidence_threshold
|
| 90 |
-
runtime_params.texture_confidence_threshold = texture_confidence_threshold
|
| 91 |
-
log.info(f"Depth confidence thresholds: confidence={confidence_threshold}, texture={texture_confidence_threshold}")
|
| 92 |
-
|
| 93 |
-
num_frames_svo = zed.get_svo_number_of_frames()
|
| 94 |
-
log.info(f"SVO contains {num_frames_svo} frames")
|
| 95 |
-
log.info(f"Extracting {len(indices)} frame indices (min={indices.min()}, max={indices.max()})")
|
| 96 |
-
|
| 97 |
-
# Convert indices to a set for O(1) lookup
|
| 98 |
-
indices_set = set(indices.tolist())
|
| 99 |
-
|
| 100 |
-
rgb_frames: list[np.ndarray] = []
|
| 101 |
-
depth_frames: list[np.ndarray] = []
|
| 102 |
-
|
| 103 |
-
image_left = sl.Mat()
|
| 104 |
-
depth_mat = sl.Mat()
|
| 105 |
-
|
| 106 |
-
try:
|
| 107 |
-
# Loop through all frames in SVO sequentially
|
| 108 |
-
# We must process sequentially because SVO cannot seek randomly
|
| 109 |
-
extracted_count = 0
|
| 110 |
-
first_frame_validated = False
|
| 111 |
-
|
| 112 |
-
with tqdm(total=len(indices), desc="ZED camera extraction", unit="frame") as pbar:
|
| 113 |
-
for frame_idx in range(num_frames_svo):
|
| 114 |
-
# Grab the next frame from SVO
|
| 115 |
-
grab_status = zed.grab(runtime_params)
|
| 116 |
-
if grab_status != sl.ERROR_CODE.SUCCESS:
|
| 117 |
-
# End of file or error
|
| 118 |
-
log.warning(f"Grab failed at frame {frame_idx}: {grab_status}")
|
| 119 |
-
break
|
| 120 |
-
|
| 121 |
-
# Always retrieve RGB and depth after grab() to keep SDK state clean
|
| 122 |
-
# RGB: LEFT view (rectified)
|
| 123 |
-
zed.retrieve_image(image_left, sl.VIEW.LEFT)
|
| 124 |
-
bgra = image_left.get_data() # (H, W, 4) uint8 - ZED SDK returns BGRA
|
| 125 |
-
rgb = cv2.cvtColor(bgra, cv2.COLOR_BGRA2RGB) # (H, W, 3) uint8
|
| 126 |
-
|
| 127 |
-
# Depth (millimeters) - should match RGB resolution
|
| 128 |
-
zed.retrieve_measure(depth_mat, sl.MEASURE.DEPTH)
|
| 129 |
-
depth = depth_mat.get_data() # (H, W) or (H, W, 1) - ZED reuses this buffer
|
| 130 |
-
depth = np.asarray(depth, dtype=np.float32).squeeze().copy() # (H, W) float32, own copy to prevent buffer reuse issues
|
| 131 |
-
|
| 132 |
-
# Replace NaN values with 0 (invalid depth)
|
| 133 |
-
depth = np.nan_to_num(depth, nan=0.0)
|
| 134 |
-
|
| 135 |
-
# Validate 1:1 alignment on first frame
|
| 136 |
-
if not first_frame_validated:
|
| 137 |
-
if rgb.shape[:2] != depth.shape:
|
| 138 |
-
raise ValueError(
|
| 139 |
-
f"RGB-Depth dimension mismatch! RGB: {rgb.shape[:2]}, Depth: {depth.shape}. "
|
| 140 |
-
f"This indicates FOV alignment issues."
|
| 141 |
-
)
|
| 142 |
-
log.info(f"✓ Validated 1:1 RGB-Depth alignment: {rgb.shape[:2]}")
|
| 143 |
-
first_frame_validated = True
|
| 144 |
-
|
| 145 |
-
# Only keep this frame if it's in our desired indices
|
| 146 |
-
if frame_idx in indices_set:
|
| 147 |
-
rgb_frames.append(rgb)
|
| 148 |
-
depth_frames.append(depth)
|
| 149 |
-
extracted_count += 1
|
| 150 |
-
pbar.update(1)
|
| 151 |
-
if extracted_count == len(indices):
|
| 152 |
-
break
|
| 153 |
-
# If frame_idx not in indices_set, we skip this frame (don't append)
|
| 154 |
-
|
| 155 |
-
log.info(f"Finished: Extracted {extracted_count}/{len(indices)} frames from {num_frames_svo} total frames")
|
| 156 |
-
finally:
|
| 157 |
-
zed.close()
|
| 158 |
-
|
| 159 |
-
if not rgb_frames:
|
| 160 |
-
log.warning("No frames were extracted!")
|
| 161 |
-
return (
|
| 162 |
-
np.empty((0, 0, 0, 3), dtype=np.uint8),
|
| 163 |
-
np.empty((0, 0), dtype=np.float32),
|
| 164 |
-
intrinsics,
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
rgb_arr = np.stack(rgb_frames, axis=0)
|
| 168 |
-
depth_arr = np.stack(depth_frames, axis=0)
|
| 169 |
-
|
| 170 |
-
log.info(f"Final arrays - RGB: {rgb_arr.shape}, Depth: {depth_arr.shape}")
|
| 171 |
-
|
| 172 |
-
return rgb_arr, depth_arr, intrinsics
|
|
|
|
| 1 |
+
"""Load aligned ZED RGB and metric depth without the ZED SDK."""
|
| 2 |
+
|
| 3 |
+
from typing import Iterable, Tuple
|
| 4 |
+
|
| 5 |
+
import cv2
|
| 6 |
+
import h5py
|
| 7 |
+
import numpy as np
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def extract_camera_data(
|
| 12 |
+
rgb_video_path: str,
|
| 13 |
+
depth_h5_path: str,
|
| 14 |
+
frame_indices: Iterable[int],
|
| 15 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 16 |
+
"""Return selected rectified-left RGB frames and aligned uint16-mm depth.
|
| 17 |
+
|
| 18 |
+
Frame index zero is the first frame in both files. Depth zero means invalid.
|
| 19 |
+
"""
|
| 20 |
+
indices = np.unique(np.asarray(list(frame_indices), dtype=np.int64))
|
| 21 |
+
if indices.size == 0:
|
| 22 |
+
return (np.empty((0, 0, 0, 3), dtype=np.uint8),
|
| 23 |
+
np.empty((0, 0, 0), dtype=np.uint16),
|
| 24 |
+
np.empty(4, dtype=np.float32))
|
| 25 |
+
if indices[0] < 0:
|
| 26 |
+
raise ValueError("ZED frame indices must be nonnegative")
|
| 27 |
+
|
| 28 |
+
with h5py.File(depth_h5_path, "r") as f:
|
| 29 |
+
if "depth_mm" not in f:
|
| 30 |
+
raise ValueError(f"Missing depth_mm dataset: {depth_h5_path}")
|
| 31 |
+
depth = f["depth_mm"]
|
| 32 |
+
if depth.ndim != 3 or depth.dtype != np.uint16:
|
| 33 |
+
raise ValueError("depth_mm must have shape (frames, height, width) and dtype uint16")
|
| 34 |
+
frame_count, height, width = depth.shape
|
| 35 |
+
if indices[-1] >= frame_count:
|
| 36 |
+
raise ValueError(f"ZED index {indices[-1]} exceeds {frame_count} depth frames")
|
| 37 |
+
intrinsics = np.asarray(f.attrs["intrinsics_fx_fy_cx_cy"], dtype=np.float32)
|
| 38 |
+
if intrinsics.shape != (4,):
|
| 39 |
+
raise ValueError("Invalid ZED intrinsics")
|
| 40 |
+
|
| 41 |
+
cap = cv2.VideoCapture(rgb_video_path)
|
| 42 |
+
if not cap.isOpened():
|
| 43 |
+
raise RuntimeError(f"Could not open ZED RGB video: {rgb_video_path}")
|
| 44 |
+
try:
|
| 45 |
+
video_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 46 |
+
if video_count > 0 and video_count != frame_count:
|
| 47 |
+
raise ValueError(f"ZED RGB/depth frame count differs: {video_count} vs {frame_count}")
|
| 48 |
+
if (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
|
| 49 |
+
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) != (width, height):
|
| 50 |
+
raise ValueError("ZED RGB/depth resolution differs")
|
| 51 |
+
rgb_frames = []
|
| 52 |
+
depth_frames = []
|
| 53 |
+
wanted = set(indices.tolist())
|
| 54 |
+
for frame_idx in tqdm(range(int(indices[-1]) + 1), desc="ZED extraction", unit="frame"):
|
| 55 |
+
ok, bgr = cap.read()
|
| 56 |
+
if not ok:
|
| 57 |
+
raise ValueError(f"ZED RGB video ends before frame {frame_idx}")
|
| 58 |
+
if frame_idx in wanted:
|
| 59 |
+
rgb_frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
|
| 60 |
+
depth_frames.append(depth[frame_idx])
|
| 61 |
+
finally:
|
| 62 |
+
cap.release()
|
| 63 |
+
|
| 64 |
+
return np.stack(rgb_frames), np.stack(depth_frames), intrinsics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
processing_code/utils/extract_dji_data.py
CHANGED
|
@@ -14,18 +14,17 @@ def extract_dji_rgb(
|
|
| 14 |
frame_indices: Iterable[int],
|
| 15 |
) -> np.ndarray:
|
| 16 |
"""
|
| 17 |
-
Extract selected RGB frames from
|
| 18 |
|
| 19 |
Parameters:
|
| 20 |
-
- video_path: path to the
|
| 21 |
- frame_indices: iterable of DJI frame indices to keep
|
| 22 |
(e.g. the `dji_frame_idx` column from `sync_triples.csv`).
|
| 23 |
|
| 24 |
Returns:
|
| 25 |
- rgb: array of shape (N, H, W, 3), dtype uint8, RGB frames.
|
| 26 |
|
| 27 |
-
|
| 28 |
-
additional transformations are needed here.
|
| 29 |
"""
|
| 30 |
if not os.path.exists(video_path):
|
| 31 |
raise FileNotFoundError(f"DJI video not found: {video_path}")
|
|
|
|
| 14 |
frame_indices: Iterable[int],
|
| 15 |
) -> np.ndarray:
|
| 16 |
"""
|
| 17 |
+
Extract selected RGB frames from the prepared DJI MKV.
|
| 18 |
|
| 19 |
Parameters:
|
| 20 |
+
- video_path: path to the rectified, 1280x720, defaced DJI video.
|
| 21 |
- frame_indices: iterable of DJI frame indices to keep
|
| 22 |
(e.g. the `dji_frame_idx` column from `sync_triples.csv`).
|
| 23 |
|
| 24 |
Returns:
|
| 25 |
- rgb: array of shape (N, H, W, 3), dtype uint8, RGB frames.
|
| 26 |
|
| 27 |
+
The release video is already rectified, cropped, resized, and defaced.
|
|
|
|
| 28 |
"""
|
| 29 |
if not os.path.exists(video_path):
|
| 30 |
raise FileNotFoundError(f"DJI video not found: {video_path}")
|
processing_code/utils/sync_timestamps.py
CHANGED
|
@@ -1,496 +1,507 @@
|
|
| 1 |
-
import numpy as np
|
| 2 |
-
import h5py
|
| 3 |
-
import logging
|
| 4 |
-
from dataclasses import dataclass
|
| 5 |
-
from typing import List, Tuple, Optional, Literal, Union
|
| 6 |
-
import os
|
| 7 |
-
import glob
|
| 8 |
-
import tyro
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
logging.
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
num_frames_attr
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
#
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
""
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
- `
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
]
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
log.info(f"Auto-picked camera timestamps: {camera_timestamps_h5}")
|
| 213 |
-
log.info(f"Auto-picked radar file: {radar_h5}")
|
| 214 |
-
log.info(f"Auto-picked
|
| 215 |
-
|
| 216 |
-
if camera_timestamps_h5 is None or radar_h5 is None:
|
| 217 |
-
raise ValueError(
|
| 218 |
-
"Provide either:\n"
|
| 219 |
-
"- directory=<folder containing camera_timestamps_*.h5 and radar_*.h5>, OR\n"
|
| 220 |
-
"- camera_timestamps_h5=<path> AND radar_h5=<path>."
|
| 221 |
-
)
|
| 222 |
-
|
| 223 |
-
result = synchronize_timestamps(
|
| 224 |
-
camera_timestamps_h5=camera_timestamps_h5,
|
| 225 |
-
radar_h5=radar_h5,
|
| 226 |
-
tolerance_ms=tolerance_ms,
|
| 227 |
-
enforce_one_to_one=enforce_one_to_one,
|
| 228 |
-
|
| 229 |
-
)
|
| 230 |
-
save_sync_csv(out_csv, result)
|
| 231 |
-
log.info(f"Wrote sync CSV: {out_csv}")
|
| 232 |
-
|
| 233 |
-
def _nearest_unused_camera_index(
|
| 234 |
-
cam_ts: np.ndarray,
|
| 235 |
-
target_t: float,
|
| 236 |
-
used_camera: set[int],
|
| 237 |
-
start_idx: int,
|
| 238 |
-
) -> Optional[int]:
|
| 239 |
-
"""
|
| 240 |
-
Find nearest unused camera index to `target_t`.
|
| 241 |
-
|
| 242 |
-
`start_idx` is the insertion index from `np.searchsorted(cam_ts, target_t)`.
|
| 243 |
-
We expand outward until we find an unused camera frame.
|
| 244 |
-
"""
|
| 245 |
-
left = start_idx - 1
|
| 246 |
-
right = start_idx
|
| 247 |
-
while left >= 0 or right < len(cam_ts):
|
| 248 |
-
cand_left = left if left >= 0 else None
|
| 249 |
-
cand_right = right if right < len(cam_ts) else None
|
| 250 |
-
|
| 251 |
-
if cand_left is None and cand_right is None:
|
| 252 |
-
return None
|
| 253 |
-
|
| 254 |
-
best: Optional[int] = None
|
| 255 |
-
best_abs = float("inf")
|
| 256 |
-
|
| 257 |
-
for cand in (cand_left, cand_right):
|
| 258 |
-
if cand is None:
|
| 259 |
-
continue
|
| 260 |
-
if cand in used_camera:
|
| 261 |
-
continue
|
| 262 |
-
abs_diff = abs(float(cam_ts[cand] - target_t))
|
| 263 |
-
if abs_diff < best_abs:
|
| 264 |
-
best_abs = abs_diff
|
| 265 |
-
best = int(cand)
|
| 266 |
-
|
| 267 |
-
if best is not None:
|
| 268 |
-
return best
|
| 269 |
-
|
| 270 |
-
left -= 1
|
| 271 |
-
right += 1
|
| 272 |
-
|
| 273 |
-
return None
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
def synchronize_timestamps(
|
| 277 |
-
camera_timestamps_h5: str,
|
| 278 |
-
radar_h5: str,
|
| 279 |
-
tolerance_ms: float = 50.0,
|
| 280 |
-
enforce_one_to_one: bool = True,
|
| 281 |
-
strategy: Literal["nearest"] = "nearest",
|
| 282 |
-
|
| 283 |
-
) -> SyncResult:
|
| 284 |
-
"""
|
| 285 |
-
Synchronize camera and radar timestamps.
|
| 286 |
-
|
| 287 |
-
Assumptions (true for the new recorders):
|
| 288 |
-
- Both timestamp streams are in **milliseconds since Unix epoch** (from `time.time()*1000`).
|
| 289 |
-
- Each stream is **monotonically increasing**.
|
| 290 |
-
|
| 291 |
-
Parameters:
|
| 292 |
-
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
""
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
#
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
abs_diff
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
f"
|
| 353 |
-
f"
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
-
|
| 382 |
-
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
-
|
| 387 |
-
-
|
| 388 |
-
-
|
| 389 |
-
-
|
| 390 |
-
-
|
| 391 |
-
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import h5py
|
| 3 |
+
import logging
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import List, Tuple, Optional, Literal, Union
|
| 6 |
+
import os
|
| 7 |
+
import glob
|
| 8 |
+
import tyro
|
| 9 |
+
|
| 10 |
+
def setup_logging(name):
|
| 11 |
+
logging.basicConfig(level=logging.INFO, format='%(name)s - %(levelname)s - %(message)s')
|
| 12 |
+
return logging.getLogger(name)
|
| 13 |
+
|
| 14 |
+
log = setup_logging("Sync")
|
| 15 |
+
|
| 16 |
+
def _load_h5_dataset_1d(h5_path: str, dataset: str) -> np.ndarray:
|
| 17 |
+
"""
|
| 18 |
+
Load a 1D dataset from an HDF5 file.
|
| 19 |
+
"""
|
| 20 |
+
with h5py.File(h5_path, 'r') as f:
|
| 21 |
+
if dataset not in f:
|
| 22 |
+
raise ValueError(f"Dataset not found in HDF5 file: {dataset!r} (file: {h5_path})")
|
| 23 |
+
dset = f[dataset]
|
| 24 |
+
# Many recorders preallocate more slots than actual frames; honor num_frames attr if present.
|
| 25 |
+
num_frames_attr = f.attrs.get("num_frames")
|
| 26 |
+
if isinstance(num_frames_attr, (int, np.integer)) and 0 < num_frames_attr <= dset.shape[0]:
|
| 27 |
+
arr = dset[: int(num_frames_attr)]
|
| 28 |
+
else:
|
| 29 |
+
arr = dset[:]
|
| 30 |
+
|
| 31 |
+
arr = np.asarray(arr, dtype=np.float64)
|
| 32 |
+
if arr.ndim != 1:
|
| 33 |
+
raise ValueError(f"Expected 1D dataset {dataset!r}, got shape {arr.shape} (file: {h5_path})")
|
| 34 |
+
# Preallocated trailing zeros may be absent from num_frames metadata. Never
|
| 35 |
+
# remove an interior slot: that would shift every later video frame index.
|
| 36 |
+
valid = np.isfinite(arr) & (arr > 0)
|
| 37 |
+
if not np.all(valid):
|
| 38 |
+
first_invalid = int(np.flatnonzero(~valid)[0])
|
| 39 |
+
if np.any(valid[first_invalid:]):
|
| 40 |
+
raise ValueError(f"Invalid timestamp inside recorded frames: {h5_path}")
|
| 41 |
+
arr = arr[:first_invalid]
|
| 42 |
+
if arr.size and np.any(np.diff(arr) <= 0):
|
| 43 |
+
raise ValueError(f"Timestamps are not strictly increasing: {h5_path}")
|
| 44 |
+
return arr
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_camera_timestamps_h5(camera_h5_path: str, frame_count: Optional[int] = None) -> np.ndarray:
|
| 48 |
+
"""Load H5 camera timestamps, restricted to exported video/depth frames."""
|
| 49 |
+
timestamps = _load_h5_dataset_1d(camera_h5_path, "timestamps_ms")
|
| 50 |
+
if frame_count is not None:
|
| 51 |
+
if frame_count <= 0 or len(timestamps) < frame_count:
|
| 52 |
+
raise ValueError(f"Expected {frame_count} ZED timestamps, found {len(timestamps)}")
|
| 53 |
+
timestamps = timestamps[:frame_count]
|
| 54 |
+
return timestamps
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_radar_timestamps_h5(radar_h5_path: str) -> np.ndarray:
|
| 58 |
+
"""
|
| 59 |
+
Load radar timestamps from `src/radarRecorder.py` output HDF5.
|
| 60 |
+
|
| 61 |
+
Expected dataset: 'timestamps_ms' (milliseconds since Unix epoch).
|
| 62 |
+
"""
|
| 63 |
+
return _load_h5_dataset_1d(radar_h5_path, "timestamps_ms")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_dji_timestamps_h5(dji_h5_path: str) -> np.ndarray:
|
| 67 |
+
"""
|
| 68 |
+
Load DJI timestamps from `src/djiRecorder.py` output HDF5.
|
| 69 |
+
|
| 70 |
+
Expected dataset: 'timestamps_ms' (milliseconds since Unix epoch).
|
| 71 |
+
"""
|
| 72 |
+
return _load_h5_dataset_1d(dji_h5_path, "timestamps_ms")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass(frozen=True)
|
| 76 |
+
class SyncResult:
|
| 77 |
+
"""
|
| 78 |
+
Output of 2-way timestamp synchronization (camera + radar).
|
| 79 |
+
|
| 80 |
+
- `pairs`: list of (camera_frame_idx, radar_frame_idx)
|
| 81 |
+
- `diffs_ms`: signed difference in ms for each pair: camera_ts - radar_ts
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
pairs: List[Tuple[int, int]]
|
| 85 |
+
diffs_ms: np.ndarray
|
| 86 |
+
camera_count: int
|
| 87 |
+
radar_count: int
|
| 88 |
+
tolerance_ms: float
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@dataclass(frozen=True)
|
| 92 |
+
class SyncResult3Way:
|
| 93 |
+
"""
|
| 94 |
+
Output of 3-way timestamp synchronization (radar + ZED depth + DJI RGB).
|
| 95 |
+
|
| 96 |
+
- `triples`: list of (radar_frame_idx, zed_frame_idx, dji_frame_idx)
|
| 97 |
+
- `diffs_radar_zed_ms`: signed difference radar_ts - zed_ts
|
| 98 |
+
- `diffs_radar_dji_ms`: signed difference radar_ts - dji_ts
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
triples: List[Tuple[int, int, int]]
|
| 102 |
+
diffs_radar_zed_ms: np.ndarray
|
| 103 |
+
diffs_radar_dji_ms: np.ndarray
|
| 104 |
+
radar_count: int
|
| 105 |
+
zed_count: int
|
| 106 |
+
dji_count: int
|
| 107 |
+
tolerance_ms: float
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def save_sync_csv(out_csv_path: str, result: Union[SyncResult, SyncResult3Way]) -> None:
|
| 111 |
+
"""
|
| 112 |
+
Save sync pairs/triples to CSV.
|
| 113 |
+
|
| 114 |
+
For SyncResult (2-way):
|
| 115 |
+
camera_frame_idx,radar_frame_idx,diff_ms
|
| 116 |
+
|
| 117 |
+
For SyncResult3Way (3-way):
|
| 118 |
+
radar_frame_idx,zed_frame_idx,dji_frame_idx,diff_radar_zed_ms,diff_radar_dji_ms
|
| 119 |
+
"""
|
| 120 |
+
os.makedirs(os.path.dirname(out_csv_path) or ".", exist_ok=True)
|
| 121 |
+
|
| 122 |
+
if isinstance(result, SyncResult3Way):
|
| 123 |
+
# 3-way sync
|
| 124 |
+
radar_idx = np.array([t[0] for t in result.triples], dtype=np.int64)
|
| 125 |
+
zed_idx = np.array([t[1] for t in result.triples], dtype=np.int64)
|
| 126 |
+
dji_idx = np.array([t[2] for t in result.triples], dtype=np.int64)
|
| 127 |
+
arr = np.column_stack([
|
| 128 |
+
radar_idx,
|
| 129 |
+
zed_idx,
|
| 130 |
+
dji_idx,
|
| 131 |
+
result.diffs_radar_zed_ms.astype(np.float64, copy=False),
|
| 132 |
+
result.diffs_radar_dji_ms.astype(np.float64, copy=False)
|
| 133 |
+
])
|
| 134 |
+
header = "radar_frame_idx,zed_frame_idx,dji_frame_idx,diff_radar_zed_ms,diff_radar_dji_ms"
|
| 135 |
+
fmt = ["%d", "%d", "%d", "%.6f", "%.6f"]
|
| 136 |
+
else:
|
| 137 |
+
# 2-way sync (backward compatibility)
|
| 138 |
+
cam_idx = np.array([p[0] for p in result.pairs], dtype=np.int64)
|
| 139 |
+
rad_idx = np.array([p[1] for p in result.pairs], dtype=np.int64)
|
| 140 |
+
arr = np.column_stack([cam_idx, rad_idx, result.diffs_ms.astype(np.float64, copy=False)])
|
| 141 |
+
header = "camera_frame_idx,radar_frame_idx,diff_ms"
|
| 142 |
+
fmt = ["%d", "%d", "%.6f"]
|
| 143 |
+
|
| 144 |
+
np.savetxt(out_csv_path, arr, fmt=fmt, delimiter=",", header=header, comments="")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _pick_latest_file(directory: str, pattern: str) -> str:
|
| 148 |
+
"""
|
| 149 |
+
Pick the latest file (by lexicographic sort) matching a pattern in a directory.
|
| 150 |
+
|
| 151 |
+
This works for our timestamped filenames like:
|
| 152 |
+
- camera_timestamps_YYYYmmdd_HHMMSS.h5
|
| 153 |
+
- radar_YYYYmmdd_HHMMSS.h5
|
| 154 |
+
"""
|
| 155 |
+
matches = glob.glob(os.path.join(directory, pattern))
|
| 156 |
+
if not matches:
|
| 157 |
+
raise FileNotFoundError(f"No files matching {pattern!r} in directory: {directory}")
|
| 158 |
+
matches.sort()
|
| 159 |
+
return matches[-1]
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _pick_latest_file_multi_ext(directory: str, patterns: list[str]) -> str:
|
| 163 |
+
"""
|
| 164 |
+
Pick the latest file matching any of multiple patterns.
|
| 165 |
+
|
| 166 |
+
Useful for finding files with different extensions (e.g., .mkv or .mp4).
|
| 167 |
+
|
| 168 |
+
Example:
|
| 169 |
+
path = _pick_latest_file_multi_ext("data", ["dji_*.mkv", "dji_*.mp4"])
|
| 170 |
+
"""
|
| 171 |
+
all_matches = []
|
| 172 |
+
for pattern in patterns:
|
| 173 |
+
matches = glob.glob(os.path.join(directory, pattern))
|
| 174 |
+
all_matches.extend(matches)
|
| 175 |
+
|
| 176 |
+
if not all_matches:
|
| 177 |
+
patterns_str = " or ".join(patterns)
|
| 178 |
+
raise FileNotFoundError(f"No files matching {patterns_str} in directory: {directory}")
|
| 179 |
+
|
| 180 |
+
all_matches.sort()
|
| 181 |
+
return all_matches[-1]
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def cli(
|
| 185 |
+
directory: Optional[str] = None,
|
| 186 |
+
camera_timestamps_h5: Optional[str] = None,
|
| 187 |
+
radar_h5: Optional[str] = None,
|
| 188 |
+
zed_frame_count: Optional[int] = None,
|
| 189 |
+
out_csv: str = os.path.join("data", "sync_pairs.csv"),
|
| 190 |
+
tolerance_ms: float = 50.0,
|
| 191 |
+
enforce_one_to_one: bool = True,
|
| 192 |
+
) -> None:
|
| 193 |
+
"""
|
| 194 |
+
CLI wrapper for timestamp synchronization.
|
| 195 |
+
|
| 196 |
+
Usage patterns:
|
| 197 |
+
|
| 198 |
+
1) Directory mode (auto-pick latest files):
|
| 199 |
+
- Provide `directory` to pick H5 files, including exported ZED depth.
|
| 200 |
+
|
| 201 |
+
2) File mode (explicit paths):
|
| 202 |
+
- Provide BOTH `camera_timestamps_h5` and `radar_h5`, optionally `zed_frame_count`.
|
| 203 |
+
"""
|
| 204 |
+
if directory is not None:
|
| 205 |
+
if camera_timestamps_h5 is not None or radar_h5 is not None or zed_frame_count is not None:
|
| 206 |
+
raise ValueError("If 'directory' is provided, do not also pass explicit file paths.")
|
| 207 |
+
camera_timestamps_h5 = _pick_latest_file(directory, "camera_timestamps_*.h5")
|
| 208 |
+
radar_h5 = _pick_latest_file(directory, "radar_*.h5")
|
| 209 |
+
zed_depth_h5 = _pick_latest_file(directory, "zed_depth*.h5")
|
| 210 |
+
with h5py.File(zed_depth_h5) as depth_file:
|
| 211 |
+
zed_frame_count = depth_file["depth_mm"].shape[0]
|
| 212 |
+
log.info(f"Auto-picked camera timestamps: {camera_timestamps_h5}")
|
| 213 |
+
log.info(f"Auto-picked radar file: {radar_h5}")
|
| 214 |
+
log.info(f"Auto-picked ZED depth: {zed_depth_h5}")
|
| 215 |
+
|
| 216 |
+
if camera_timestamps_h5 is None or radar_h5 is None:
|
| 217 |
+
raise ValueError(
|
| 218 |
+
"Provide either:\n"
|
| 219 |
+
"- directory=<folder containing camera_timestamps_*.h5 and radar_*.h5>, OR\n"
|
| 220 |
+
"- camera_timestamps_h5=<path> AND radar_h5=<path>."
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
result = synchronize_timestamps(
|
| 224 |
+
camera_timestamps_h5=camera_timestamps_h5,
|
| 225 |
+
radar_h5=radar_h5,
|
| 226 |
+
tolerance_ms=tolerance_ms,
|
| 227 |
+
enforce_one_to_one=enforce_one_to_one,
|
| 228 |
+
zed_frame_count=zed_frame_count,
|
| 229 |
+
)
|
| 230 |
+
save_sync_csv(out_csv, result)
|
| 231 |
+
log.info(f"Wrote sync CSV: {out_csv}")
|
| 232 |
+
|
| 233 |
+
def _nearest_unused_camera_index(
|
| 234 |
+
cam_ts: np.ndarray,
|
| 235 |
+
target_t: float,
|
| 236 |
+
used_camera: set[int],
|
| 237 |
+
start_idx: int,
|
| 238 |
+
) -> Optional[int]:
|
| 239 |
+
"""
|
| 240 |
+
Find nearest unused camera index to `target_t`.
|
| 241 |
+
|
| 242 |
+
`start_idx` is the insertion index from `np.searchsorted(cam_ts, target_t)`.
|
| 243 |
+
We expand outward until we find an unused camera frame.
|
| 244 |
+
"""
|
| 245 |
+
left = start_idx - 1
|
| 246 |
+
right = start_idx
|
| 247 |
+
while left >= 0 or right < len(cam_ts):
|
| 248 |
+
cand_left = left if left >= 0 else None
|
| 249 |
+
cand_right = right if right < len(cam_ts) else None
|
| 250 |
+
|
| 251 |
+
if cand_left is None and cand_right is None:
|
| 252 |
+
return None
|
| 253 |
+
|
| 254 |
+
best: Optional[int] = None
|
| 255 |
+
best_abs = float("inf")
|
| 256 |
+
|
| 257 |
+
for cand in (cand_left, cand_right):
|
| 258 |
+
if cand is None:
|
| 259 |
+
continue
|
| 260 |
+
if cand in used_camera:
|
| 261 |
+
continue
|
| 262 |
+
abs_diff = abs(float(cam_ts[cand] - target_t))
|
| 263 |
+
if abs_diff < best_abs:
|
| 264 |
+
best_abs = abs_diff
|
| 265 |
+
best = int(cand)
|
| 266 |
+
|
| 267 |
+
if best is not None:
|
| 268 |
+
return best
|
| 269 |
+
|
| 270 |
+
left -= 1
|
| 271 |
+
right += 1
|
| 272 |
+
|
| 273 |
+
return None
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def synchronize_timestamps(
|
| 277 |
+
camera_timestamps_h5: str,
|
| 278 |
+
radar_h5: str,
|
| 279 |
+
tolerance_ms: float = 50.0,
|
| 280 |
+
enforce_one_to_one: bool = True,
|
| 281 |
+
strategy: Literal["nearest"] = "nearest",
|
| 282 |
+
zed_frame_count: Optional[int] = None,
|
| 283 |
+
) -> SyncResult:
|
| 284 |
+
"""
|
| 285 |
+
Synchronize camera and radar timestamps.
|
| 286 |
+
|
| 287 |
+
Assumptions (true for the new recorders):
|
| 288 |
+
- Both timestamp streams are in **milliseconds since Unix epoch** (from `time.time()*1000`).
|
| 289 |
+
- Each stream is **monotonically increasing**.
|
| 290 |
+
|
| 291 |
+
Parameters:
|
| 292 |
+
- zed_frame_count: Number of exported ZED RGB/depth frames.
|
| 293 |
+
|
| 294 |
+
Returns pairs and per-pair signed diffs: Δt = t_cam - t_radar.
|
| 295 |
+
"""
|
| 296 |
+
if strategy != "nearest":
|
| 297 |
+
raise ValueError(f"Unsupported strategy: {strategy!r}")
|
| 298 |
+
|
| 299 |
+
cam_ts = load_camera_timestamps_h5(camera_timestamps_h5, zed_frame_count)
|
| 300 |
+
rad_ts = load_radar_timestamps_h5(radar_h5)
|
| 301 |
+
|
| 302 |
+
log.info(f"Camera timestamps: {len(cam_ts)}")
|
| 303 |
+
|
| 304 |
+
# Ensure float for arithmetic (HDF5 may store float64 already, but keep consistent)
|
| 305 |
+
cam_ts = cam_ts.astype(np.float64, copy=False)
|
| 306 |
+
rad_ts = rad_ts.astype(np.float64, copy=False)
|
| 307 |
+
|
| 308 |
+
# Reverse logic: iterate radar frames and pick nearest camera frame.
|
| 309 |
+
# Goal: keep (as many as possible) radar frames, since radar is the lower FPS stream.
|
| 310 |
+
pairs: List[Tuple[int, int]] = []
|
| 311 |
+
diffs: List[float] = []
|
| 312 |
+
used_camera: set[int] = set()
|
| 313 |
+
|
| 314 |
+
for rad_idx, r_t in enumerate(rad_ts):
|
| 315 |
+
insert_idx = int(np.searchsorted(cam_ts, r_t))
|
| 316 |
+
|
| 317 |
+
if enforce_one_to_one:
|
| 318 |
+
cam_idx = _nearest_unused_camera_index(cam_ts, float(r_t), used_camera, insert_idx)
|
| 319 |
+
else:
|
| 320 |
+
# Nearest of the two immediate neighbors (can reuse camera frames).
|
| 321 |
+
cand0 = insert_idx - 1 if insert_idx > 0 else None
|
| 322 |
+
cand1 = insert_idx if insert_idx < len(cam_ts) else None
|
| 323 |
+
best: Optional[int] = None
|
| 324 |
+
best_abs = float("inf")
|
| 325 |
+
for cand in (cand0, cand1):
|
| 326 |
+
if cand is None:
|
| 327 |
+
continue
|
| 328 |
+
abs_diff = abs(float(cam_ts[cand] - r_t))
|
| 329 |
+
if abs_diff < best_abs:
|
| 330 |
+
best_abs = abs_diff
|
| 331 |
+
best = int(cand)
|
| 332 |
+
cam_idx = best
|
| 333 |
+
|
| 334 |
+
if cam_idx is None:
|
| 335 |
+
# No camera frames at all (or no unused ones left).
|
| 336 |
+
break
|
| 337 |
+
|
| 338 |
+
signed = float(cam_ts[cam_idx] - r_t)
|
| 339 |
+
abs_diff = abs(signed)
|
| 340 |
+
|
| 341 |
+
if abs_diff > tolerance_ms:
|
| 342 |
+
continue
|
| 343 |
+
|
| 344 |
+
pairs.append((int(cam_idx), int(rad_idx)))
|
| 345 |
+
diffs.append(signed)
|
| 346 |
+
if enforce_one_to_one:
|
| 347 |
+
used_camera.add(int(cam_idx))
|
| 348 |
+
|
| 349 |
+
diffs_ms = np.array(diffs, dtype=np.float64)
|
| 350 |
+
log.info(
|
| 351 |
+
f"Synchronized {len(pairs)} pairs | "
|
| 352 |
+
f"camera={len(cam_ts)} radar={len(rad_ts)} | tol={tolerance_ms}ms | "
|
| 353 |
+
f"one_to_one={enforce_one_to_one}"
|
| 354 |
+
)
|
| 355 |
+
return SyncResult(
|
| 356 |
+
pairs=pairs,
|
| 357 |
+
diffs_ms=diffs_ms,
|
| 358 |
+
camera_count=int(len(cam_ts)),
|
| 359 |
+
radar_count=int(len(rad_ts)),
|
| 360 |
+
tolerance_ms=float(tolerance_ms),
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
if __name__ == "__main__":
|
| 364 |
+
tyro.cli(cli)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def synchronize_timestamps_3way(
|
| 368 |
+
radar_h5: str,
|
| 369 |
+
zed_timestamps_h5: str,
|
| 370 |
+
dji_timestamps_h5: str,
|
| 371 |
+
tolerance_ms: float = 50.0,
|
| 372 |
+
enforce_one_to_one: bool = True,
|
| 373 |
+
zed_frame_count: Optional[int] = None,
|
| 374 |
+
dji_frame_count: Optional[int] = None,
|
| 375 |
+
) -> SyncResult3Way:
|
| 376 |
+
"""
|
| 377 |
+
Synchronize 3 timestamp streams: radar (reference), ZED depth, DJI RGB.
|
| 378 |
+
|
| 379 |
+
Strategy:
|
| 380 |
+
- Radar is the lowest FPS stream (typically ~10 Hz), so we use it as the reference.
|
| 381 |
+
- For each radar frame, find the nearest ZED frame and nearest DJI frame.
|
| 382 |
+
- Both must be within tolerance_ms of the radar timestamp.
|
| 383 |
+
|
| 384 |
+
Parameters:
|
| 385 |
+
- radar_h5: Path to radar HDF5 file with timestamps_ms
|
| 386 |
+
- zed_timestamps_h5: Path to ZED camera timestamps HDF5
|
| 387 |
+
- dji_timestamps_h5: Path to DJI timestamps HDF5
|
| 388 |
+
- tolerance_ms: Maximum time difference in milliseconds
|
| 389 |
+
- enforce_one_to_one: If True, each ZED/DJI frame can only be used once
|
| 390 |
+
- zed_frame_count: Number of aligned ZED RGB/depth frames
|
| 391 |
+
- dji_frame_count: Number of anonymized DJI video frames
|
| 392 |
+
|
| 393 |
+
Returns:
|
| 394 |
+
- SyncResult3Way with triples (radar_idx, zed_idx, dji_idx)
|
| 395 |
+
"""
|
| 396 |
+
# Load all timestamps
|
| 397 |
+
radar_ts = load_radar_timestamps_h5(radar_h5)
|
| 398 |
+
zed_ts = load_camera_timestamps_h5(zed_timestamps_h5, zed_frame_count)
|
| 399 |
+
dji_ts = load_dji_timestamps_h5(dji_timestamps_h5)
|
| 400 |
+
if dji_frame_count is not None:
|
| 401 |
+
if dji_frame_count <= 0:
|
| 402 |
+
raise ValueError(f"Invalid DJI frame count: {dji_frame_count}")
|
| 403 |
+
if len(dji_ts) == 0:
|
| 404 |
+
raise ValueError(f"No DJI timestamps in {dji_timestamps_h5}")
|
| 405 |
+
if len(dji_ts) < dji_frame_count:
|
| 406 |
+
log.warning(
|
| 407 |
+
"DJI video has %d frames but only %d timestamps; "
|
| 408 |
+
"untimed frames cannot be synchronized",
|
| 409 |
+
dji_frame_count, len(dji_ts),
|
| 410 |
+
)
|
| 411 |
+
dji_ts = dji_ts[:dji_frame_count]
|
| 412 |
+
|
| 413 |
+
log.info(f"ZED timestamps: {len(zed_ts)}")
|
| 414 |
+
|
| 415 |
+
# Ensure float64 for arithmetic
|
| 416 |
+
radar_ts = radar_ts.astype(np.float64, copy=False)
|
| 417 |
+
zed_ts = zed_ts.astype(np.float64, copy=False)
|
| 418 |
+
dji_ts = dji_ts.astype(np.float64, copy=False)
|
| 419 |
+
|
| 420 |
+
log.info(f"Timestamp ranges:")
|
| 421 |
+
log.info(f" Radar: {len(radar_ts)} frames, {radar_ts[0]:.2f} - {radar_ts[-1]:.2f} ms")
|
| 422 |
+
log.info(f" ZED: {len(zed_ts)} frames, {zed_ts[0]:.2f} - {zed_ts[-1]:.2f} ms")
|
| 423 |
+
log.info(f" DJI: {len(dji_ts)} frames, {dji_ts[0]:.2f} - {dji_ts[-1]:.2f} ms")
|
| 424 |
+
|
| 425 |
+
# Iterate through radar frames (lowest FPS, reference stream)
|
| 426 |
+
triples = []
|
| 427 |
+
diffs_radar_zed = []
|
| 428 |
+
diffs_radar_dji = []
|
| 429 |
+
used_zed = set()
|
| 430 |
+
used_dji = set()
|
| 431 |
+
|
| 432 |
+
for radar_idx, r_t in enumerate(radar_ts):
|
| 433 |
+
# Find nearest ZED frame
|
| 434 |
+
zed_insert_idx = int(np.searchsorted(zed_ts, r_t))
|
| 435 |
+
if enforce_one_to_one:
|
| 436 |
+
zed_idx = _nearest_unused_camera_index(zed_ts, float(r_t), used_zed, zed_insert_idx)
|
| 437 |
+
else:
|
| 438 |
+
cand0 = zed_insert_idx - 1 if zed_insert_idx > 0 else None
|
| 439 |
+
cand1 = zed_insert_idx if zed_insert_idx < len(zed_ts) else None
|
| 440 |
+
zed_idx = None
|
| 441 |
+
best_abs = float("inf")
|
| 442 |
+
for cand in (cand0, cand1):
|
| 443 |
+
if cand is None:
|
| 444 |
+
continue
|
| 445 |
+
abs_diff = abs(float(zed_ts[cand] - r_t))
|
| 446 |
+
if abs_diff < best_abs:
|
| 447 |
+
best_abs = abs_diff
|
| 448 |
+
zed_idx = int(cand)
|
| 449 |
+
|
| 450 |
+
if zed_idx is None:
|
| 451 |
+
continue
|
| 452 |
+
|
| 453 |
+
zed_diff = float(r_t - zed_ts[zed_idx])
|
| 454 |
+
if abs(zed_diff) > tolerance_ms:
|
| 455 |
+
continue
|
| 456 |
+
|
| 457 |
+
# Find nearest DJI frame
|
| 458 |
+
dji_insert_idx = int(np.searchsorted(dji_ts, r_t))
|
| 459 |
+
if enforce_one_to_one:
|
| 460 |
+
dji_idx = _nearest_unused_camera_index(dji_ts, float(r_t), used_dji, dji_insert_idx)
|
| 461 |
+
else:
|
| 462 |
+
cand0 = dji_insert_idx - 1 if dji_insert_idx > 0 else None
|
| 463 |
+
cand1 = dji_insert_idx if dji_insert_idx < len(dji_ts) else None
|
| 464 |
+
dji_idx = None
|
| 465 |
+
best_abs = float("inf")
|
| 466 |
+
for cand in (cand0, cand1):
|
| 467 |
+
if cand is None:
|
| 468 |
+
continue
|
| 469 |
+
abs_diff = abs(float(dji_ts[cand] - r_t))
|
| 470 |
+
if abs_diff < best_abs:
|
| 471 |
+
best_abs = abs_diff
|
| 472 |
+
dji_idx = int(cand)
|
| 473 |
+
|
| 474 |
+
if dji_idx is None:
|
| 475 |
+
continue
|
| 476 |
+
|
| 477 |
+
dji_diff = float(r_t - dji_ts[dji_idx])
|
| 478 |
+
if abs(dji_diff) > tolerance_ms:
|
| 479 |
+
continue
|
| 480 |
+
|
| 481 |
+
# Both ZED and DJI within tolerance - add triple
|
| 482 |
+
triples.append((int(radar_idx), int(zed_idx), int(dji_idx)))
|
| 483 |
+
diffs_radar_zed.append(zed_diff)
|
| 484 |
+
diffs_radar_dji.append(dji_diff)
|
| 485 |
+
|
| 486 |
+
if enforce_one_to_one:
|
| 487 |
+
used_zed.add(int(zed_idx))
|
| 488 |
+
used_dji.add(int(dji_idx))
|
| 489 |
+
|
| 490 |
+
diffs_radar_zed_ms = np.array(diffs_radar_zed, dtype=np.float64)
|
| 491 |
+
diffs_radar_dji_ms = np.array(diffs_radar_dji, dtype=np.float64)
|
| 492 |
+
|
| 493 |
+
log.info(
|
| 494 |
+
f"Synchronized {len(triples)} triples | "
|
| 495 |
+
f"radar={len(radar_ts)} zed={len(zed_ts)} dji={len(dji_ts)} | "
|
| 496 |
+
f"tol={tolerance_ms}ms | one_to_one={enforce_one_to_one}"
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
return SyncResult3Way(
|
| 500 |
+
triples=triples,
|
| 501 |
+
diffs_radar_zed_ms=diffs_radar_zed_ms,
|
| 502 |
+
diffs_radar_dji_ms=diffs_radar_dji_ms,
|
| 503 |
+
radar_count=int(len(radar_ts)),
|
| 504 |
+
zed_count=int(len(zed_ts)),
|
| 505 |
+
dji_count=int(len(dji_ts)),
|
| 506 |
+
tolerance_ms=float(tolerance_ms),
|
| 507 |
+
)
|