Datasets:

ArXiv:
Bin-0815 commited on
Commit
d2e274e
·
verified ·
1 Parent(s): 55d5c8a

Document anonymized videos and publish SDK-free processor

Browse files
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. **This release currently contains only non-video data. DJI and ZED video recordings are not publicly available; any future video release depends on anonymization and author clearance, and no release date is set.**
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 in this release contains:
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. **The processor also needs the ZED and DJI videos, so the public download alone cannot run it until the anonymized videos are released.**
35
 
36
- 1. Install the [ZED SDK](https://www.stereolabs.com/developers/release/) on a Linux machine with a supported NVIDIA GPU.
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
- Run the ZED Python API installer **after activating** the environment. See the [Stereolabs instructions](https://docs.stereolabs.com/docs/development/api-languages/python) if your SDK uses another path. We tested the processor with Python 3.12 and ZED SDK 5.4.1; a different SDK version may produce slightly different ZED RGB/depth values.
48
 
49
- 3. Process one evaluation sequence:
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 1920x1080
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: resize 1920x1080 -> 896x504, then save as NPY for fast loading
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} ({rgb_codec.upper()} codec)")
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
- svo_path = _pick_latest_file(sequence_dir, "zed_*.svo2")
 
310
  dji_timestamps_h5 = _pick_latest_file(sequence_dir, "dji_timestamps_*.h5")
311
- dji_video_path = _pick_latest_file_multi_ext(sequence_dir, ["dji_*.mkv", "dji_*.mp4"])
312
 
313
  log.info(f"Radar H5: {radar_h5}")
314
  log.info(f"ZED timestamps: {zed_timestamps_h5}")
315
- log.info(f"ZED SVO2: {svo_path}")
 
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
- svo_path=svo_path,
336
- dji_video_path=dji_video_path,
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 SVO...")
440
  zed_rgb, zed_depth_mm, _intrinsics = extract_camera_data(
441
- svo_path=svo_path,
 
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': depth_confidence,
471
- 'depth_texture_confidence': 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
- - zed_*.svo2 (ZED video with depth)
 
519
  - dji_timestamps_*.h5 (DJI action camera timestamps)
520
- - dji_*.mkv or dji_*.mp4 (DJI video)
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 1920x1080
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
- import os
2
- import logging
3
- from typing import Iterable, Tuple
4
-
5
- import cv2
6
- import numpy as np
7
- import pyzed.sl as sl
8
- from tqdm import tqdm
9
-
10
- log = logging.getLogger(__name__)
11
-
12
-
13
- def extract_camera_data(
14
- svo_path: str,
15
- frame_indices: Iterable[int],
16
- depth_mode: str = "NEURAL_PLUS",
17
- confidence_threshold: int = 100,
18
- texture_confidence_threshold: int = 100,
19
- ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
20
- """
21
- Extract selected RGB and depth frames from a recorded SVO/SVO2.
22
-
23
- This function ensures 1:1 pixel alignment between RGB and depth by:
24
- - Using the same rectified view (sl.VIEW.LEFT) for RGB
25
- - Using sl.MEASURE.DEPTH which matches the rectified resolution
26
- - Validating dimensions on the first frame to catch FOV mismatches
27
-
28
- Parameters:
29
- - svo_path: path to the .svo/.svo2 file recorded by `src/cameraRecorder.py`.
30
- - frame_indices: iterable of camera frame indices to keep
31
- (e.g. the `camera_frame_idx` column from `sync_pairs.csv`).
32
- - depth_mode: ZED depth mode, e.g. "NEURAL_PLUS" for the finest model.
33
- Note: NEURAL modes may fill in peripheral regions beyond traditional stereo overlap.
34
- - confidence_threshold: Depth confidence threshold (1-100). Higher values (closer to 100)
35
- fill in more depth holes but may add noise. Lower values filter more strictly.
36
- Default: 100 (least filtering, most coverage).
37
- - texture_confidence_threshold: Texture confidence threshold (1-100). Controls depth
38
- estimation in uniform/textureless areas. Lower values allow depth in less detailed
39
- regions. Default: 100 (least filtering).
40
-
41
- Returns:
42
- - rgb: array of shape (N, H, W, 3), dtype uint8, LEFT camera RGB frames (rectified).
43
- - depth_mm: array of shape (N, H, W), dtype float32, depth in millimeters (rectified).
44
- RGB and depth are guaranteed to have identical (H, W) dimensions for 1:1 alignment.
45
- - intrinsics: array of shape (4,), dtype float32, `[fx, fy, cx, cy]` for the
46
- rectified LEFT camera. These intrinsics apply to all returned frames.
47
- """
48
- if not os.path.exists(svo_path):
49
- raise FileNotFoundError(f"SVO not found: {svo_path}")
50
-
51
- indices = np.asarray(list(frame_indices), dtype=np.int64)
52
- if indices.size == 0:
53
- return (
54
- np.empty((0, 0, 0, 3), dtype=np.uint8),
55
- np.empty((0, 0), dtype=np.float32),
56
- np.empty((4,), dtype=np.float32),
57
- )
58
-
59
- # Ensure indices are sorted and unique.
60
- indices = np.unique(indices)
61
-
62
- init = sl.InitParameters()
63
- init.set_from_svo_file(svo_path)
64
- init.svo_real_time_mode = False # Process SVO as fast as possible
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 DJI video (MP4/MKV).
18
 
19
  Parameters:
20
- - video_path: path to the video file recorded by `src/djiRecorder.py`.
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
- Note: The video was already flipped (UD+LR) during recording, so no
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
- import pyzed.sl as sl
10
-
11
- def setup_logging(name):
12
- logging.basicConfig(level=logging.INFO, format='%(name)s - %(levelname)s - %(message)s')
13
- return logging.getLogger(name)
14
-
15
- log = setup_logging("Sync")
16
-
17
- def _load_h5_dataset_1d(h5_path: str, dataset: str) -> np.ndarray:
18
- """
19
- Load a 1D dataset from an HDF5 file.
20
- """
21
- with h5py.File(h5_path, 'r') as f:
22
- if dataset not in f:
23
- raise ValueError(f"Dataset not found in HDF5 file: {dataset!r} (file: {h5_path})")
24
- dset = f[dataset]
25
- # Many recorders preallocate more slots than actual frames; honor num_frames attr if present.
26
- num_frames_attr = f.attrs.get("num_frames")
27
- if isinstance(num_frames_attr, (int, np.integer)) and 0 < num_frames_attr <= dset.shape[0]:
28
- arr = dset[: int(num_frames_attr)]
29
- else:
30
- arr = dset[:]
31
-
32
- arr = np.asarray(arr, dtype=np.float64)
33
- if arr.ndim != 1:
34
- raise ValueError(f"Expected 1D dataset {dataset!r}, got shape {arr.shape} (file: {h5_path})")
35
- # Guard against preallocated-but-unwritten zeros (should never happen with time.time()*1000).
36
- mask = arr > 0
37
- return arr[mask]
38
-
39
-
40
- def load_camera_timestamps_h5(camera_h5_path: str) -> np.ndarray:
41
- """
42
- Load camera timestamps from HDF5 and remove the last one.
43
-
44
- This ensures the number of timestamps is always safely within the SVO frame count,
45
- avoiding off-by-one errors that can occur with SVO files.
46
-
47
- Expected dataset: 'timestamps_ms' (milliseconds since Unix epoch).
48
- Returns: timestamps in milliseconds, shape (N-1,)
49
- """
50
- timestamps = _load_h5_dataset_1d(camera_h5_path, "timestamps_ms")
51
-
52
- # Always remove the last timestamp to be safe
53
- if len(timestamps) > 0:
54
- timestamps = timestamps[:-1]
55
-
56
- return timestamps
57
-
58
-
59
- def load_radar_timestamps_h5(radar_h5_path: str) -> np.ndarray:
60
- """
61
- Load radar timestamps from `src/radarRecorder.py` output HDF5.
62
-
63
- Expected dataset: 'timestamps_ms' (milliseconds since Unix epoch).
64
- """
65
- return _load_h5_dataset_1d(radar_h5_path, "timestamps_ms")
66
-
67
-
68
- def load_dji_timestamps_h5(dji_h5_path: str) -> np.ndarray:
69
- """
70
- Load DJI timestamps from `src/djiRecorder.py` output HDF5.
71
-
72
- Expected dataset: 'timestamps_ms' (milliseconds since Unix epoch).
73
- """
74
- return _load_h5_dataset_1d(dji_h5_path, "timestamps_ms")
75
-
76
-
77
- @dataclass(frozen=True)
78
- class SyncResult:
79
- """
80
- Output of 2-way timestamp synchronization (camera + radar).
81
-
82
- - `pairs`: list of (camera_frame_idx, radar_frame_idx)
83
- - `diffs_ms`: signed difference in ms for each pair: camera_ts - radar_ts
84
- """
85
-
86
- pairs: List[Tuple[int, int]]
87
- diffs_ms: np.ndarray
88
- camera_count: int
89
- radar_count: int
90
- tolerance_ms: float
91
-
92
-
93
- @dataclass(frozen=True)
94
- class SyncResult3Way:
95
- """
96
- Output of 3-way timestamp synchronization (radar + ZED depth + DJI RGB).
97
-
98
- - `triples`: list of (radar_frame_idx, zed_frame_idx, dji_frame_idx)
99
- - `diffs_radar_zed_ms`: signed difference radar_ts - zed_ts
100
- - `diffs_radar_dji_ms`: signed difference radar_ts - dji_ts
101
- """
102
-
103
- triples: List[Tuple[int, int, int]]
104
- diffs_radar_zed_ms: np.ndarray
105
- diffs_radar_dji_ms: np.ndarray
106
- radar_count: int
107
- zed_count: int
108
- dji_count: int
109
- tolerance_ms: float
110
-
111
-
112
- def save_sync_csv(out_csv_path: str, result: Union[SyncResult, SyncResult3Way]) -> None:
113
- """
114
- Save sync pairs/triples to CSV.
115
-
116
- For SyncResult (2-way):
117
- camera_frame_idx,radar_frame_idx,diff_ms
118
-
119
- For SyncResult3Way (3-way):
120
- radar_frame_idx,zed_frame_idx,dji_frame_idx,diff_radar_zed_ms,diff_radar_dji_ms
121
- """
122
- os.makedirs(os.path.dirname(out_csv_path) or ".", exist_ok=True)
123
-
124
- if isinstance(result, SyncResult3Way):
125
- # 3-way sync
126
- radar_idx = np.array([t[0] for t in result.triples], dtype=np.int64)
127
- zed_idx = np.array([t[1] for t in result.triples], dtype=np.int64)
128
- dji_idx = np.array([t[2] for t in result.triples], dtype=np.int64)
129
- arr = np.column_stack([
130
- radar_idx,
131
- zed_idx,
132
- dji_idx,
133
- result.diffs_radar_zed_ms.astype(np.float64, copy=False),
134
- result.diffs_radar_dji_ms.astype(np.float64, copy=False)
135
- ])
136
- header = "radar_frame_idx,zed_frame_idx,dji_frame_idx,diff_radar_zed_ms,diff_radar_dji_ms"
137
- fmt = ["%d", "%d", "%d", "%.6f", "%.6f"]
138
- else:
139
- # 2-way sync (backward compatibility)
140
- cam_idx = np.array([p[0] for p in result.pairs], dtype=np.int64)
141
- rad_idx = np.array([p[1] for p in result.pairs], dtype=np.int64)
142
- arr = np.column_stack([cam_idx, rad_idx, result.diffs_ms.astype(np.float64, copy=False)])
143
- header = "camera_frame_idx,radar_frame_idx,diff_ms"
144
- fmt = ["%d", "%d", "%.6f"]
145
-
146
- np.savetxt(out_csv_path, arr, fmt=fmt, delimiter=",", header=header, comments="")
147
-
148
-
149
- def _pick_latest_file(directory: str, pattern: str) -> str:
150
- """
151
- Pick the latest file (by lexicographic sort) matching a pattern in a directory.
152
-
153
- This works for our timestamped filenames like:
154
- - camera_timestamps_YYYYmmdd_HHMMSS.h5
155
- - radar_YYYYmmdd_HHMMSS.h5
156
- """
157
- matches = glob.glob(os.path.join(directory, pattern))
158
- if not matches:
159
- raise FileNotFoundError(f"No files matching {pattern!r} in directory: {directory}")
160
- matches.sort()
161
- return matches[-1]
162
-
163
-
164
- def _pick_latest_file_multi_ext(directory: str, patterns: list[str]) -> str:
165
- """
166
- Pick the latest file matching any of multiple patterns.
167
-
168
- Useful for finding files with different extensions (e.g., .mkv or .mp4).
169
-
170
- Example:
171
- path = _pick_latest_file_multi_ext("data", ["dji_*.mkv", "dji_*.mp4"])
172
- """
173
- all_matches = []
174
- for pattern in patterns:
175
- matches = glob.glob(os.path.join(directory, pattern))
176
- all_matches.extend(matches)
177
-
178
- if not all_matches:
179
- patterns_str = " or ".join(patterns)
180
- raise FileNotFoundError(f"No files matching {patterns_str} in directory: {directory}")
181
-
182
- all_matches.sort()
183
- return all_matches[-1]
184
-
185
-
186
- def cli(
187
- directory: Optional[str] = None,
188
- camera_timestamps_h5: Optional[str] = None,
189
- radar_h5: Optional[str] = None,
190
- svo_path: Optional[str] = None,
191
- out_csv: str = os.path.join("data", "sync_pairs.csv"),
192
- tolerance_ms: float = 50.0,
193
- enforce_one_to_one: bool = True,
194
- ) -> None:
195
- """
196
- CLI wrapper for timestamp synchronization.
197
-
198
- Usage patterns:
199
-
200
- 1) Directory mode (auto-pick latest files):
201
- - Provide `directory` and omit `camera_timestamps_h5` / `radar_h5` / `svo_path`.
202
-
203
- 2) File mode (explicit paths):
204
- - Provide BOTH `camera_timestamps_h5` and `radar_h5`, optionally `svo_path`.
205
- """
206
- if directory is not None:
207
- if camera_timestamps_h5 is not None or radar_h5 is not None or svo_path is not None:
208
- raise ValueError("If 'directory' is provided, do not also pass explicit file paths.")
209
- camera_timestamps_h5 = _pick_latest_file(directory, "camera_timestamps_*.h5")
210
- radar_h5 = _pick_latest_file(directory, "radar_*.h5")
211
- svo_path = _pick_latest_file(directory, "zed_*.svo2")
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 SVO: {svo_path}")
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
- svo_path=svo_path,
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
- svo_path: Optional[str] = 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
- - svo_path: Optional path to SVO2 file. If provided, validates that camera timestamps
293
- don't exceed the actual number of frames in the SVO.
294
-
295
- Returns pairs and per-pair signed diffs: Δt = t_cam - t_radar.
296
- """
297
- if strategy != "nearest":
298
- raise ValueError(f"Unsupported strategy: {strategy!r}")
299
-
300
- cam_ts = load_camera_timestamps_h5(camera_timestamps_h5)
301
- rad_ts = load_radar_timestamps_h5(radar_h5)
302
-
303
- log.info(f"Camera timestamps: {len(cam_ts)} (last timestamp already removed for SVO safety)")
304
-
305
- # Ensure float for arithmetic (HDF5 may store float64 already, but keep consistent)
306
- cam_ts = cam_ts.astype(np.float64, copy=False)
307
- rad_ts = rad_ts.astype(np.float64, copy=False)
308
-
309
- # Reverse logic: iterate radar frames and pick nearest camera frame.
310
- # Goal: keep (as many as possible) radar frames, since radar is the lower FPS stream.
311
- pairs: List[Tuple[int, int]] = []
312
- diffs: List[float] = []
313
- used_camera: set[int] = set()
314
-
315
- for rad_idx, r_t in enumerate(rad_ts):
316
- insert_idx = int(np.searchsorted(cam_ts, r_t))
317
-
318
- if enforce_one_to_one:
319
- cam_idx = _nearest_unused_camera_index(cam_ts, float(r_t), used_camera, insert_idx)
320
- else:
321
- # Nearest of the two immediate neighbors (can reuse camera frames).
322
- cand0 = insert_idx - 1 if insert_idx > 0 else None
323
- cand1 = insert_idx if insert_idx < len(cam_ts) else None
324
- best: Optional[int] = None
325
- best_abs = float("inf")
326
- for cand in (cand0, cand1):
327
- if cand is None:
328
- continue
329
- abs_diff = abs(float(cam_ts[cand] - r_t))
330
- if abs_diff < best_abs:
331
- best_abs = abs_diff
332
- best = int(cand)
333
- cam_idx = best
334
-
335
- if cam_idx is None:
336
- # No camera frames at all (or no unused ones left).
337
- break
338
-
339
- signed = float(cam_ts[cam_idx] - r_t)
340
- abs_diff = abs(signed)
341
-
342
- if abs_diff > tolerance_ms:
343
- continue
344
-
345
- pairs.append((int(cam_idx), int(rad_idx)))
346
- diffs.append(signed)
347
- if enforce_one_to_one:
348
- used_camera.add(int(cam_idx))
349
-
350
- diffs_ms = np.array(diffs, dtype=np.float64)
351
- log.info(
352
- f"Synchronized {len(pairs)} pairs | "
353
- f"camera={len(cam_ts)} radar={len(rad_ts)} | tol={tolerance_ms}ms | "
354
- f"one_to_one={enforce_one_to_one}"
355
- )
356
- return SyncResult(
357
- pairs=pairs,
358
- diffs_ms=diffs_ms,
359
- camera_count=int(len(cam_ts)),
360
- radar_count=int(len(rad_ts)),
361
- tolerance_ms=float(tolerance_ms),
362
- )
363
-
364
- if __name__ == "__main__":
365
- tyro.cli(cli)
366
-
367
-
368
- def synchronize_timestamps_3way(
369
- radar_h5: str,
370
- zed_timestamps_h5: str,
371
- dji_timestamps_h5: str,
372
- tolerance_ms: float = 50.0,
373
- enforce_one_to_one: bool = True,
374
- svo_path: Optional[str] = None,
375
- dji_video_path: Optional[str] = None,
376
- ) -> SyncResult3Way:
377
- """
378
- Synchronize 3 timestamp streams: radar (reference), ZED depth, DJI RGB.
379
-
380
- Strategy:
381
- - Radar is the lowest FPS stream (typically ~10 Hz), so we use it as the reference.
382
- - For each radar frame, find the nearest ZED frame and nearest DJI frame.
383
- - Both must be within tolerance_ms of the radar timestamp.
384
-
385
- Parameters:
386
- - radar_h5: Path to radar HDF5 file with timestamps_ms
387
- - zed_timestamps_h5: Path to ZED camera timestamps HDF5
388
- - dji_timestamps_h5: Path to DJI timestamps HDF5
389
- - tolerance_ms: Maximum time difference in milliseconds
390
- - enforce_one_to_one: If True, each ZED/DJI frame can only be used once
391
- - svo_path: Optional path to SVO2 file for frame count validation
392
- - dji_video_path: Optional path to DJI video for frame count validation
393
-
394
- Returns:
395
- - SyncResult3Way with triples (radar_idx, zed_idx, dji_idx)
396
- """
397
- # Load all timestamps
398
- radar_ts = load_radar_timestamps_h5(radar_h5)
399
- zed_ts = load_camera_timestamps_h5(zed_timestamps_h5)
400
- dji_ts = load_dji_timestamps_h5(dji_timestamps_h5)
401
-
402
- log.info(f"ZED timestamps: {len(zed_ts)} (last timestamp already removed for SVO safety)")
403
-
404
- # Ensure float64 for arithmetic
405
- radar_ts = radar_ts.astype(np.float64, copy=False)
406
- zed_ts = zed_ts.astype(np.float64, copy=False)
407
- dji_ts = dji_ts.astype(np.float64, copy=False)
408
-
409
- log.info(f"Timestamp ranges:")
410
- log.info(f" Radar: {len(radar_ts)} frames, {radar_ts[0]:.2f} - {radar_ts[-1]:.2f} ms")
411
- log.info(f" ZED: {len(zed_ts)} frames, {zed_ts[0]:.2f} - {zed_ts[-1]:.2f} ms")
412
- log.info(f" DJI: {len(dji_ts)} frames, {dji_ts[0]:.2f} - {dji_ts[-1]:.2f} ms")
413
-
414
- # Iterate through radar frames (lowest FPS, reference stream)
415
- triples = []
416
- diffs_radar_zed = []
417
- diffs_radar_dji = []
418
- used_zed = set()
419
- used_dji = set()
420
-
421
- for radar_idx, r_t in enumerate(radar_ts):
422
- # Find nearest ZED frame
423
- zed_insert_idx = int(np.searchsorted(zed_ts, r_t))
424
- if enforce_one_to_one:
425
- zed_idx = _nearest_unused_camera_index(zed_ts, float(r_t), used_zed, zed_insert_idx)
426
- else:
427
- cand0 = zed_insert_idx - 1 if zed_insert_idx > 0 else None
428
- cand1 = zed_insert_idx if zed_insert_idx < len(zed_ts) else None
429
- zed_idx = None
430
- best_abs = float("inf")
431
- for cand in (cand0, cand1):
432
- if cand is None:
433
- continue
434
- abs_diff = abs(float(zed_ts[cand] - r_t))
435
- if abs_diff < best_abs:
436
- best_abs = abs_diff
437
- zed_idx = int(cand)
438
-
439
- if zed_idx is None:
440
- continue
441
-
442
- zed_diff = float(r_t - zed_ts[zed_idx])
443
- if abs(zed_diff) > tolerance_ms:
444
- continue
445
-
446
- # Find nearest DJI frame
447
- dji_insert_idx = int(np.searchsorted(dji_ts, r_t))
448
- if enforce_one_to_one:
449
- dji_idx = _nearest_unused_camera_index(dji_ts, float(r_t), used_dji, dji_insert_idx)
450
- else:
451
- cand0 = dji_insert_idx - 1 if dji_insert_idx > 0 else None
452
- cand1 = dji_insert_idx if dji_insert_idx < len(dji_ts) else None
453
- dji_idx = None
454
- best_abs = float("inf")
455
- for cand in (cand0, cand1):
456
- if cand is None:
457
- continue
458
- abs_diff = abs(float(dji_ts[cand] - r_t))
459
- if abs_diff < best_abs:
460
- best_abs = abs_diff
461
- dji_idx = int(cand)
462
-
463
- if dji_idx is None:
464
- continue
465
-
466
- dji_diff = float(r_t - dji_ts[dji_idx])
467
- if abs(dji_diff) > tolerance_ms:
468
- continue
469
-
470
- # Both ZED and DJI within tolerance - add triple
471
- triples.append((int(radar_idx), int(zed_idx), int(dji_idx)))
472
- diffs_radar_zed.append(zed_diff)
473
- diffs_radar_dji.append(dji_diff)
474
-
475
- if enforce_one_to_one:
476
- used_zed.add(int(zed_idx))
477
- used_dji.add(int(dji_idx))
478
-
479
- diffs_radar_zed_ms = np.array(diffs_radar_zed, dtype=np.float64)
480
- diffs_radar_dji_ms = np.array(diffs_radar_dji, dtype=np.float64)
481
-
482
- log.info(
483
- f"Synchronized {len(triples)} triples | "
484
- f"radar={len(radar_ts)} zed={len(zed_ts)} dji={len(dji_ts)} | "
485
- f"tol={tolerance_ms}ms | one_to_one={enforce_one_to_one}"
486
- )
487
-
488
- return SyncResult3Way(
489
- triples=triples,
490
- diffs_radar_zed_ms=diffs_radar_zed_ms,
491
- diffs_radar_dji_ms=diffs_radar_dji_ms,
492
- radar_count=int(len(radar_ts)),
493
- zed_count=int(len(zed_ts)),
494
- dji_count=int(len(dji_ts)),
495
- tolerance_ms=float(tolerance_ms),
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
+ )