File size: 7,759 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 |
import argparse
import os
import sys
import numpy as np
import SimpleITK as sitk
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
MODALITY_MAP = {
"t2w": 0,
"t2f": 1,
"t1n": 2,
"t1c": 3,
}
def _parse_cases(s: str):
if not s:
return []
return [p.strip() for p in s.split(",") if p.strip()]
def _normalize_slice(img2d: np.ndarray) -> np.ndarray:
p1, p99 = np.percentile(img2d, (1, 99))
if p99 <= p1:
return np.zeros_like(img2d, dtype=np.float32)
img = (img2d - p1) / (p99 - p1)
return np.clip(img, 0.0, 1.0).astype(np.float32)
def _pred_to_three_channels(pred: np.ndarray) -> np.ndarray:
# Accept either 4D (3, D, H, W) or 3D label map (D, H, W) with labels 0-3.
if pred.ndim == 4:
return pred
if pred.ndim != 3:
raise ValueError(f"unexpected pred shape: {pred.shape}")
# label -> TC/WT/ET
labels = pred
tc = (labels == 1) | (labels == 3)
wt = (labels == 1) | (labels == 2) | (labels == 3)
et = labels == 3
return np.stack([tc, wt, et], axis=0).astype(np.uint8)
def _pick_slices(mask_3c: np.ndarray, num_slices: int) -> list[int]:
# mask_3c: (3, D, H, W)
mask_sum = mask_3c.sum(axis=0) # (D, H, W)
per_slice = mask_sum.reshape(mask_sum.shape[0], -1).sum(axis=1)
if per_slice.max() == 0:
# fallback: evenly spaced slices
return sorted(set(np.linspace(0, mask_sum.shape[0] - 1, num_slices, dtype=int).tolist()))
idx = np.argsort(per_slice)[::-1]
chosen = []
for i in idx:
if len(chosen) >= num_slices:
break
chosen.append(int(i))
return sorted(chosen)
def _overlay_mask(gray: np.ndarray, masks: list[np.ndarray]) -> np.ndarray:
# gray: (H, W), masks: [tc, wt, et]
rgb = np.stack([gray, gray, gray], axis=-1)
colors = [
(1.0, 0.0, 0.0), # TC - red
(0.0, 1.0, 0.0), # WT - green
(1.0, 1.0, 0.0), # ET - yellow
]
alphas = [0.5, 0.25, 0.5]
for mask, color, alpha in zip(masks, colors, alphas):
m = mask.astype(bool)
if m.any():
rgb[m] = rgb[m] * (1.0 - alpha) + np.array(color) * alpha
return rgb
def _load_processed_image(processed_dir: str, case_name: str, modality: int) -> np.ndarray:
img_path = os.path.join(processed_dir, f"{case_name}.npy")
if not os.path.isfile(img_path):
raise FileNotFoundError(f"processed image not found: {img_path}")
arr = np.load(img_path, mmap_mode="r")
if arr.ndim != 4:
raise ValueError(f"unexpected image shape: {arr.shape}")
return np.asarray(arr[modality], dtype=np.float32) # (D, H, W)
def _load_prediction(pred_dir: str, case_name: str) -> np.ndarray:
pred_path = os.path.join(pred_dir, f"{case_name}.nii.gz")
if not os.path.isfile(pred_path):
raise FileNotFoundError(f"prediction not found: {pred_path}")
pred_itk = sitk.ReadImage(pred_path)
pred_arr = sitk.GetArrayFromImage(pred_itk)
return _pred_to_three_channels(np.asarray(pred_arr))
def _load_gt(processed_dir: str, case_name: str) -> np.ndarray:
seg_path = os.path.join(processed_dir, f"{case_name}_seg.npy")
if not os.path.isfile(seg_path):
raise FileNotFoundError(f"gt seg not found: {seg_path}")
seg = np.load(seg_path, mmap_mode="r")
seg = np.asarray(seg)
if seg.ndim == 4 and seg.shape[0] == 1:
seg = seg[0]
return _pred_to_three_channels(seg)
def visualize_case(case_name: str, pred_dir: str, processed_dir: str, modality: int, num_slices: int, out_dir: str, show_gt: bool = True):
img = _load_processed_image(processed_dir, case_name, modality) # (D, H, W)
pred = _load_prediction(pred_dir, case_name) # (3, D, H, W)
gt = None
if show_gt:
try:
gt = _load_gt(processed_dir, case_name)
except FileNotFoundError:
gt = None
if pred.shape[1:] != img.shape:
raise ValueError(f"shape mismatch for {case_name}: img={img.shape}, pred={pred.shape}")
if gt is not None and gt.shape[1:] != img.shape:
raise ValueError(f"shape mismatch for {case_name}: img={img.shape}, gt={gt.shape}")
slice_ids = _pick_slices(pred, num_slices)
ncols = 3 if gt is not None else 2
fig, axes = plt.subplots(nrows=len(slice_ids), ncols=ncols, figsize=(4 * ncols, 3 * len(slice_ids)))
if len(slice_ids) == 1:
axes = np.array([axes])
if ncols == 2 and axes.ndim == 1:
axes = axes[None, :]
for row, z in enumerate(slice_ids):
img2d = img[z]
gray = _normalize_slice(img2d)
tc = pred[0, z]
wt = pred[1, z]
et = pred[2, z]
axes[row, 0].imshow(gray, cmap="gray")
axes[row, 0].set_title(f"{case_name} z={z} (raw)")
axes[row, 0].axis("off")
overlay = _overlay_mask(gray, [tc, wt, et])
axes[row, 1].imshow(overlay)
axes[row, 1].set_title(f"{case_name} z={z} (pred)")
axes[row, 1].axis("off")
if gt is not None:
gt_tc = gt[0, z]
gt_wt = gt[1, z]
gt_et = gt[2, z]
gt_overlay = _overlay_mask(gray, [gt_tc, gt_wt, gt_et])
axes[row, 2].imshow(gt_overlay)
axes[row, 2].set_title(f"{case_name} z={z} (gt)")
axes[row, 2].axis("off")
legend = [
Patch(color=(1.0, 0.0, 0.0), label="TC"),
Patch(color=(0.0, 1.0, 0.0), label="WT"),
Patch(color=(1.0, 1.0, 0.0), label="ET"),
]
fig.legend(handles=legend, loc="lower center", ncol=3)
fig.tight_layout(rect=[0, 0.05, 1, 1])
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, f"{case_name}_overlay.png")
fig.savefig(out_path, dpi=150)
plt.close(fig)
return out_path
def main():
parser = argparse.ArgumentParser(description="Visualize SegMamba predictions (overlay on processed images).")
parser.add_argument("--pred_dir", type=str, required=True, help="Prediction folder containing case_name.nii.gz.")
parser.add_argument("--processed_dir", type=str, required=True, help="Processed data dir containing case_name.npy.")
parser.add_argument("--out_dir", type=str, default="./prediction_results/visualizations")
parser.add_argument("--modality", type=str, default="t2f", help="t2w|t2f|t1n|t1c or an int index.")
parser.add_argument("--num_cases", type=int, default=5)
parser.add_argument("--num_slices", type=int, default=3)
parser.add_argument("--cases", type=str, default="", help="Comma-separated case names to visualize.")
parser.add_argument("--no_gt", action="store_true", help="Disable GT overlay (prediction only).")
args = parser.parse_args()
if args.modality.isdigit():
modality = int(args.modality)
else:
modality = MODALITY_MAP.get(args.modality.lower(), 1)
if modality < 0 or modality > 3:
raise ValueError("modality index must be 0..3")
cases = _parse_cases(args.cases)
if not cases:
pred_files = sorted([f for f in os.listdir(args.pred_dir) if f.endswith(".nii.gz")])
cases = [os.path.splitext(os.path.splitext(f)[0])[0] for f in pred_files][: args.num_cases]
if not cases:
print("No cases found.")
sys.exit(0)
print(f"Visualizing {len(cases)} cases, modality={modality}")
for case_name in cases:
out_path = visualize_case(
case_name=case_name,
pred_dir=args.pred_dir,
processed_dir=args.processed_dir,
modality=modality,
num_slices=args.num_slices,
out_dir=args.out_dir,
show_gt=not args.no_gt,
)
print(f"saved: {out_path}")
if __name__ == "__main__":
main()
|