|
|
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: |
|
|
|
|
|
if pred.ndim == 4: |
|
|
return pred |
|
|
if pred.ndim != 3: |
|
|
raise ValueError(f"unexpected pred shape: {pred.shape}") |
|
|
|
|
|
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_sum = mask_3c.sum(axis=0) |
|
|
per_slice = mask_sum.reshape(mask_sum.shape[0], -1).sum(axis=1) |
|
|
if per_slice.max() == 0: |
|
|
|
|
|
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: |
|
|
|
|
|
rgb = np.stack([gray, gray, gray], axis=-1) |
|
|
colors = [ |
|
|
(1.0, 0.0, 0.0), |
|
|
(0.0, 1.0, 0.0), |
|
|
(1.0, 1.0, 0.0), |
|
|
] |
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
pred = _load_prediction(pred_dir, case_name) |
|
|
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() |
|
|
|