Mind Data Hub

Stanford Translational AI Lab (STAI)

Structural MRI Processing Pipeline (2)

GitHub GitHub YouTube YouTube QCQC Sample 

A lightweight, end‑to‑end pipeline for brain extraction, registration to MNI, post‑processing (N4 + masked Z‑score + cropping), QC visualization, and CSV metadata generation.

Prerequisites → Configuration → Processing Steps (numbered) → Quick Start → Outputs/QC → Authors/Version.


Prerequisites

  • Python ≥ 3.8
  • Python packages: numpynibabelSimpleITKmatplotlibtqdmtemplateflowpandas
  • SynthStrip via one of:
    • Singularity image: freesurfer/synthstrip:latest (recommended)
    • Docker image: freesurfer/synthstrip:latest
    • FreeSurfer installation with mri_synthstrip in $FREESURFER_HOME/bin
  • (Optional) TemplateFlow cache (auto‑downloads MNI152NLin2009cAsym template)
  • (Optional) conda for environment management

Example env setup

conda create -y -n smri python=3.10
conda activate smri
pip install numpy nibabel SimpleITK matplotlib tqdm templateflow pandas
 

Configuration

Paths and behavior are controlled by config.py (shared by all scripts). The scripts are primarily config‑driven; minimal CLI flags are provided for convenience.

Key items in config.py:

  • Paths: INPUT_DIROUTPUT_DIRSTAGE_ROOTS
  • Unified structure pattern: STRUCTURE = "{root}/{subject}/{session}"
  • Patterns: SKULLSTRIP_T1_FILE_PATTERNSKULLSTRIP_T2_FILE_PATTERN
  • Processing: MODALITIESSUBJECTSSESSIONSFORCE_REPROCESSING
  • QC thresholds, logging, CPU threads
  • Registration: MNI_TEMPLATE_VERSIONMNI_TEMPLATE_RESOLUTION
  • Post‑process: POSTPROCESS_APPLY_N4POSTPROCESS_CROP_MARGIN
  • CSV metadata: output dir, columns, demographics encoders

Processing Steps

0) Convert DICOM to Nifti, dicom_to_nifti.py

If your dataset is already in NIfTI, skip this step. Otherwise, this script converts DICOM folders into NIfTI (gzip-compressed, BIDS-style layout) using dcm2niix.

Inputs

  • DICOM series or root directory

