Datasets:
Download code/make_homepage_preview.py from mylyu/M4Raw_brain: direct link, hf CLI and curl.
- Browser
- Download file 3.93 kB
-
https://huggingface.co/datasets/mylyu/M4Raw_brain/resolve/main/code/make_homepage_preview.py
- Command line
-
hf download hf://datasets/mylyu/M4Raw_brain/code/make_homepage_preview.py
-
curl -L -o make_homepage_preview.py https://huggingface.co/datasets/mylyu/M4Raw_brain/resolve/main/code/make_homepage_preview.py
3.93 kB
| #!/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() | |