|
|
import os |
|
|
from typing import Dict, Iterable, List, Optional, Tuple |
|
|
|
|
|
import numpy as np |
|
|
import nibabel as nib |
|
|
from scipy import ndimage as ndi |
|
|
|
|
|
|
|
|
def ensure_dir(path: str) -> None: |
|
|
os.makedirs(path, exist_ok=True) |
|
|
|
|
|
|
|
|
def _resolve_nii(case_dir: str, name: str) -> str: |
|
|
for ext in [".nii.gz", ".nii"]: |
|
|
path = os.path.join(case_dir, name + ext) |
|
|
if os.path.isfile(path): |
|
|
return path |
|
|
raise FileNotFoundError(f"Missing NIfTI: {case_dir}/{name}.nii(.gz)") |
|
|
|
|
|
|
|
|
def load_nifti(path: str) -> Tuple[np.ndarray, np.ndarray]: |
|
|
img = nib.load(path) |
|
|
data = img.get_fdata() |
|
|
return np.asarray(data), img.affine |
|
|
|
|
|
|
|
|
def normalize_volume(vol: np.ndarray, eps: float = 1e-6) -> np.ndarray: |
|
|
x = np.asarray(vol, dtype=np.float32) |
|
|
x = np.nan_to_num(x, nan=0.0, posinf=0.0, neginf=0.0) |
|
|
flat = x.reshape(-1) |
|
|
if flat.size == 0: |
|
|
return np.zeros_like(x, dtype=np.float32) |
|
|
lo, hi = np.percentile(flat, [1, 99]) |
|
|
if hi - lo < eps: |
|
|
return np.zeros_like(x, dtype=np.float32) |
|
|
x = np.clip(x, lo, hi) |
|
|
x = (x - lo) / (hi - lo + eps) |
|
|
return x |
|
|
|
|
|
|
|
|
def label_to_regions(label: np.ndarray) -> np.ndarray: |
|
|
label = np.asarray(label) |
|
|
wt = label > 0 |
|
|
tc = (label == 1) | (label == 4) |
|
|
et = label == 4 |
|
|
return np.stack([wt, tc, et], axis=0).astype(np.uint8) |
|
|
|
|
|
|
|
|
def regions_to_label(regions: np.ndarray) -> np.ndarray: |
|
|
if regions.ndim != 4 or regions.shape[0] != 3: |
|
|
raise ValueError("regions must be [3, D, H, W]") |
|
|
wt = regions[0] > 0.5 |
|
|
tc = regions[1] > 0.5 |
|
|
et = regions[2] > 0.5 |
|
|
label = np.zeros_like(wt, dtype=np.int16) |
|
|
label[wt] = 2 |
|
|
label[tc] = 1 |
|
|
label[et] = 4 |
|
|
return label |
|
|
|
|
|
|
|
|
def load_case_nifti( |
|
|
root_dir: str, |
|
|
case_id: str, |
|
|
modalities: List[str], |
|
|
seg_name: str = "seg", |
|
|
include_label: bool = True, |
|
|
) -> Tuple[Dict[str, np.ndarray], Optional[np.ndarray], np.ndarray]: |
|
|
case_dir = os.path.join(root_dir, case_id) |
|
|
images: Dict[str, np.ndarray] = {} |
|
|
affine = None |
|
|
for mod in modalities: |
|
|
path = _resolve_nii(case_dir, mod) |
|
|
arr, affine = load_nifti(path) |
|
|
images[mod] = np.asarray(arr, dtype=np.float32) |
|
|
label = None |
|
|
if include_label: |
|
|
seg_path = _resolve_nii(case_dir, seg_name) |
|
|
label, _ = load_nifti(seg_path) |
|
|
label = np.asarray(label, dtype=np.int16) |
|
|
if affine is None: |
|
|
affine = np.eye(4) |
|
|
return images, label, affine |
|
|
|
|
|
|
|
|
def _load_npz_arrays(npz_path: str, include_label: bool) -> Tuple[np.ndarray, Optional[np.ndarray]]: |
|
|
data = np.load(npz_path) |
|
|
image = data["data"] |
|
|
label = data["seg"] if include_label and "seg" in data else None |
|
|
return image, label |
|
|
|
|
|
|
|
|
def load_case_npz( |
|
|
npz_dir: str, |
|
|
case_id: str, |
|
|
include_label: bool = True, |
|
|
) -> Tuple[np.ndarray, Optional[np.ndarray]]: |
|
|
if case_id.endswith(".npz"): |
|
|
npz_path = case_id |
|
|
else: |
|
|
npz_path = os.path.join(npz_dir, case_id + ".npz") |
|
|
if not os.path.isfile(npz_path): |
|
|
raise FileNotFoundError(f"Missing npz: {npz_path}") |
|
|
|
|
|
npy_path = npz_path[:-3] + "npy" |
|
|
seg_path = npz_path[:-4] + "_seg.npy" |
|
|
if os.path.isfile(npy_path): |
|
|
image = np.load(npy_path, mmap_mode="r") |
|
|
else: |
|
|
image, _ = _load_npz_arrays(npz_path, include_label=False) |
|
|
|
|
|
label = None |
|
|
if include_label: |
|
|
if os.path.isfile(seg_path): |
|
|
label = np.load(seg_path, mmap_mode="r") |
|
|
else: |
|
|
_, label = _load_npz_arrays(npz_path, include_label=True) |
|
|
|
|
|
image = np.asarray(image, dtype=np.float32) |
|
|
if image.ndim == 5 and image.shape[0] == 1: |
|
|
image = image[0] |
|
|
if image.ndim == 4 and image.shape[0] != 4 and image.shape[-1] == 4: |
|
|
image = image.transpose(3, 0, 1, 2) |
|
|
|
|
|
if label is not None: |
|
|
label = np.asarray(label, dtype=np.int16) |
|
|
if label.ndim == 4 and label.shape[0] == 1: |
|
|
label = label[0] |
|
|
return image, label |
|
|
|
|
|
|
|
|
def load_case( |
|
|
data_cfg: Dict, |
|
|
case_id: str, |
|
|
include_label: bool = True, |
|
|
) -> Tuple[Dict[str, np.ndarray], Optional[np.ndarray], np.ndarray]: |
|
|
data_format = data_cfg.get("format", "nifti") |
|
|
if data_format == "segmamba_npz": |
|
|
npz_dir = data_cfg.get("npz_dir") or data_cfg.get("root_dir", "") |
|
|
image, label = load_case_npz(npz_dir, case_id, include_label=include_label) |
|
|
images = {f"ch{i}": image[i] for i in range(image.shape[0])} |
|
|
affine = np.eye(4) |
|
|
return images, label, affine |
|
|
root_dir = data_cfg.get("root_dir", "") |
|
|
modalities = data_cfg.get("modalities", ["t1n", "t1c", "t2f", "t2w"]) |
|
|
seg_name = data_cfg.get("seg_name", "seg") |
|
|
return load_case_nifti(root_dir, case_id, modalities, seg_name=seg_name, include_label=include_label) |
|
|
|
|
|
|
|
|
def load_prediction( |
|
|
pred_dir: str, |
|
|
case_id: str, |
|
|
pred_type: str = "auto", |
|
|
) -> Dict[str, Optional[np.ndarray]]: |
|
|
def _find(base: str) -> Optional[str]: |
|
|
for ext in [".nii.gz", ".nii"]: |
|
|
path = os.path.join(pred_dir, base + ext) |
|
|
if os.path.isfile(path): |
|
|
return path |
|
|
return None |
|
|
|
|
|
pred_type = pred_type.lower() |
|
|
paths = { |
|
|
"regions_prob": _find(f"{case_id}_regions_prob"), |
|
|
"regions_bin": _find(f"{case_id}_regions_bin"), |
|
|
"label": _find(f"{case_id}_label"), |
|
|
"segmamba_3c": _find(f"{case_id}"), |
|
|
} |
|
|
if pred_type == "auto": |
|
|
for key in ["regions_prob", "regions_bin", "label", "segmamba_3c"]: |
|
|
if paths[key] is not None: |
|
|
pred_type = key |
|
|
break |
|
|
path = paths.get(pred_type) |
|
|
if path is None: |
|
|
raise FileNotFoundError(f"No prediction found for {case_id} in {pred_dir}") |
|
|
|
|
|
arr, _ = load_nifti(path) |
|
|
arr = np.asarray(arr) |
|
|
out: Dict[str, Optional[np.ndarray]] = {"label": None, "regions": None, "prob": None} |
|
|
if pred_type in {"regions_prob", "regions_bin"}: |
|
|
if arr.ndim != 4 or arr.shape[-1] != 3: |
|
|
raise ValueError(f"Expected (D,H,W,3) for regions, got {arr.shape}") |
|
|
regions = arr.transpose(3, 0, 1, 2) |
|
|
out["prob"] = regions.astype(np.float32) if pred_type == "regions_prob" else None |
|
|
out["regions"] = (regions > 0.5).astype(np.uint8) if pred_type == "regions_prob" else regions.astype(np.uint8) |
|
|
out["label"] = regions_to_label(out["regions"]) |
|
|
elif pred_type == "segmamba_3c": |
|
|
if arr.ndim != 4 or arr.shape[-1] != 3: |
|
|
raise ValueError(f"Expected (D,H,W,3) for SegMamba 3c, got {arr.shape}") |
|
|
regions = arr.transpose(3, 0, 1, 2).astype(np.uint8) |
|
|
out["regions"] = regions |
|
|
out["label"] = regions_to_label(regions) |
|
|
else: |
|
|
label = arr.astype(np.int16) |
|
|
out["label"] = label |
|
|
out["regions"] = label_to_regions(label) |
|
|
return out |
|
|
|
|
|
|
|
|
def select_slices_from_mask(mask: Optional[np.ndarray]) -> Dict[str, int]: |
|
|
if mask is None or mask.sum() == 0: |
|
|
return {"axial": None, "coronal": None, "sagittal": None} |
|
|
m = mask.astype(np.uint8) |
|
|
axial = int(np.argmax(m.sum(axis=(1, 2)))) |
|
|
coronal = int(np.argmax(m.sum(axis=(0, 2)))) |
|
|
sagittal = int(np.argmax(m.sum(axis=(0, 1)))) |
|
|
return {"axial": axial, "coronal": coronal, "sagittal": sagittal} |
|
|
|
|
|
|
|
|
def fallback_slices(shape: Tuple[int, int, int]) -> Dict[str, int]: |
|
|
d, h, w = shape |
|
|
return {"axial": d // 2, "coronal": h // 2, "sagittal": w // 2} |
|
|
|
|
|
|
|
|
def extract_slice(vol: np.ndarray, plane: str, idx: int) -> np.ndarray: |
|
|
if plane == "axial": |
|
|
img = vol[idx, :, :] |
|
|
elif plane == "coronal": |
|
|
img = vol[:, idx, :] |
|
|
elif plane == "sagittal": |
|
|
img = vol[:, :, idx] |
|
|
else: |
|
|
raise ValueError(f"Unknown plane: {plane}") |
|
|
return np.rot90(img) |
|
|
|
|
|
|
|
|
def mask_boundary(mask2d: np.ndarray, iterations: int = 1) -> np.ndarray: |
|
|
if mask2d.sum() == 0: |
|
|
return mask2d.astype(bool) |
|
|
eroded = ndi.binary_erosion(mask2d.astype(bool), iterations=iterations) |
|
|
return np.logical_xor(mask2d.astype(bool), eroded) |
|
|
|
|
|
|
|
|
def overlay_masks( |
|
|
base2d: np.ndarray, |
|
|
masks: Dict[str, np.ndarray], |
|
|
colors: Dict[str, Tuple[float, float, float]], |
|
|
alpha: float = 0.5, |
|
|
draw_boundary: bool = True, |
|
|
boundary_width: int = 1, |
|
|
) -> np.ndarray: |
|
|
base = np.clip(base2d, 0.0, 1.0) |
|
|
rgb = np.stack([base, base, base], axis=-1) |
|
|
order = ["WT", "TC", "ET"] |
|
|
for key in order: |
|
|
if key not in masks: |
|
|
continue |
|
|
m = masks[key].astype(bool) |
|
|
|
|
|
if m.shape != base.shape: |
|
|
from scipy.ndimage import zoom |
|
|
zoom_factors = (base.shape[0] / m.shape[0], base.shape[1] / m.shape[1]) |
|
|
m = zoom(m.astype(float), zoom_factors, order=0) > 0.5 |
|
|
if m.sum() == 0: |
|
|
continue |
|
|
color = np.array(colors.get(key, (1.0, 0.0, 0.0)), dtype=np.float32) |
|
|
rgb[m] = (1.0 - alpha) * rgb[m] + alpha * color |
|
|
if draw_boundary: |
|
|
b = mask_boundary(m, iterations=boundary_width) |
|
|
rgb[b] = color |
|
|
return rgb |
|
|
|
|
|
|
|
|
def signed_distance(mask: np.ndarray) -> np.ndarray: |
|
|
mask = mask.astype(bool) |
|
|
if mask.sum() == 0: |
|
|
return np.zeros_like(mask, dtype=np.float32) |
|
|
outside = ndi.distance_transform_edt(~mask) |
|
|
inside = ndi.distance_transform_edt(mask) |
|
|
return (inside - outside).astype(np.float32) |
|
|
|
|
|
|
|
|
def boundary_error_map(pred: np.ndarray, gt: np.ndarray) -> np.ndarray: |
|
|
pred = pred.astype(bool) |
|
|
gt = gt.astype(bool) |
|
|
dist = np.abs(signed_distance(gt)) |
|
|
err = np.zeros_like(dist, dtype=np.float32) |
|
|
err[pred & ~gt] = dist[pred & ~gt] |
|
|
err[~pred & gt] = -dist[~pred & gt] |
|
|
return err |
|
|
|
|
|
|
|
|
def connected_components(mask: np.ndarray) -> Tuple[np.ndarray, int]: |
|
|
labeled, num = ndi.label(mask.astype(np.uint8)) |
|
|
return labeled, int(num) |
|
|
|
|
|
|
|
|
def bin_by_threshold(value: float, thresholds: Iterable[float]) -> int: |
|
|
for i, t in enumerate(thresholds): |
|
|
if value <= t: |
|
|
return i |
|
|
return len(list(thresholds)) |
|
|
|
|
|
|
|
|
def fft_amplitude_slice(vol: np.ndarray, plane: str = "axial") -> np.ndarray: |
|
|
fft = np.fft.fftn(vol) |
|
|
amp = np.abs(fft) |
|
|
amp = np.fft.fftshift(amp) |
|
|
d, h, w = amp.shape |
|
|
if plane == "axial": |
|
|
sl = amp[d // 2, :, :] |
|
|
elif plane == "coronal": |
|
|
sl = amp[:, h // 2, :] |
|
|
else: |
|
|
sl = amp[:, :, w // 2] |
|
|
sl = np.log1p(sl) |
|
|
return normalize_volume(sl) |
|
|
|
|
|
|
|
|
def fourier_amplitude_mix(a: np.ndarray, b: np.ndarray, lam: float) -> np.ndarray: |
|
|
|
|
|
if a.shape != b.shape: |
|
|
from scipy.ndimage import zoom |
|
|
|
|
|
b_resized = np.zeros_like(a) |
|
|
for c in range(min(a.shape[0], b.shape[0])): |
|
|
zoom_factors = tuple(a.shape[i+1] / b.shape[i+1] for i in range(3)) |
|
|
b_resized[c] = zoom(b[c], zoom_factors, order=1) |
|
|
b = b_resized |
|
|
fft_a = np.fft.fftn(a, axes=(1, 2, 3)) |
|
|
fft_b = np.fft.fftn(b, axes=(1, 2, 3)) |
|
|
amp_a = np.abs(fft_a) |
|
|
amp_b = np.abs(fft_b) |
|
|
phase = np.exp(1j * np.angle(fft_a)) |
|
|
amp_mix = (1.0 - lam) * amp_a + lam * amp_b |
|
|
mixed = np.fft.ifftn(amp_mix * phase, axes=(1, 2, 3)).real |
|
|
return mixed.astype(np.float32) |
|
|
|