Datasets:
File size: 3,932 Bytes
476f992 | 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 | #!/usr/bin/env python3
"""Generate the deterministic M4Raw Brain homepage montage."""
from __future__ import annotations
import argparse
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from m4raw_io import read_target
DEFAULT_SCAN_ID = "2022061003"
SEQUENCES = (
("T1-weighted", "multicoil_train", "T1", 3),
("T2-weighted", "multicoil_train", "T2", 3),
("FLAIR", "multicoil_train", "FLAIR", 2),
("GRE", "multicoil_gre", "GRE", 2),
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--release-root", type=Path, default=Path("."))
parser.add_argument("--scan-id", default=DEFAULT_SCAN_ID)
parser.add_argument("--slice", type=int, default=9)
parser.add_argument("--output", type=Path)
return parser.parse_args()
def shared_intensity_limits(images: list[np.ndarray]) -> tuple[float, float]:
values = np.concatenate(
[image[np.isfinite(image) & (image > 0)].ravel() for image in images]
)
if values.size == 0:
return 0.0, 1.0
low, high = np.percentile(values, (0.5, 99.5))
return float(low), float(max(high, low + 1e-6))
def load_repetitions(
root: Path, folder: str, scan_id: str, suffix: str, count: int
) -> list[np.ndarray]:
return [
read_target(root / folder / f"{scan_id}_{suffix}{rep:02d}.h5")
for rep in range(1, count + 1)
]
def main() -> None:
args = parse_args()
root = args.release_root.resolve()
output = args.output or root / "assets" / "representative_images.png"
figure, axes = plt.subplots(
2,
4,
figsize=(15.0, 7.4),
facecolor="white",
constrained_layout=True,
)
for column, (title, folder, suffix, repetition_count) in enumerate(SEQUENCES):
repetitions = load_repetitions(
root, folder, args.scan_id, suffix, repetition_count
)
if args.slice < 0 or args.slice >= repetitions[0].shape[0]:
raise IndexError(
f"Slice {args.slice} is outside {suffix} volume with "
f"{repetitions[0].shape[0]} slices"
)
# Match the original tutorial: display stored RSS slices directly.
single = np.asarray(repetitions[0][args.slice])
average = np.mean(
np.stack([volume[args.slice] for volume in repetitions]),
axis=0,
dtype=np.float64,
).astype(np.float32)
limits = shared_intensity_limits([single, average])
axes[0, column].set_title(
title, fontsize=18, fontweight="semibold", pad=10
)
for row, image in enumerate((single, average)):
axes[row, column].imshow(
image,
cmap="gray",
vmin=limits[0],
vmax=limits[1],
interpolation="nearest",
origin="upper",
)
axes[row, column].set_xticks([])
axes[row, column].set_yticks([])
for spine in axes[row, column].spines.values():
spine.set_visible(False)
axes[1, column].text(
0.03,
0.04,
f"{repetition_count} acquisitions",
transform=axes[1, column].transAxes,
color="white",
fontsize=12,
ha="left",
va="bottom",
bbox={"facecolor": "black", "alpha": 0.55, "edgecolor": "none", "pad": 3},
)
axes[0, 0].set_ylabel(
"Single acquisition", fontsize=16, fontweight="semibold", labelpad=14
)
axes[1, 0].set_ylabel(
"Repeat average", fontsize=16, fontweight="semibold", labelpad=14
)
output.parent.mkdir(parents=True, exist_ok=True)
figure.savefig(output, dpi=200, facecolor="white", bbox_inches="tight")
plt.close(figure)
print(output)
if __name__ == "__main__":
main()
|