from __future__ import annotations import json from pathlib import Path import numpy as np def write_handoff(path, rgb, mask, positions, meta): rgb, mask = np.asarray(rgb, np.float32), np.asarray(mask, bool) positions = [int(p) for p in positions] if rgb.ndim != 4 or rgb.shape[0] != len(positions) or rgb.shape[-1] != 3 or mask.shape != rgb.shape[:3]: raise ValueError(f'hand-off shapes rgb {rgb.shape} mask {mask.shape} positions {positions}') path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name('.' + path.name) with open(tmp, 'wb') as fh: np.savez_compressed(fh, rgb=rgb, mask=mask, positions=np.asarray(positions, np.int64), meta=np.asarray(json.dumps(meta))) tmp.replace(path) def load_handoff(path, positions): with np.load(path, allow_pickle=False) as h: rgb, mask, pos = h['rgb'].astype(np.float32), h['mask'].astype(bool), h['positions'].tolist() meta = json.loads(str(h['meta'])) if pos != list(positions) or rgb.shape[0] != len(pos) or mask.shape != rgb.shape[:3]: raise ValueError(f'{path}: positions {pos} (expected {list(positions)}), rgb {rgb.shape}, mask {mask.shape}') return rgb, mask, meta