from __future__ import annotations import numpy as np from .scene import LabelSet class FrameLabels: def __init__(self, root, *, name: str, layers, width: int = 518, height: int = 294): self.labels = LabelSet.open(root, name=name) grid = self.labels.grid if (int(grid.get('width', -1)), int(grid.get('height', -1))) != (width, height): raise ValueError(f'{name} labels in {root} are {grid.get("width")}x{grid.get("height")}, expected {width}x{height}') self.layers, self.shape = tuple(layers), (height, width) missing = [layer for layer in self.layers if layer not in self.labels.manifest.get('layers', [])] if missing: raise ValueError(f'{name} label set {root} does not declare layers {missing}') def read(self, scene_id: str, indices, frame_count: int, timestamps_start_us=None) -> dict: import h5py self.labels.require(scene_id) path = self.labels.path(scene_id) if not path.is_file(): raise FileNotFoundError(f'{self.labels.name} labels missing for {scene_id}: {path}') idx = [int(i) for i in indices] order = np.argsort(idx, kind='stable') sorted_idx = [idx[i] for i in order] if len(set(sorted_idx)) != len(sorted_idx): raise ValueError(f'duplicate frames {idx}') out = {} with h5py.File(path, 'r') as handle: for layer in self.layers: data = handle[layer] if data.shape != (frame_count, *self.shape): raise ValueError(f'{scene_id} {layer} {data.shape} != ({frame_count}, {self.shape[0]}, {self.shape[1]})') if sorted_idx[0] < 0 or sorted_idx[-1] >= data.shape[0]: raise IndexError(f'{scene_id} {layer}: frames {sorted_idx} outside 0..{data.shape[0] - 1}') values = data[sorted_idx] unsorted = np.empty_like(values) unsorted[order] = values out[layer] = unsorted stored = handle['frame_indices'][sorted_idx] if not np.array_equal(stored, sorted_idx): raise ValueError(f'{scene_id}: label frame_indices {stored.tolist()} != {sorted_idx}') if timestamps_start_us is not None: ts = np.asarray(timestamps_start_us, np.int64)[order] if not np.array_equal(handle['timestamp_start_us'][sorted_idx], ts): raise ValueError(f'{scene_id}: label timestamps differ from frames.jsonl') return out class MotionStore(FrameLabels): def __init__(self, root): super().__init__(root, name='motion', layers=('motion_mask',)) class CleanSkyStore(FrameLabels): def __init__(self, root): super().__init__(root, name='sky', layers=('sky',)) if self.labels.version != 1: raise ValueError(f'sky labels v{self.labels.version}, expected v1')