Outputs

  • {subject}/{session}/anat/*.nii.gz (+ JSON sidecars)

CLI

python dicom_to_nifti.py --dicom_dir /path/to/DICOM --output_dir /path/to/nifti --subject sub-0001 --session ses-01

Reference: Li, X., Morgan, P.S., Ashburner, J., Smith, J., & Rorden, C. (2016). The first step for neuroimaging data analysis: DICOM to NIfTI conversion. Journal of Neuroscience Methods, 264, 47–56.
https://www.sciencedirect.com/science/article/pii/S0165027016300073


1) Brain Extraction, skullstrip.py

Removes non‑brain tissue using SynthStrip. The script tries Singularity → Docker → FreeSurfer binary (in this order). Generates brain, mask, and QC images.

Inputs

  • NIfTI files discovered via STRUCTURE and patterns:
    • *acq-MPRAGE_T1w.nii.gz
    • *acq-CUBE_T2w.nii.gz

Outputs (per subject/session in STAGE_ROOTS["skullstrip"])

  • *_brain.nii.gz*_brain_mask.nii.gz
  • *_desc-qc.png overlay montage
  • Global CSV: QC/qc_summary.csv with brain volume (ml) and PASS/FAIL

CLI

python skullstrip.py                  # process all
python skullstrip.py --subject sub-ON12345
Reference: Hoopes, A., Mora, J.S., Dalca, A.V., Fischl, B., & Hoffmann, M. (2022). SynthStrip: Skull-Stripping for Any Brain Image. NeuroImage, 260, 119474.
https://doi.org/10.1016/j.neuroimage.2022.119474
 

2) Registration to MNI (Rigid → Affine), reg.py

Registers T1w to MNI152NLin2009cAsym (1mm) using SimpleITK (Mattes MI; multi‑resolution). Applies the same transforms to T2w of the same session.

Method

  • Rigid: Euler3D, shrink [4,2,1], linear
  • Affine: 12‑DOF, shrink [2,1], linear
  • Final resampling: composite transform (rigid+affine) for single interpolation
  • Saves *.mat transforms

Outputs (per subject/session in STAGE_ROOTS["registration"])

  • *_mni_rigid_warped.nii.gz (QC/ref)
  • *_mni_warped.nii.gz (final)
  • other/*_rigid.matother/*_affine.mat

CLI

python reg.py
python reg.py --subject sub-ON12345
Reference: Lowekamp, B.C., Chen, D.T., Ibáñez, L., & Blezek, D. (2013). The Design of SimpleITK. Frontiers in Neuroinformatics, 7, 45.
 

3) Post‑processing, postprocess_mni_mask_zscore_crop.py

Warp masks to MNI, run N4 bias correction (optional), compute masked Z‑scorecrop around the brain, and save a multi‑slice visualization.

Steps

  1. Warp native masks → MNI with nearest‑neighbor using composite transform (rigid+affine)
  2. N4 bias correction (if POSTPROCESS_APPLY_N4 = True)
  3. Masked Z‑score: μ/σ computed within mask; background kept at 0
  4. Crop: tight bounding box (+ POSTPROCESS_CROP_MARGIN), affine updated (qform/sform set)
  5. Save multi‑slice PNG montage

Outputs (per subject/session; under the same registration anat/)

  • T1w_mni_mask.nii.gz
  • T1w_mni_warped_n4.nii.gz (if N4 enabled)
  • T1w_mni_zscore_fixed.nii.gz
  • T1w_mni_zscore_fixed_cropped.nii.gz
  • multislice_visualization_<subj>.png
  • (T2 equivalents when available; falls back to T1 mask if T2 mask missing)

CLI

python postprocess_mni_mask_zscore_crop.py
python postprocess_mni_mask_zscore_crop.py --subject sub-ON12345
Reference: Tustison, N.J., Avants, B.B., Cook, P.A., Zheng, Y., Egan, A., Yushkevich, P.A., & Gee, J.C. (2010). N4ITK: Improved N3 bias correction. IEEE Transactions on Medical Imaging, 29(6), 1310–1320.
https://doi.org/10.1109/TMI.2010.2046908

4) Quality Control & Reports, skullstrip.pystructural_qc.py

  • skullstrip.py writes per‑subject QC montages and a global QC CSV with brain volume.
  • structural_qc.py (optional helpers) can be used for extended validations (e.g., Dice vs reference).

 

Outputs

  • QC/qc_summary.csv (columns: input_file, output_file, modality, qc_status, brain_volume_ml, qc_image_path, error_message)

5) CSV Metadata, generate_csv_metadata.py

Scans registration outputs and builds CSVs listing MNI warpedZ‑score, and cropped paths, with optional demographics (participants.tsv) and encodings (sexhandedness).

Outputs

  • metadata/T1_metadata.csv
  • metadata/T2_metadata.csv

CLI

python generate_csv_metadata.py
 

Quick Start

# 0) (optional) create environment
conda create -y -n smri python=3.10
conda activate smri
pip install numpy nibabel SimpleITK matplotlib tqdm templateflow pandas

# 1) configure
# edit config.py (private paths, thresholds)

# 2) brain extraction
python skullstrip.py

# 3) registration
python reg.py

# 4) post-process
python postprocess_mni_mask_zscore_crop.py

# 5) metadata tables
python generate_csv_metadata.py
 

Outputs (Where to Find Things)

  • Skullstrip → STAGE_ROOTS["skullstrip"]
    *_brain.nii.gz*_brain_mask.nii.gz*_desc-qc.png, global QC/qc_summary.csv

  • Registration → STAGE_ROOTS["registration"]
    *_mni_rigid_warped.nii.gz*_mni_warped.nii.gzother/*_rigid.matother/*_affine.mat

  • Post‑process → same anat/ under registration
    T1w_mni_mask.nii.gzT1w_mni_zscore_fixed.nii.gzT1w_mni_zscore_fixed_cropped.nii.gzmultislice_visualization_<subj>.png (and T2 analogs)

  • CSV metadata → CSV_METADATA_DIR
    T1_metadata.csvT2_metadata.csv


Authors / Version

  • Author: Mohammad H. Abbasi (mabbasi [at] stanford.edu)
  • Lab: Stanford University, STAI Lab (https://stai.stanford.edu)
  • Created: 2025  |  Version: 1.0.0 | Last update: 10 Sep, 2025

Acknowledgements

Thanks to the open‑source neuroimaging community (FreeSurfer, TemplateFlow, SimpleITK, nibabel) and dataset providers.

 

Mind Data Hub Home Page >>