Upload folder using huggingface_hub
Browse files- processing_code/processor.py +668 -0
- processing_code/requirements.txt +12 -0
- processing_code/utils/extract_camera_data.py +172 -0
- processing_code/utils/extract_dji_data.py +85 -0
- processing_code/utils/extract_max_data.py +162 -0
- processing_code/utils/extract_pcd.py +126 -0
- processing_code/utils/extract_radar_data.py +110 -0
- processing_code/utils/sync_timestamps.py +496 -0
processing_code/processor.py
ADDED
|
@@ -0,0 +1,668 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import cv2
|
| 7 |
+
import h5py
|
| 8 |
+
import numpy as np
|
| 9 |
+
import tyro
|
| 10 |
+
from rich.logging import RichHandler
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
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
|
| 21 |
+
from utils.extract_dji_data import extract_dji_rgb
|
| 22 |
+
from utils.extract_radar_data import process_single_frame
|
| 23 |
+
from utils.extract_max_data import extract_max30105_for_sequence
|
| 24 |
+
from utils.extract_pcd import extract_point_cloud_from_frame
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def setup_logging(name):
|
| 28 |
+
logging.basicConfig(
|
| 29 |
+
level=logging.INFO,
|
| 30 |
+
format=f"%(name)-12s %(message)s",
|
| 31 |
+
datefmt="[%H:%M:%S]",
|
| 32 |
+
handlers=[RichHandler()]
|
| 33 |
+
)
|
| 34 |
+
return logging.getLogger(name)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_radar_frames(radar_h5_path: str, frame_indices: np.ndarray) -> np.ndarray:
|
| 38 |
+
"""
|
| 39 |
+
Load selected radar frames from HDF5.
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
- radar_frames: shape (N, doppler, tx, rx, range), dtype from file (typically int16)
|
| 43 |
+
"""
|
| 44 |
+
with h5py.File(radar_h5_path, "r") as f:
|
| 45 |
+
if "radar_data" not in f:
|
| 46 |
+
raise ValueError(f"Dataset 'radar_data' not found in {radar_h5_path}")
|
| 47 |
+
|
| 48 |
+
num_frames_attr = f.attrs.get("num_frames")
|
| 49 |
+
if isinstance(num_frames_attr, (int, np.integer)):
|
| 50 |
+
num_frames_attr = int(num_frames_attr)
|
| 51 |
+
else:
|
| 52 |
+
num_frames_attr = f["radar_data"].shape[0]
|
| 53 |
+
|
| 54 |
+
# Load only the specified indices
|
| 55 |
+
frames = []
|
| 56 |
+
for idx in frame_indices:
|
| 57 |
+
if idx < 0 or idx >= num_frames_attr:
|
| 58 |
+
continue
|
| 59 |
+
frames.append(f["radar_data"][int(idx)])
|
| 60 |
+
|
| 61 |
+
if not frames:
|
| 62 |
+
return np.empty((0, 0, 0, 0, 0), dtype=np.int16)
|
| 63 |
+
|
| 64 |
+
return np.stack(frames, axis=0)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _resize_rgb_to(
|
| 68 |
+
frames: np.ndarray,
|
| 69 |
+
target_size: Tuple[int, int],
|
| 70 |
+
interpolation: int = cv2.INTER_LINEAR,
|
| 71 |
+
log=None,
|
| 72 |
+
) -> np.ndarray:
|
| 73 |
+
"""
|
| 74 |
+
Resize RGB frames (N, H, W, 3) uint8 to (N, target_h, target_w, 3).
|
| 75 |
+
|
| 76 |
+
target_size: (width, height) for cv2 convention, e.g. (512, 288).
|
| 77 |
+
"""
|
| 78 |
+
N, H, W, C = frames.shape
|
| 79 |
+
assert C == 3 and frames.dtype == np.uint8
|
| 80 |
+
w, h = target_size
|
| 81 |
+
if (W, H) == (w, h):
|
| 82 |
+
return frames
|
| 83 |
+
out = np.empty((N, h, w, 3), dtype=np.uint8)
|
| 84 |
+
if log:
|
| 85 |
+
log.info(f" Resizing RGB {frames.shape} -> (N, {h}, {w}, 3)...")
|
| 86 |
+
for i in range(N):
|
| 87 |
+
out[i] = cv2.resize(frames[i], (w, h), interpolation=interpolation)
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def save_processed_optimized(
|
| 92 |
+
output_dir: str,
|
| 93 |
+
radar_cube: Optional[np.ndarray] = None,
|
| 94 |
+
zed_rgb: Optional[np.ndarray] = None,
|
| 95 |
+
zed_depth_mm: Optional[np.ndarray] = None,
|
| 96 |
+
dji_rgb: Optional[np.ndarray] = None,
|
| 97 |
+
radar_timestamps: Optional[np.ndarray] = None,
|
| 98 |
+
zed_timestamps: Optional[np.ndarray] = None,
|
| 99 |
+
dji_timestamps: Optional[np.ndarray] = None,
|
| 100 |
+
sync_result=None,
|
| 101 |
+
metadata: dict = None,
|
| 102 |
+
rgb_codec: str = "mjpeg",
|
| 103 |
+
radar_filename: str = "radar.npy",
|
| 104 |
+
log=None,
|
| 105 |
+
):
|
| 106 |
+
"""
|
| 107 |
+
Save processed multimodal data using optimized formats for fast loading.
|
| 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
|
| 115 |
+
|
| 116 |
+
rgb_codec: Unused (kept for backward compatibility).
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
output_dir: Directory path to save files and metadata JSON
|
| 120 |
+
radar_cube: (N, doppler, elevation, azimuth, range) complex64
|
| 121 |
+
zed_rgb: (N, H, W, 3) uint8
|
| 122 |
+
zed_depth_mm: (N, H, W) float32
|
| 123 |
+
dji_rgb: (N, H, W, 3) uint8
|
| 124 |
+
radar_timestamps: (N,) float64 - milliseconds
|
| 125 |
+
zed_timestamps: (N,) float64 - milliseconds
|
| 126 |
+
dji_timestamps: (N,) float64 - milliseconds
|
| 127 |
+
sync_result: SyncResult or SyncResult3Way object
|
| 128 |
+
metadata: Optional dict of additional metadata
|
| 129 |
+
log: Logger instance
|
| 130 |
+
"""
|
| 131 |
+
import json
|
| 132 |
+
|
| 133 |
+
if log:
|
| 134 |
+
log.info(f"Saving to optimized format in directory: {output_dir}")
|
| 135 |
+
|
| 136 |
+
# Prepare metadata dictionary
|
| 137 |
+
meta_dict = {}
|
| 138 |
+
|
| 139 |
+
# Save radar data as NPY
|
| 140 |
+
if radar_cube is not None:
|
| 141 |
+
radar_path = os.path.join(output_dir, radar_filename)
|
| 142 |
+
np.save(radar_path, radar_cube)
|
| 143 |
+
|
| 144 |
+
meta_dict['radar'] = {
|
| 145 |
+
'shape': list(radar_cube.shape),
|
| 146 |
+
'dtype': str(radar_cube.dtype),
|
| 147 |
+
'shape_info': '(N, doppler, elevation, azimuth, range)',
|
| 148 |
+
'num_frames': int(radar_cube.shape[0]),
|
| 149 |
+
'file': radar_filename
|
| 150 |
+
}
|
| 151 |
+
if radar_timestamps is not None:
|
| 152 |
+
meta_dict['radar']['timestamps_ms'] = [float(t) for t in radar_timestamps]
|
| 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")
|
| 160 |
+
np.save(dji_path, dji_rgb_resized)
|
| 161 |
+
|
| 162 |
+
meta_dict["dji_rgb"] = {
|
| 163 |
+
"shape": list(dji_rgb_resized.shape),
|
| 164 |
+
"dtype": str(dji_rgb_resized.dtype),
|
| 165 |
+
"num_frames": int(dji_rgb_resized.shape[0]),
|
| 166 |
+
"file": "dji_rgb.npy",
|
| 167 |
+
"resolution": [896, 504],
|
| 168 |
+
"original_resolution": [dji_rgb.shape[2], dji_rgb.shape[1]],
|
| 169 |
+
}
|
| 170 |
+
if dji_timestamps is not None:
|
| 171 |
+
meta_dict["dji_rgb"]["timestamps_ms"] = [float(t) for t in dji_timestamps]
|
| 172 |
+
if log:
|
| 173 |
+
log.info(
|
| 174 |
+
f" DJI RGB: {dji_rgb.shape} -> resized {dji_rgb_resized.shape} -> dji_rgb.npy"
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# Save ZED RGB as NPY: resize to 896x504
|
| 178 |
+
if zed_rgb is not None:
|
| 179 |
+
zed_rgb_resized = _resize_rgb_to(zed_rgb, (896, 504), log=log)
|
| 180 |
+
zed_rgb_path = os.path.join(output_dir, "zed_rgb.npy")
|
| 181 |
+
np.save(zed_rgb_path, zed_rgb_resized)
|
| 182 |
+
|
| 183 |
+
meta_dict["zed_rgb"] = {
|
| 184 |
+
"shape": list(zed_rgb_resized.shape),
|
| 185 |
+
"dtype": str(zed_rgb_resized.dtype),
|
| 186 |
+
"num_frames": int(zed_rgb_resized.shape[0]),
|
| 187 |
+
"file": "zed_rgb.npy",
|
| 188 |
+
"resolution": [896, 504],
|
| 189 |
+
"original_resolution": [zed_rgb.shape[2], zed_rgb.shape[1]],
|
| 190 |
+
}
|
| 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:
|
| 198 |
+
zed_depth_path = os.path.join(output_dir, 'zed_depth.npy')
|
| 199 |
+
depth_uint16 = np.clip(zed_depth_mm, 0, 65535).astype(np.uint16)
|
| 200 |
+
np.save(zed_depth_path, depth_uint16)
|
| 201 |
+
|
| 202 |
+
meta_dict['zed_depth'] = {
|
| 203 |
+
'shape': list(zed_depth_mm.shape),
|
| 204 |
+
'dtype': 'uint16',
|
| 205 |
+
'original_dtype': str(zed_depth_mm.dtype),
|
| 206 |
+
'num_frames': int(zed_depth_mm.shape[0]),
|
| 207 |
+
'depth_units': 'millimeters',
|
| 208 |
+
'depth_mode': 'NEURAL_PLUS',
|
| 209 |
+
'file': 'zed_depth.npy'
|
| 210 |
+
}
|
| 211 |
+
if zed_timestamps is not None:
|
| 212 |
+
meta_dict['zed_depth']['timestamps_ms'] = [float(t) for t in zed_timestamps]
|
| 213 |
+
if log:
|
| 214 |
+
log.info(f" ZED Depth: {zed_depth_mm.shape} -> uint16 zed_depth.npy")
|
| 215 |
+
|
| 216 |
+
# Add synchronization info to metadata
|
| 217 |
+
if sync_result is not None:
|
| 218 |
+
sync_meta = {
|
| 219 |
+
'tolerance_ms': float(sync_result.tolerance_ms)
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
if hasattr(sync_result, 'triples'): # 3-way sync
|
| 223 |
+
radar_idx = [int(t[0]) for t in sync_result.triples]
|
| 224 |
+
zed_idx = [int(t[1]) for t in sync_result.triples]
|
| 225 |
+
dji_idx = [int(t[2]) for t in sync_result.triples]
|
| 226 |
+
sync_meta['sync_type'] = '3-way'
|
| 227 |
+
sync_meta['radar_indices'] = radar_idx
|
| 228 |
+
sync_meta['zed_indices'] = zed_idx
|
| 229 |
+
sync_meta['dji_indices'] = dji_idx
|
| 230 |
+
sync_meta['diffs_radar_zed_ms'] = [float(d) for d in sync_result.diffs_radar_zed_ms]
|
| 231 |
+
sync_meta['diffs_radar_dji_ms'] = [float(d) for d in sync_result.diffs_radar_dji_ms]
|
| 232 |
+
else: # 2-way sync
|
| 233 |
+
camera_idx = [int(p[0]) for p in sync_result.pairs]
|
| 234 |
+
radar_idx = [int(p[1]) for p in sync_result.pairs]
|
| 235 |
+
sync_meta['sync_type'] = '2-way'
|
| 236 |
+
sync_meta['camera_indices'] = camera_idx
|
| 237 |
+
sync_meta['radar_indices'] = radar_idx
|
| 238 |
+
sync_meta['diffs_ms'] = [float(d) for d in sync_result.diffs_ms]
|
| 239 |
+
|
| 240 |
+
meta_dict['sync'] = sync_meta
|
| 241 |
+
|
| 242 |
+
# Add optional metadata
|
| 243 |
+
if metadata:
|
| 244 |
+
meta_dict['metadata'] = metadata
|
| 245 |
+
|
| 246 |
+
# Save metadata to JSON
|
| 247 |
+
metadata_path = os.path.join(output_dir, 'metadata.json')
|
| 248 |
+
with open(metadata_path, 'w') as f:
|
| 249 |
+
json.dump(meta_dict, f, indent=2)
|
| 250 |
+
|
| 251 |
+
if log:
|
| 252 |
+
log.info(f"Metadata saved to: metadata.json")
|
| 253 |
+
log.info(f"Optimized files saved successfully in: {output_dir}")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def process_sequence(
|
| 257 |
+
sequence_dir: str,
|
| 258 |
+
no_radar: bool,
|
| 259 |
+
no_camera: bool,
|
| 260 |
+
no_dji: bool,
|
| 261 |
+
rgb_codec: str = "mjpeg",
|
| 262 |
+
no_doppler: bool = False,
|
| 263 |
+
pcd: bool = True,
|
| 264 |
+
base_output_dir: str = "processed",
|
| 265 |
+
log=None,
|
| 266 |
+
):
|
| 267 |
+
"""
|
| 268 |
+
Process a single sequence directory.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
sequence_dir: Path to sequence directory containing sensor data files
|
| 272 |
+
no_radar: Skip radar processing
|
| 273 |
+
no_camera: Skip ZED camera (RGB + depth) processing
|
| 274 |
+
no_dji: Skip DJI RGB processing
|
| 275 |
+
log: Logger instance
|
| 276 |
+
"""
|
| 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}")
|
| 285 |
+
log.info("="*80)
|
| 286 |
+
|
| 287 |
+
# Validate options
|
| 288 |
+
if no_radar and no_camera and no_dji and not pcd:
|
| 289 |
+
log.error("Cannot skip all modalities. At least one must be processed.")
|
| 290 |
+
return False, 0, "all modalities skipped"
|
| 291 |
+
|
| 292 |
+
# Log processing mode
|
| 293 |
+
processing_modes = []
|
| 294 |
+
if not no_radar:
|
| 295 |
+
processing_modes.append("radar")
|
| 296 |
+
if not no_camera:
|
| 297 |
+
processing_modes.append("ZED RGB+depth")
|
| 298 |
+
if not no_dji:
|
| 299 |
+
processing_modes.append("DJI RGB")
|
| 300 |
+
if pcd:
|
| 301 |
+
processing_modes.append("canonical 3-D radar point clouds")
|
| 302 |
+
log.info(f"Processing modes: {', '.join(processing_modes)}")
|
| 303 |
+
log.info(f"Synchronization: 3-way (radar + ZED + DJI), tolerance={tolerance_ms}ms")
|
| 304 |
+
|
| 305 |
+
# Auto-detect files
|
| 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 |
+
|
| 319 |
+
# Create output directory
|
| 320 |
+
sequence_basename = os.path.basename(os.path.normpath(sequence_dir))
|
| 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)...")
|
| 327 |
+
sync_result = None
|
| 328 |
+
try:
|
| 329 |
+
sync_result = synchronize_timestamps_3way(
|
| 330 |
+
radar_h5=radar_h5,
|
| 331 |
+
zed_timestamps_h5=zed_timestamps_h5,
|
| 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}"
|
| 340 |
+
log.error(err)
|
| 341 |
+
return False, 0, err
|
| 342 |
+
log.info(f"Synchronized {len(sync_result.triples)} triples")
|
| 343 |
+
|
| 344 |
+
if len(sync_result.triples) == 0:
|
| 345 |
+
log.warning("No synchronized triples found. Skipping this sequence.")
|
| 346 |
+
return False, 0, "no synchronized triples"
|
| 347 |
+
|
| 348 |
+
# Special handling for Razor-1 sequence: filter out frames with ZED index > 10000
|
| 349 |
+
sequence_name = os.path.basename(os.path.normpath(sequence_dir))
|
| 350 |
+
if sequence_name == "Razor-1":
|
| 351 |
+
zed_indices = np.array([t[1] for t in sync_result.triples], dtype=np.int64)
|
| 352 |
+
original_count = len(zed_indices)
|
| 353 |
+
valid_mask = zed_indices <= 10000
|
| 354 |
+
|
| 355 |
+
filtered_count = int(valid_mask.sum())
|
| 356 |
+
if filtered_count < original_count:
|
| 357 |
+
log.warning(f"Razor-1 sequence: Filtered out {original_count - filtered_count} frames with ZED index > 10000")
|
| 358 |
+
log.info(f"Remaining frames: {filtered_count}")
|
| 359 |
+
|
| 360 |
+
# Create new SyncResult3Way with filtered data
|
| 361 |
+
filtered_triples = [t for t, valid in zip(sync_result.triples, valid_mask) if valid]
|
| 362 |
+
filtered_diffs_radar_zed = np.array(sync_result.diffs_radar_zed_ms)[valid_mask]
|
| 363 |
+
filtered_diffs_radar_dji = np.array(sync_result.diffs_radar_dji_ms)[valid_mask]
|
| 364 |
+
|
| 365 |
+
sync_result = SyncResult3Way(
|
| 366 |
+
triples=filtered_triples,
|
| 367 |
+
diffs_radar_zed_ms=filtered_diffs_radar_zed,
|
| 368 |
+
diffs_radar_dji_ms=filtered_diffs_radar_dji,
|
| 369 |
+
radar_count=sync_result.radar_count,
|
| 370 |
+
zed_count=sync_result.zed_count,
|
| 371 |
+
dji_count=sync_result.dji_count,
|
| 372 |
+
tolerance_ms=sync_result.tolerance_ms
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
if len(sync_result.triples) == 0:
|
| 376 |
+
log.warning("Razor-1 sequence: No frames left after filtering. Skipping this sequence.")
|
| 377 |
+
return False, 0, "Razor-1: no frames after filter"
|
| 378 |
+
|
| 379 |
+
sync_csv_path = os.path.join(output_dir, "sync_triples.csv")
|
| 380 |
+
save_sync_csv(sync_csv_path, sync_result)
|
| 381 |
+
log.info(f"Saved sync triples: {sync_csv_path}")
|
| 382 |
+
radar_indices = np.array([t[0] for t in sync_result.triples], dtype=np.int64)
|
| 383 |
+
zed_indices = np.array([t[1] for t in sync_result.triples], dtype=np.int64)
|
| 384 |
+
dji_indices = np.array([t[2] for t in sync_result.triples], dtype=np.int64)
|
| 385 |
+
|
| 386 |
+
# Load timestamps for metadata
|
| 387 |
+
log.info("Loading timestamps for metadata...")
|
| 388 |
+
try:
|
| 389 |
+
with h5py.File(radar_h5, 'r') as f:
|
| 390 |
+
radar_timestamps = f['timestamps_ms'][:][radar_indices]
|
| 391 |
+
with h5py.File(zed_timestamps_h5, 'r') as f:
|
| 392 |
+
zed_timestamps = f['timestamps_ms'][:][zed_indices]
|
| 393 |
+
with h5py.File(dji_timestamps_h5, 'r') as f:
|
| 394 |
+
dji_timestamps = f['timestamps_ms'][:][dji_indices]
|
| 395 |
+
except (OSError, ValueError) as e:
|
| 396 |
+
err = f"Failed to load timestamps for metadata: {e}"
|
| 397 |
+
log.error(err)
|
| 398 |
+
return False, 0, err
|
| 399 |
+
|
| 400 |
+
if any(Path(sequence_dir).glob("max30105_*.h5")):
|
| 401 |
+
extract_max30105_for_sequence(
|
| 402 |
+
sequence_dir, radar_indices, radar_timestamps, output_dir,
|
| 403 |
+
max_tolerance_ms=tolerance_ms, enforce_one_to_one=enforce_one_to_one, log=log,
|
| 404 |
+
)
|
| 405 |
+
else:
|
| 406 |
+
log.info("No MAX30105 file; skipping optional sensor")
|
| 407 |
+
|
| 408 |
+
# Initialize data holders
|
| 409 |
+
radar_cube_arr = None
|
| 410 |
+
zed_rgb = None
|
| 411 |
+
zed_depth_mm = None
|
| 412 |
+
dji_rgb = None
|
| 413 |
+
|
| 414 |
+
# Step 2: Process radar data
|
| 415 |
+
if not no_radar or pcd:
|
| 416 |
+
log.info(f"Loading {len(radar_indices)} radar frames...")
|
| 417 |
+
radar_raw_frames = load_radar_frames(radar_h5, radar_indices)
|
| 418 |
+
log.info(f"Radar raw shape: {radar_raw_frames.shape}, dtype: {radar_raw_frames.dtype}")
|
| 419 |
+
|
| 420 |
+
radar_cubes = []
|
| 421 |
+
pcd_dir = os.path.join(output_dir, "pcd")
|
| 422 |
+
if pcd:
|
| 423 |
+
os.makedirs(pcd_dir, exist_ok=True)
|
| 424 |
+
with tqdm(total=len(radar_raw_frames), desc="Radar processing", unit="frame") as pbar:
|
| 425 |
+
for frame_index, frame in enumerate(radar_raw_frames):
|
| 426 |
+
if not no_radar:
|
| 427 |
+
radar_cubes.append(process_single_frame(frame, no_doppler=no_doppler))
|
| 428 |
+
if pcd:
|
| 429 |
+
np.save(os.path.join(pcd_dir, f"pcd_{frame_index}.npy"), extract_point_cloud_from_frame(frame))
|
| 430 |
+
pbar.update(1)
|
| 431 |
+
if not no_radar:
|
| 432 |
+
radar_cube_arr = np.stack(radar_cubes, axis=0)
|
| 433 |
+
log.info(f"Radar cube shape: {radar_cube_arr.shape}, dtype: {radar_cube_arr.dtype}")
|
| 434 |
+
else:
|
| 435 |
+
log.info("Skipping radar processing (--no-radar)")
|
| 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}")
|
| 449 |
+
else:
|
| 450 |
+
log.info("Skipping ZED RGB/depth extraction (--no-camera)")
|
| 451 |
+
|
| 452 |
+
# Step 4: Extract DJI RGB
|
| 453 |
+
if not no_dji:
|
| 454 |
+
log.info(f"Extracting {len(dji_indices)} DJI RGB frames from video...")
|
| 455 |
+
dji_rgb = extract_dji_rgb(
|
| 456 |
+
video_path=dji_video_path,
|
| 457 |
+
frame_indices=dji_indices,
|
| 458 |
+
)
|
| 459 |
+
log.info(f"DJI RGB shape: {dji_rgb.shape}, dtype: {dji_rgb.dtype}")
|
| 460 |
+
else:
|
| 461 |
+
log.info("Skipping DJI RGB extraction (--no-dji)")
|
| 462 |
+
|
| 463 |
+
# Step 5: Save output using optimized format
|
| 464 |
+
log.info("Saving to optimized format...")
|
| 465 |
+
|
| 466 |
+
metadata = {
|
| 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 |
+
|
| 475 |
+
save_processed_optimized(
|
| 476 |
+
output_dir=output_dir,
|
| 477 |
+
radar_cube=radar_cube_arr,
|
| 478 |
+
zed_rgb=zed_rgb,
|
| 479 |
+
zed_depth_mm=zed_depth_mm,
|
| 480 |
+
dji_rgb=dji_rgb,
|
| 481 |
+
radar_timestamps=radar_timestamps,
|
| 482 |
+
zed_timestamps=zed_timestamps,
|
| 483 |
+
dji_timestamps=dji_timestamps,
|
| 484 |
+
sync_result=sync_result,
|
| 485 |
+
metadata=metadata,
|
| 486 |
+
rgb_codec=rgb_codec,
|
| 487 |
+
radar_filename="radar_no_doppler.npy" if no_doppler else "radar.npy",
|
| 488 |
+
log=log,
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
log.info("Sequence processing complete.")
|
| 492 |
+
log.info(f"Output directory: {os.path.abspath(output_dir)}")
|
| 493 |
+
|
| 494 |
+
# Return success status and number of synced frames
|
| 495 |
+
num_synced_frames = len(sync_result.triples)
|
| 496 |
+
return True, num_synced_frames, ""
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def main(
|
| 500 |
+
dataset: str,
|
| 501 |
+
sequences: Optional[list[str]] = None,
|
| 502 |
+
no_radar: bool = False,
|
| 503 |
+
no_camera: bool = False,
|
| 504 |
+
no_dji: bool = False,
|
| 505 |
+
list_unprocessed: bool = False,
|
| 506 |
+
rgb_codec: str = "mjpeg",
|
| 507 |
+
no_doppler: bool = False,
|
| 508 |
+
pcd: bool = True,
|
| 509 |
+
output_dir: str = "processed",
|
| 510 |
+
):
|
| 511 |
+
"""
|
| 512 |
+
Process multimodal sensor data from a dataset containing multiple sequences.
|
| 513 |
+
|
| 514 |
+
Pipeline for each sequence:
|
| 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)
|
| 524 |
+
- enforce_one_to_one: True (fixed)
|
| 525 |
+
|
| 526 |
+
3. Extract and process synchronized frames:
|
| 527 |
+
- Radar: Process AWR1843 raw data to Range-Doppler-Azimuth-Elevation cube
|
| 528 |
+
- ZED: Extract RGB (LEFT camera) + depth maps (millimeters, confidence=100)
|
| 529 |
+
- DJI: Extract RGB frames
|
| 530 |
+
|
| 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
|
| 538 |
+
- metadata.json: Shapes, dtypes, timestamps, sync indices
|
| 539 |
+
- sync_triples.csv: Frame index mapping (radar, ZED, DJI)
|
| 540 |
+
- pcd/pcd_<index>.npy: Canonical 3-D radar points (default)
|
| 541 |
+
|
| 542 |
+
rgb_codec: Unused (kept for backward compatibility).
|
| 543 |
+
|
| 544 |
+
Args:
|
| 545 |
+
dataset: Path to dataset directory containing sequence subdirectories (required)
|
| 546 |
+
sequences: List of specific sequence names to process. If not provided, processes all
|
| 547 |
+
sequences found in the dataset directory. If provided, processes only the
|
| 548 |
+
specified sequences.
|
| 549 |
+
no_radar: Skip radar processing
|
| 550 |
+
no_camera: Skip ZED camera (RGB + depth) processing
|
| 551 |
+
no_dji: Skip DJI RGB processing
|
| 552 |
+
no_doppler: Keep only chirp 0 and skip the Doppler FFT.
|
| 553 |
+
pcd: Save a canonical 3-D point cloud for every synchronized radar frame (default: True).
|
| 554 |
+
list_unprocessed: If True, only list dataset sequences not yet in output_dir and exit
|
| 555 |
+
rgb_codec: "ffv1" or "mjpeg" for RGB video encoding (mjpeg = faster loading)
|
| 556 |
+
output_dir: Base directory where processed sequences are written
|
| 557 |
+
|
| 558 |
+
Examples:
|
| 559 |
+
# Process all sequences in Data directory
|
| 560 |
+
python processor.py --dataset Data
|
| 561 |
+
|
| 562 |
+
# Process specific sequences only
|
| 563 |
+
python processor.py --dataset Data --sequences seq1 seq2 seq3
|
| 564 |
+
|
| 565 |
+
# Process without radar
|
| 566 |
+
python processor.py --dataset Data --no-radar
|
| 567 |
+
|
| 568 |
+
# Process only camera data
|
| 569 |
+
python processor.py --dataset Data --no-radar --no-dji
|
| 570 |
+
|
| 571 |
+
# Skip point clouds if only array outputs are needed
|
| 572 |
+
python processor.py --dataset Data --no-pcd
|
| 573 |
+
"""
|
| 574 |
+
log = setup_logging("Processor")
|
| 575 |
+
|
| 576 |
+
log.info("=" * 80)
|
| 577 |
+
log.info("MobiCom Multimodal Dataset Processor")
|
| 578 |
+
log.info("=" * 80)
|
| 579 |
+
log.info(f"Dataset path: {dataset}")
|
| 580 |
+
log.info("Output format: Optimized (NPY for radar and RGB, ZED depth uint16)")
|
| 581 |
+
log.info(f"Base output directory: {output_dir}")
|
| 582 |
+
|
| 583 |
+
# Validate dataset path
|
| 584 |
+
if not os.path.isdir(dataset):
|
| 585 |
+
log.error(f"Dataset directory not found: {dataset}")
|
| 586 |
+
return
|
| 587 |
+
|
| 588 |
+
# Validate options
|
| 589 |
+
if no_radar and no_camera and no_dji and not pcd and not list_unprocessed:
|
| 590 |
+
log.error("Cannot skip all modalities. At least one must be processed.")
|
| 591 |
+
return
|
| 592 |
+
|
| 593 |
+
# Get list of sequences to process
|
| 594 |
+
if sequences is None or len(sequences) == 0:
|
| 595 |
+
# Process all subdirectories in dataset
|
| 596 |
+
sequences = [d for d in os.listdir(dataset)
|
| 597 |
+
if os.path.isdir(os.path.join(dataset, d))]
|
| 598 |
+
sequences.sort()
|
| 599 |
+
log.info(f"Found {len(sequences)} sequences in dataset: {sequences}")
|
| 600 |
+
else:
|
| 601 |
+
log.info(f"Processing {len(sequences)} specified sequences: {sequences}")
|
| 602 |
+
|
| 603 |
+
if list_unprocessed:
|
| 604 |
+
processed_dir = output_dir
|
| 605 |
+
done = set()
|
| 606 |
+
if os.path.isdir(processed_dir):
|
| 607 |
+
for name in os.listdir(processed_dir):
|
| 608 |
+
meta = os.path.join(processed_dir, name, "metadata.json")
|
| 609 |
+
if os.path.isfile(meta):
|
| 610 |
+
done.add(name)
|
| 611 |
+
unprocessed = [s for s in sequences if s not in done]
|
| 612 |
+
log.info(f"Sequences not yet processed ({len(unprocessed)}): {unprocessed}")
|
| 613 |
+
return
|
| 614 |
+
|
| 615 |
+
# Process each sequence
|
| 616 |
+
success_count = 0
|
| 617 |
+
total_synced_frames = 0
|
| 618 |
+
failed_sequences = []
|
| 619 |
+
|
| 620 |
+
for i, seq_name in enumerate(sequences, 1):
|
| 621 |
+
seq_path = os.path.join(dataset, seq_name)
|
| 622 |
+
|
| 623 |
+
if not os.path.isdir(seq_path):
|
| 624 |
+
log.warning(f"Sequence directory not found, skipping: {seq_path}")
|
| 625 |
+
failed_sequences.append((seq_name, "directory not found", 0))
|
| 626 |
+
continue
|
| 627 |
+
|
| 628 |
+
log.info(f"\n[{i}/{len(sequences)}] Processing sequence: {seq_name}")
|
| 629 |
+
|
| 630 |
+
success, num_frames, reason = process_sequence(
|
| 631 |
+
sequence_dir=seq_path,
|
| 632 |
+
no_radar=no_radar,
|
| 633 |
+
no_camera=no_camera,
|
| 634 |
+
no_dji=no_dji,
|
| 635 |
+
rgb_codec=rgb_codec,
|
| 636 |
+
no_doppler=no_doppler,
|
| 637 |
+
pcd=pcd,
|
| 638 |
+
base_output_dir=output_dir,
|
| 639 |
+
log=log,
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
if success:
|
| 643 |
+
success_count += 1
|
| 644 |
+
total_synced_frames += num_frames
|
| 645 |
+
log.info(f"✓ Successfully processed: {seq_name} ({num_frames} synced frames)")
|
| 646 |
+
else:
|
| 647 |
+
failed_sequences.append((seq_name, reason or "processing failed", num_frames))
|
| 648 |
+
log.warning(f"✗ Failed to process: {seq_name}")
|
| 649 |
+
|
| 650 |
+
# Summary
|
| 651 |
+
log.info("\n" + "="*80)
|
| 652 |
+
log.info("Processing Summary")
|
| 653 |
+
log.info("="*80)
|
| 654 |
+
log.info(f"Total sequences: {len(sequences)}")
|
| 655 |
+
log.info(f"Successfully processed: {success_count}")
|
| 656 |
+
log.info(f"Failed: {len(failed_sequences)}")
|
| 657 |
+
log.info(f"Total synced frames saved: {total_synced_frames}")
|
| 658 |
+
|
| 659 |
+
if failed_sequences:
|
| 660 |
+
log.warning("\nFailed sequences:")
|
| 661 |
+
for seq_name, reason, _ in failed_sequences:
|
| 662 |
+
log.warning(f" - {seq_name}: {reason}")
|
| 663 |
+
|
| 664 |
+
log.info(f"\nOutput directory: {os.path.abspath(output_dir)}")
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
if __name__ == "__main__":
|
| 668 |
+
tyro.cli(main)
|
processing_code/requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python dependencies for processor.py and the canonical 3-D point-cloud output.
|
| 2 |
+
numpy>=1.26
|
| 3 |
+
opencv-python>=4.8
|
| 4 |
+
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/
|
processing_code/utils/extract_camera_data.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
processing_code/utils/extract_dji_data.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from typing import Iterable
|
| 4 |
+
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
log = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def extract_dji_rgb(
|
| 13 |
+
video_path: str,
|
| 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}")
|
| 32 |
+
|
| 33 |
+
indices = np.asarray(list(frame_indices), dtype=np.int64)
|
| 34 |
+
if indices.size == 0:
|
| 35 |
+
return np.empty((0, 0, 0, 3), dtype=np.uint8)
|
| 36 |
+
|
| 37 |
+
# Ensure indices are sorted and unique
|
| 38 |
+
indices = np.unique(indices)
|
| 39 |
+
indices_set = set(indices.tolist())
|
| 40 |
+
|
| 41 |
+
# Open video
|
| 42 |
+
cap = cv2.VideoCapture(video_path)
|
| 43 |
+
if not cap.isOpened():
|
| 44 |
+
raise RuntimeError(f"Failed to open DJI video: {video_path}")
|
| 45 |
+
|
| 46 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 47 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 48 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 49 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 50 |
+
|
| 51 |
+
log.info(f"DJI video: {width}x{height} @ {fps:.2f} FPS, {total_frames} frames")
|
| 52 |
+
log.info(f"Extracting {len(indices)} frame indices (min={indices.min()}, max={indices.max()})")
|
| 53 |
+
|
| 54 |
+
rgb_frames = []
|
| 55 |
+
frame_idx = 0
|
| 56 |
+
extracted_count = 0
|
| 57 |
+
|
| 58 |
+
with tqdm(total=len(indices), desc="DJI extraction", unit="frame") as pbar:
|
| 59 |
+
while frame_idx < total_frames:
|
| 60 |
+
ret, frame = cap.read()
|
| 61 |
+
if not ret:
|
| 62 |
+
break
|
| 63 |
+
|
| 64 |
+
if frame_idx in indices_set:
|
| 65 |
+
# OpenCV reads in BGR, convert to RGB
|
| 66 |
+
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 67 |
+
rgb_frames.append(rgb)
|
| 68 |
+
extracted_count += 1
|
| 69 |
+
pbar.update(1)
|
| 70 |
+
if extracted_count == len(indices):
|
| 71 |
+
break
|
| 72 |
+
|
| 73 |
+
frame_idx += 1
|
| 74 |
+
|
| 75 |
+
cap.release()
|
| 76 |
+
log.info(f"Finished: Extracted {extracted_count}/{len(indices)} DJI frames from {frame_idx} total frames")
|
| 77 |
+
|
| 78 |
+
if not rgb_frames:
|
| 79 |
+
log.warning("No DJI frames were extracted!")
|
| 80 |
+
return np.empty((0, 0, 0, 3), dtype=np.uint8)
|
| 81 |
+
|
| 82 |
+
rgb_arr = np.stack(rgb_frames, axis=0)
|
| 83 |
+
log.info(f"Final DJI RGB array: {rgb_arr.shape}")
|
| 84 |
+
|
| 85 |
+
return rgb_arr
|
processing_code/utils/extract_max_data.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from typing import Optional, List, Dict
|
| 4 |
+
|
| 5 |
+
import h5py
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from utils.sync_timestamps import _pick_latest_file
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _load_max30105_h5(max_h5_path: str) -> Dict[str, np.ndarray]:
|
| 12 |
+
"""
|
| 13 |
+
Load MAX30105 timestamps and samples from HDF5.
|
| 14 |
+
|
| 15 |
+
Expected datasets:
|
| 16 |
+
- 'timestamps_ms' (milliseconds since Unix epoch)
|
| 17 |
+
- 'samples_uint32' with the same first dimension as timestamps
|
| 18 |
+
"""
|
| 19 |
+
with h5py.File(max_h5_path, "r") as f:
|
| 20 |
+
if "timestamps_ms" not in f:
|
| 21 |
+
raise ValueError(
|
| 22 |
+
f"'timestamps_ms' dataset not found in MAX30105 HDF5 file: {max_h5_path}"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
ts = np.asarray(f["timestamps_ms"][:], dtype=np.float64)
|
| 26 |
+
if ts.ndim != 1:
|
| 27 |
+
raise ValueError(
|
| 28 |
+
f"Expected 1D 'timestamps_ms' in {max_h5_path}, got shape {ts.shape}"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
data: Dict[str, np.ndarray] = {"timestamps_ms": ts}
|
| 32 |
+
|
| 33 |
+
# Main MAX30105 sample dataset (typically shape (N, 3) uint32)
|
| 34 |
+
if "samples_uint32" not in f:
|
| 35 |
+
raise ValueError(
|
| 36 |
+
f"'samples_uint32' dataset not found in MAX30105 HDF5 file: {max_h5_path}"
|
| 37 |
+
)
|
| 38 |
+
samples = np.asarray(f["samples_uint32"][:])
|
| 39 |
+
if samples.shape[0] != ts.shape[0]:
|
| 40 |
+
raise ValueError(
|
| 41 |
+
f"'samples_uint32' length {samples.shape[0]} does not match "
|
| 42 |
+
f"timestamps length {ts.shape[0]} in {max_h5_path}"
|
| 43 |
+
)
|
| 44 |
+
data["samples_uint32"] = samples
|
| 45 |
+
|
| 46 |
+
return data
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _align_max_to_radar(
|
| 50 |
+
radar_indices: np.ndarray,
|
| 51 |
+
radar_ts: np.ndarray,
|
| 52 |
+
max_data: Dict[str, np.ndarray],
|
| 53 |
+
max_tolerance_ms: float,
|
| 54 |
+
enforce_one_to_one: bool,
|
| 55 |
+
) -> Dict[str, np.ndarray]:
|
| 56 |
+
"""
|
| 57 |
+
For each synchronized radar timestamp, find the nearest MAX30105 sample.
|
| 58 |
+
|
| 59 |
+
Returns a dict with per-channel arrays for each present channel (e.g. 'samples_uint32'),
|
| 60 |
+
aligned to the subset of synchronized radar timestamps that could be matched within
|
| 61 |
+
`max_tolerance_ms`.
|
| 62 |
+
"""
|
| 63 |
+
max_ts = max_data["timestamps_ms"].astype(np.float64, copy=False)
|
| 64 |
+
|
| 65 |
+
matched_channels: Dict[str, List[np.ndarray]] = {
|
| 66 |
+
ch: [] for ch in max_data.keys() if ch != "timestamps_ms"
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
used_max = set() if enforce_one_to_one else None
|
| 70 |
+
|
| 71 |
+
for radar_idx, r_t in zip(radar_indices, radar_ts):
|
| 72 |
+
insert_idx = int(np.searchsorted(max_ts, r_t))
|
| 73 |
+
|
| 74 |
+
# Nearest neighbor search (optionally one-to-one)
|
| 75 |
+
cand0 = insert_idx - 1 if insert_idx > 0 else None
|
| 76 |
+
cand1 = insert_idx if insert_idx < len(max_ts) else None
|
| 77 |
+
|
| 78 |
+
best_idx: Optional[int] = None
|
| 79 |
+
best_abs = float("inf")
|
| 80 |
+
for cand in (cand0, cand1):
|
| 81 |
+
if cand is None:
|
| 82 |
+
continue
|
| 83 |
+
if enforce_one_to_one and cand in used_max:
|
| 84 |
+
continue
|
| 85 |
+
abs_diff = abs(float(max_ts[cand] - r_t))
|
| 86 |
+
if abs_diff < best_abs:
|
| 87 |
+
best_abs = abs_diff
|
| 88 |
+
best_idx = int(cand)
|
| 89 |
+
|
| 90 |
+
if best_idx is None:
|
| 91 |
+
continue
|
| 92 |
+
|
| 93 |
+
diff = float(r_t - max_ts[best_idx])
|
| 94 |
+
if abs(diff) > max_tolerance_ms:
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
for ch, lst in matched_channels.items():
|
| 98 |
+
lst.append(max_data[ch][best_idx])
|
| 99 |
+
|
| 100 |
+
if enforce_one_to_one:
|
| 101 |
+
used_max.add(best_idx)
|
| 102 |
+
|
| 103 |
+
out: Dict[str, np.ndarray] = {}
|
| 104 |
+
for ch, lst in matched_channels.items():
|
| 105 |
+
out[ch] = np.asarray(lst)
|
| 106 |
+
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def extract_max30105_for_sequence(
|
| 111 |
+
sequence_dir: str,
|
| 112 |
+
radar_indices: np.ndarray,
|
| 113 |
+
radar_timestamps: np.ndarray,
|
| 114 |
+
output_dir: str,
|
| 115 |
+
max_tolerance_ms: float = 50.0,
|
| 116 |
+
enforce_one_to_one: bool = True,
|
| 117 |
+
log: Optional[logging.Logger] = None,
|
| 118 |
+
) -> int:
|
| 119 |
+
"""
|
| 120 |
+
Extract MAX30105 samples aligned to synchronized radar timestamps for a sequence
|
| 121 |
+
and save them as max30105.npy in the given output directory.
|
| 122 |
+
"""
|
| 123 |
+
seq_name = os.path.basename(os.path.normpath(sequence_dir))
|
| 124 |
+
|
| 125 |
+
max_h5 = _pick_latest_file(sequence_dir, "max30105_*.h5")
|
| 126 |
+
if log:
|
| 127 |
+
log.info(f"MAX30105 H5: {max_h5}")
|
| 128 |
+
|
| 129 |
+
max_data = _load_max30105_h5(max_h5)
|
| 130 |
+
|
| 131 |
+
aligned = _align_max_to_radar(
|
| 132 |
+
radar_indices=radar_indices,
|
| 133 |
+
radar_ts=radar_timestamps,
|
| 134 |
+
max_data=max_data,
|
| 135 |
+
max_tolerance_ms=max_tolerance_ms,
|
| 136 |
+
enforce_one_to_one=enforce_one_to_one,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
any_channel = next((arr for arr in aligned.values()), None)
|
| 140 |
+
num_matched = int(any_channel.shape[0]) if any_channel is not None else 0
|
| 141 |
+
if log:
|
| 142 |
+
log.info(
|
| 143 |
+
f"Matched {num_matched} MAX30105 samples to synchronized radar frames."
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
samples = aligned.get("samples_uint32")
|
| 147 |
+
if samples is None:
|
| 148 |
+
if log:
|
| 149 |
+
log.warning(
|
| 150 |
+
"No 'samples_uint32' channel found in aligned MAX30105 data; nothing saved."
|
| 151 |
+
)
|
| 152 |
+
return num_matched
|
| 153 |
+
|
| 154 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 155 |
+
out_path = os.path.join(output_dir, "max30105.npy")
|
| 156 |
+
np.save(out_path, samples)
|
| 157 |
+
|
| 158 |
+
if log:
|
| 159 |
+
log.info(f"Saved extracted MAX30105 readings to: {out_path}")
|
| 160 |
+
|
| 161 |
+
return num_matched
|
| 162 |
+
|
processing_code/utils/extract_pcd.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Canonical 3-D radar point-cloud extraction used by ``processor --pcd``."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from utils.extract_radar_data import iiqq_to_iq, mimo
|
| 6 |
+
|
| 7 |
+
RANGE_FFT_SIZE = 256
|
| 8 |
+
DOPPLER_FFT_SIZE = 64
|
| 9 |
+
AZIMUTH_FFT_SIZE = 32
|
| 10 |
+
ELEVATION_FFT_SIZE = 8
|
| 11 |
+
RANGE_RES_M = 0.04375
|
| 12 |
+
CAMERA_POS_IN_RADAR_M = np.array([-0.08, 0.10, 0.05], dtype=np.float32)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _hann(length: int) -> np.ndarray:
|
| 16 |
+
return np.ones(length, dtype=np.float32) if length <= 2 else np.hanning(length).astype(np.float32)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _fft(data: np.ndarray, axis: int, size: int | None = None, shift: bool = False) -> np.ndarray:
|
| 20 |
+
shape = [1] * data.ndim
|
| 21 |
+
shape[axis] = data.shape[axis]
|
| 22 |
+
result = np.fft.fft(data * _hann(data.shape[axis]).reshape(shape), n=size, axis=axis)
|
| 23 |
+
return np.fft.fftshift(result, axes=axis) if shift else result
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _training(values: np.ndarray, index: int, win: int, guard: int, cyclic: bool):
|
| 27 |
+
left = np.arange(index - guard - win, index - guard)
|
| 28 |
+
right = np.arange(index + guard + 1, index + guard + win + 1)
|
| 29 |
+
if cyclic:
|
| 30 |
+
return values[left % len(values)], values[right % len(values)]
|
| 31 |
+
if left[0] < 0 or right[-1] >= len(values):
|
| 32 |
+
return None, None
|
| 33 |
+
return values[left], values[right]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _cfar(values: np.ndarray, axis: int, mode: int, win: int, guard: int, noise_div: int, cyclic: bool, threshold_db: float) -> np.ndarray:
|
| 37 |
+
data = np.moveaxis(values, axis, -1)
|
| 38 |
+
detected = np.zeros_like(data, dtype=bool)
|
| 39 |
+
scale = 10.0 ** (threshold_db / 20.0)
|
| 40 |
+
for outer in np.ndindex(data.shape[:-1]):
|
| 41 |
+
row = data[outer]
|
| 42 |
+
for cut in range(len(row)):
|
| 43 |
+
left, right = _training(row, cut, win, guard, cyclic)
|
| 44 |
+
if left is None:
|
| 45 |
+
continue
|
| 46 |
+
left_sum, right_sum = float(left.sum()), float(right.sum())
|
| 47 |
+
if mode == 0:
|
| 48 |
+
noise = (left_sum + right_sum) / (2**noise_div)
|
| 49 |
+
elif mode == 1:
|
| 50 |
+
noise = max(left_sum, right_sum) / (2**noise_div)
|
| 51 |
+
else:
|
| 52 |
+
noise = min(left_sum, right_sum) / (2**noise_div)
|
| 53 |
+
detected[outer + (cut,)] = row[cut] > noise * scale
|
| 54 |
+
return np.moveaxis(detected, -1, axis)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _local_maxima(values: np.ndarray) -> np.ndarray:
|
| 58 |
+
rows, cols = values.shape
|
| 59 |
+
output = np.zeros_like(values, dtype=bool)
|
| 60 |
+
for row in range(rows):
|
| 61 |
+
for col in range(cols):
|
| 62 |
+
center = values[row, col]
|
| 63 |
+
maximum = True
|
| 64 |
+
for dr in (-1, 0, 1):
|
| 65 |
+
for dc in (-1, 0, 1):
|
| 66 |
+
if dr == dc == 0:
|
| 67 |
+
continue
|
| 68 |
+
rr = (row + dr) % rows
|
| 69 |
+
cc = col + dc
|
| 70 |
+
if cc < 0 or cc >= cols:
|
| 71 |
+
continue
|
| 72 |
+
if values[rr, cc] >= center:
|
| 73 |
+
maximum = False
|
| 74 |
+
break
|
| 75 |
+
if not maximum:
|
| 76 |
+
break
|
| 77 |
+
output[row, col] = maximum
|
| 78 |
+
return output
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _xyz(snapshot: np.ndarray, range_m: float) -> np.ndarray | None:
|
| 82 |
+
window = _hann(2)[:, None] * _hann(8)[None, :]
|
| 83 |
+
spectrum = np.fft.fftshift(np.fft.fft2(snapshot * window, s=(ELEVATION_FFT_SIZE, AZIMUTH_FFT_SIZE)), axes=(0, 1))
|
| 84 |
+
elevation, azimuth = np.unravel_index(np.abs(spectrum).argmax(), spectrum.shape)
|
| 85 |
+
ux = float(np.clip(2.0 * (azimuth - AZIMUTH_FFT_SIZE // 2) / AZIMUTH_FFT_SIZE, -1, 1))
|
| 86 |
+
uy = float(np.clip(2.0 * (elevation - ELEVATION_FFT_SIZE // 2) / ELEVATION_FFT_SIZE, -1, 1))
|
| 87 |
+
uz_sq = 1.0 - ux * ux - uy * uy
|
| 88 |
+
if uz_sq <= 0:
|
| 89 |
+
return None
|
| 90 |
+
return np.array([range_m * ux, range_m * uy, range_m * np.sqrt(uz_sq)], dtype=np.float32)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _nearest_per_ray(points: np.ndarray) -> np.ndarray:
|
| 94 |
+
if len(points) == 0:
|
| 95 |
+
return np.empty((0, 3), dtype=np.float32)
|
| 96 |
+
ranges = np.linalg.norm(points, axis=1)
|
| 97 |
+
valid = ranges > 1e-6
|
| 98 |
+
points, ranges = points[valid], ranges[valid]
|
| 99 |
+
chosen: dict[tuple[float, float, float], int] = {}
|
| 100 |
+
for index, (direction, distance) in enumerate(zip(np.round(points / ranges[:, None], 6), ranges)):
|
| 101 |
+
key = tuple(float(x) for x in direction)
|
| 102 |
+
if key not in chosen or distance < ranges[chosen[key]]:
|
| 103 |
+
chosen[key] = index
|
| 104 |
+
return points[np.array(sorted(chosen.values()), dtype=np.int64)].astype(np.float32)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def extract_point_cloud_from_frame(iiqq_frame: np.ndarray) -> np.ndarray:
|
| 108 |
+
"""Return canonical ``(N, 3) float32`` camera-frame XYZ radar points."""
|
| 109 |
+
virtual = mimo(iiqq_to_iq(iiqq_frame))
|
| 110 |
+
range_fft = _fft(virtual, axis=-1, size=RANGE_FFT_SIZE)
|
| 111 |
+
doppler_fft = _fft(range_fft, axis=0, size=DOPPLER_FFT_SIZE, shift=True)
|
| 112 |
+
rd_map = np.sqrt(np.sum(np.abs(doppler_fft) ** 2, axis=(1, 2))).astype(np.float32)
|
| 113 |
+
mask = _cfar(rd_map, 1, 2, 8, 4, 3, False, 15.0)
|
| 114 |
+
mask &= _cfar(rd_map, 0, 0, 4, 2, 3, True, 15.0)
|
| 115 |
+
mask &= _local_maxima(rd_map)
|
| 116 |
+
points = []
|
| 117 |
+
for doppler, range_bin in zip(*np.nonzero(mask)):
|
| 118 |
+
range_m = float(range_bin) * RANGE_RES_M
|
| 119 |
+
if range_m > 10.60:
|
| 120 |
+
continue
|
| 121 |
+
point = _xyz(doppler_fft[doppler, :, :, range_bin], range_m)
|
| 122 |
+
if point is not None:
|
| 123 |
+
points.append(point)
|
| 124 |
+
if not points:
|
| 125 |
+
return np.empty((0, 3), dtype=np.float32)
|
| 126 |
+
return (_nearest_per_ray(np.stack(points, axis=0)) - CAMERA_POS_IN_RADAR_M).astype(np.float32)
|
processing_code/utils/extract_radar_data.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
def iiqq_to_iq(iiqq: np.ndarray) -> np.ndarray:
|
| 4 |
+
"""
|
| 5 |
+
Convert interleaved IIQQ radar data to complex IQ format.
|
| 6 |
+
|
| 7 |
+
Args:
|
| 8 |
+
iiqq: Input array with shape [..., N] where N is divisible by 4
|
| 9 |
+
|
| 10 |
+
Returns:
|
| 11 |
+
Complex array with shape [..., N/2] and dtype complex64
|
| 12 |
+
"""
|
| 13 |
+
if iiqq.dtype == np.complex64:
|
| 14 |
+
return iiqq
|
| 15 |
+
|
| 16 |
+
shape = (*iiqq.shape[:-1], iiqq.shape[-1] // 2)
|
| 17 |
+
iq = np.zeros(shape, dtype=np.complex64)
|
| 18 |
+
iq[..., 0::2] = 1j * iiqq[..., 0::4] + iiqq[..., 2::4]
|
| 19 |
+
iq[..., 1::2] = 1j * iiqq[..., 1::4] + iiqq[..., 3::4]
|
| 20 |
+
return iq
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def mimo(data: np.ndarray) -> np.ndarray:
|
| 24 |
+
"""
|
| 25 |
+
Convert raw radar data to MIMO virtual array format.
|
| 26 |
+
Maps (batch, doppler, tx, rx, range) -> (batch, doppler, elevation, azimuth, range).
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
data: Input array with shape [..., tx, rx, range]
|
| 30 |
+
tx=3, rx=4
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
Virtual array with shape [..., 2, 8, range]
|
| 34 |
+
"""
|
| 35 |
+
if len(data.shape) == 5:
|
| 36 |
+
# batch, doppler, tx, rx, range = data.shape
|
| 37 |
+
# mimo_data = np.zeros((batch, doppler, 2, 8, range), dtype=np.complex64)
|
| 38 |
+
# mimo_data[:, :, 0, 2:6, :] = data[:, :, 1, :, :]
|
| 39 |
+
# mimo_data[:, :, 1, 0:4, :] = data[:, :, 0, :, :]
|
| 40 |
+
# mimo_data[:, :, 1, 4:8, :] = data[:, :, 2, :, :]
|
| 41 |
+
raise NotImplementedError(f"Batch operation not supported.")
|
| 42 |
+
elif len(data.shape) == 4:
|
| 43 |
+
doppler, tx, rx, range = data.shape
|
| 44 |
+
mimo_data = np.zeros((doppler, 2, 8, range), dtype=np.complex64)
|
| 45 |
+
mimo_data[:, 0, 2:6, :] = data[:, 1, :, :]
|
| 46 |
+
mimo_data[:, 1, 0:4, :] = data[:, 0, :, :]
|
| 47 |
+
mimo_data[:, 1, 4:8, :] = data[:, 2, :, :]
|
| 48 |
+
else:
|
| 49 |
+
raise ValueError(f"Expected 4D or 5D input, got shape {data.shape}")
|
| 50 |
+
|
| 51 |
+
return mimo_data
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def fft_w_shift(data: np.ndarray, dim: int = -1, shift: bool = False) -> np.ndarray:
|
| 55 |
+
"""
|
| 56 |
+
Apply FFT to data with shift to center the zero frequency component.
|
| 57 |
+
"""
|
| 58 |
+
fft_array = np.fft.fft(data, axis=dim)
|
| 59 |
+
if shift:
|
| 60 |
+
fft_array = np.fft.fftshift(fft_array, axes=dim)
|
| 61 |
+
return fft_array
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def range_doppler_fft(data: np.ndarray) -> np.ndarray:
|
| 65 |
+
"""
|
| 66 |
+
Apply FFT to data in range and doppler dimensions.
|
| 67 |
+
"""
|
| 68 |
+
range_fft = fft_w_shift(data, dim=-1, shift=False)
|
| 69 |
+
doppler_fft = fft_w_shift(range_fft, dim=0, shift=True)
|
| 70 |
+
return doppler_fft
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def azimuth_elevation_fft(data: np.ndarray) -> np.ndarray:
|
| 74 |
+
"""
|
| 75 |
+
Apply FFT to data in azimuth and elevation dimensions.
|
| 76 |
+
"""
|
| 77 |
+
# Axis 1 is Elevation (size 2), Axis 2 is Azimuth (size 8)
|
| 78 |
+
elevation_fft = fft_w_shift(data, dim=1, shift=True)
|
| 79 |
+
azimuth_fft = fft_w_shift(elevation_fft, dim=2, shift=True)
|
| 80 |
+
return azimuth_fft
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def process_single_frame(iiqq: np.ndarray, no_doppler: bool = False) -> np.ndarray:
|
| 84 |
+
"""
|
| 85 |
+
Process a single (non-batched) frame of radar data.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
iiqq: Raw data with shape (doppler, tx, rx, range).
|
| 89 |
+
no_doppler: Keep only chirp 0 as a size-one Doppler axis and skip the
|
| 90 |
+
Doppler FFT. This is intentionally applied before any Doppler
|
| 91 |
+
transform; it is not a slice of the full Doppler FFT output.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
A complex cube with shape (doppler, elevation, azimuth, range). The
|
| 95 |
+
Doppler axis has length one when ``no_doppler`` is true.
|
| 96 |
+
"""
|
| 97 |
+
iq_data = iiqq_to_iq(iiqq)
|
| 98 |
+
# Maps (doppler, tx, rx, range) -> (doppler, elevation, azimuth, range).
|
| 99 |
+
mimo_data = mimo(iq_data)
|
| 100 |
+
if no_doppler:
|
| 101 |
+
# Preserve only the first slow-time sample and perform the range FFT.
|
| 102 |
+
# Keeping the leading dimension makes the output layout consistent
|
| 103 |
+
# with the full range-Doppler processing path.
|
| 104 |
+
range_doppler_fft_data = fft_w_shift(mimo_data[0:1], dim=-1, shift=False)
|
| 105 |
+
else:
|
| 106 |
+
# Apply range-doppler FFT
|
| 107 |
+
range_doppler_fft_data = range_doppler_fft(mimo_data)
|
| 108 |
+
# Apply azimuth-elevation FFT
|
| 109 |
+
azimuth_elevation_fft_data = azimuth_elevation_fft(range_doppler_fft_data)
|
| 110 |
+
return azimuth_elevation_fft_data
|
processing_code/utils/sync_timestamps.py
ADDED
|
@@ -0,0 +1,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 |
+
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 |
+
)
|