"""Bounded native B-scan windows, including adjacent/distant and global views.""" import numpy as np from src.io import iter_volume_frames, normalize_frame, read_frames OFFSETS = {1: [0], 3: [-1, 0, 1], 5: [-8, -1, 0, 1, 8], 6: [-1, 0, 1]} def iter_normalized_contexts(headers, shapes): if any(shape[2] not in OFFSETS for shape in shapes): raise ValueError("Unsupported OCT image context") spatial = sorted({tuple(shape[:2]) for shape in shapes}) total = sum(int(ds.get("NumberOfFrames", 1)) for _, ds in headers) if total < 1: raise ValueError("Empty structural volume") global_views = {} if any(shape[2] == 6 for shape in shapes): selected = [0, total // 2, total - 1] raw = read_frames(headers, sorted(set(selected))) for shape in spatial: global_views[shape] = np.stack( [normalize_frame(raw[index], shape) for index in selected] ) radius = max(abs(offset) for shape in shapes for offset in OFFSETS[shape[2]]) iterator = iter(iter_volume_frames(headers)) cache = {} loaded = -1 for center in range(total): last = min(total - 1, center + radius) while loaded < last: frame = next(iterator, None) if frame is None: raise ValueError("Structural frames ended before declared geometry") loaded += 1 cache[loaded] = {shape: normalize_frame(frame, shape) for shape in spatial} images = [] for shape in shapes: key = tuple(shape[:2]) indices = [ max(0, min(total - 1, center + offset)) for offset in OFFSETS[shape[2]] ] image = np.stack([cache[index][key] for index in indices]) if shape[2] == 6: image = np.concatenate([image, global_views[key]], axis=0) images.append(image) yield images oldest = center + 1 - radius for index in list(cache): if index < oldest: del cache[index] if next(iterator, None) is not None: raise ValueError("Surplus structural frames")