File size: 11,159 Bytes
fe8202e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
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)
# Handle shape mismatch by resizing mask to match base
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 shapes differ, crop/pad b to match a
if a.shape != b.shape:
from scipy.ndimage import zoom
# Resize b to match a shape
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)
|