The Brazilian High-Risk Cohort (BHRC) is a longitudinal study tracking youth at high risk for mental disorders (e.g., ADHD, anxiety) in Brazil, integrating neuroimaging (MRI), cognitive assessments, and mental health phenotyping.
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.
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.
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.mat, other/*_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.
The fMRI Pre-Processing Pipeline is a lightweight, end-to-end workflow built around fMRIPrep. FMRIPrep handles motion/distortion correction, anatomical/functional alignment to standard spaces, surface mapping, confound modeling, and we added connectivity analysis, with clear QC visualizations considering QC on the number of volumes (Adjustable), FD, high-motion ratio; QC with visual connectivity matrices; and tabular outputs for downstream ML/AI.
Generate automatic visualizations (connectivity heatmaps + distribution plots + statistics)
Save matrices, timeseries, and visualizations
Outputs (per subject in CONNECTIVITY_OUTPUT_DIR):
sub-*_*_timeseries.csv: Regional timeseries
sub-*_*_*_connectivity.csv: Connectivity matrices
sub-*_*_*_visualization.png: Connectivity heatmaps with statistics
Available Atlases:aal, harvard_oxford, schaefer-100, schaefer-400, difumo-256, difumo-1024
python connectivity_matrix.py --subjects sub-01 sub-02 --atlases aal schaefer-100
# OR use standalone runner:
python run_connectivity.py --all-completed --atlases aal harvard_oxford
Note: When using pipeline_runner.py, connectivity generation (including visualization) happens automatically after each subject completes fMRIPrep successfully.
5) Quality Control, fmri_qc.py
Processing Steps:
Find all subjects with fMRIPrep outputs
Locate best confounds file per subject/session (≥50 volumes)
fmri_qc_data.csv: Tabular QC data (metrics + status)
QC Thresholds:
PASS: Mean FD ≤ 0.3 mm, High-Motion Ratio ≤ 20%, Volumes ≥ 180
REVIEW: Mean FD 0.3–0.5 mm OR High-Motion Ratio ≤ 30% OR Volumes 120–179
FAIL: Mean FD ≥ 0.5 mm OR High-Motion Ratio > 30% OR Volumes < 120
# Run QC for all subjects
python fmri_qc.py --all
# Run QC for specific subjects
python fmri_qc.py --subjects 001 002
# Export group-level QC summary
python fmri_qc.py --all --export-summary
python pipeline_runner.py --mode single --subject SUB_ID --cpu-only
Log Analysis
# Check pipeline status
python pipeline_runner.py --mode status
# View subject logs
tail -f /path/to/logs/sub-SUB_ID.log
cat /path/to/logs/sub-SUB_ID.error
# Monitor system resources
top -u $USER
nvidia-smi # For GPU usage
fMRI QC Manual Review Summary
Overall QC Review
All subjects and sessions are reviewed and classified as PASS, REVIEW, or FAIL based on motion (framewise displacement, FD) and scan length. PASS indicates high-quality data, REVIEW marks usable but moderate-quality data, and FAIL means the data are not usable. The thresholds for these categories (volumes, FD cutoffs, motion ratio) are fully configurable in the QC settings.
Per-Subject QC Reports
Each subject has its own HTML report showing QC status, task and scan details, number of volumes, and motion metrics such as mean and maximum FD. The report also links to the subject’s fMRIPrep output for visual inspection. If connectivity analysis is included, the report provides the connectivity matrix, visualizations, and ROI time series.
fMRIPrep HTML Report Manual Review Guidelines
For detailed quality assessment, review the fMRIPrep HTML reports. Key areas to check:
1. Brain Mask & Segmentation
Red line: Should outline the brain (not skull/dura)
fMRIPrep: Esteban, O., Markiewicz, C. J., Blair, R. W., et al. (2019). fMRIPrep: a robust preprocessing pipeline for functional MRI. Nature Methods, 16(1), 111-116.
Nilearn: Abraham, A., Pedregosa, F., Eickenberg, M., et al. (2014). Machine learning for neuroimaging with scikit-learn. Frontiers in Neuroinformatics, 8, 14.
BIDS: Gorgolewski, K. J., Auer, T., Calhoun, V. D., et al. (2016). The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments. Scientific Data, 3, 160044.
QC / Motion Quality Metrics: Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Spurious but systematic correlations in functional connectivity MRI networks arise from subject motion. NeuroImage, 59(3), 2142–2154.
Quality Control and Exclusion Criteria
We have checked all the items in the code above and reported them in the QC results. However, after preprocessing with fMRIPrep, all outputs must still be carefully reviewed. Always check the fMRIPrep log for the message “fMRIPrep finished successfully!”. Confirm that each scan has an acceptable number of volumes, review the generated QC reports and images, and visually inspect the final outputs for additional verification.
Data with excessive motion or insufficient volumes should be excluded. Typical thresholds include minimum volume counts, mean FD limits, and motion ratios. These thresholds are defined in the QC configuration and can be adjusted depending on dataset requirements. All steps have been carefully performed, and the codes have been made publicly available for transparency and reproducibility.
Authors / Version
Author: Mohammad H. Abbasi (This email address is being protected from spambots. You need JavaScript enabled to view it.)
Created: 2025 | Version: 1.0.0 | Last update: September 16, 2025
Acknowledgements
Thanks to the fMRIPrep team, Nilearn contributors, and the broader neuroimaging community for developing the foundational tools that made this pipeline possible.
Special appreciation to the Stanford Translational AI Lab (STAI Lab) for extending the QC, connectivity, and pipeline management components.
Sincere thanks to Favour Nerrise and Karan Singh for their valuable feedback, collaboration, and continuous contributions to improving the pipeline.
How to Cite This Work
If you use this pipeline in your research, please cite it as follows:
Abbasi, M.H., & Adeli, E. (2025). fMRI Processing Pipeline: A lightweight, end-to-end framework for BIDS-compatible fMRI preprocessing and quality control. Stanford Translational AI Lab, Stanford University. Zenodo. https://doi.org/10.5281/zenodo.17516604
@software{abbasi2025fmri,
author = {Mohammad Hassan Abbasi and Ehsan Adeli},
title = {f{MRI} {P}rocessing {P}ipeline: A lightweight, end-to-end framework for {BIDS}-compatible f{MRI} preprocessing and quality control},
year = {2025},
institution = {Stanford Translational AI Lab, Stanford University},
publisher = {Zenodo},
doi = {10.5281/zenodo.17516368},
url = {https://doi.org/10.5281/zenodo.17516604}, note = {Zenodo, doi: 10.5281/zenodo.17516604},
}
The Structural MRI (sMRI) Processing Pipeline is a lightweight, end-to-end workflow for structural brain MRI. It performs brain extraction, registration to MNI, and post-processing (N4 bias correction, masked Z-score normalization, cropping), and produces clear QC visualizations plus CSV metadata for downstream analysis. The design is config-driven, scalable across cohorts, and interoperable with common neuroimaging tools and AI pipelines.
Brain Extraction, SynthStrip (Singularity/Docker/FreeSurfer) with montage QC & volume summary.
Registration, Rigid → Affine alignment to MNI152NLin2009cAsym (1mm) using SimpleITK.
Post-processing, Optional N4, masked Z-score, tight cropping with affine update.
QC & Reports, Per-subject overlays and global QC CSV (PASS/FAIL, volumes, messages).
Metadata, CSV indices for warped/normalized/cropped outputs (+ optional demographics encodings).
The pipeline is config-driven. Edit config.py once and drive all scripts consistently. Below is a concise map of the most important keys, with usage tips and sensible defaults.
Paths
INPUT_DIR: Root directory for input NIfTI files.
OUTPUT_DIR: Root for all outputs (skullstrip / registration / postprocess / metadata).
If your dataset is already in NIfTI, skip this step. Otherwise, this script converts DICOM folders into gzip-compressed NIfTI (BIDS-style layout) using dcm2niix.
Inputs
DICOM series or a root directory containing series
Removes non-brain tissue using SynthStrip. The script attempts Singularity → Docker → FreeSurfer binary (in that 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 montage overlay
Global CSV: QC/qc_summary.csv (brain volume, PASS/FAIL, paths, message)
CLI
python skullstrip.py # process all
python skullstrip.py --subject sub-ON12345
2) Registration to MNI (Rigid → Affine), reg.py
Registers T1w to MNI152NLin2009cAsym (1mm) with SimpleITK (Mattes MI, multi-resolution), then applies the same transforms to T2w in 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"])
The Diffusion MRI (DTI) Pre-Processing Pipeline is a lightweight, end-to-end workflow for diffusion brain MRI. It performs susceptibility correction (TOPUP), eddy current & motion correction (EDDY), within-session alignment/merge, registration to MNI, and diffusion tensor fitting (DIPY). The pipeline generates clear QC visualizations and summary tables (CSV/JSON/HTML) for downstream analysis. The design is config-driven, scalable across cohorts, and interoperable with common neuroimaging tools and AI pipelines.
Distortion & Motion, FSL TOPUP (AP/PA) + EDDY with slice-to-volume (S2V) and outlier replacement (REPOL).
Brain Extraction, FSL BET with montage QC and brain-volume range checks.
Registration, FLIRT rigid (6 DOF) → affine (12 DOF) to MNI (trilinear for images, nearest-neighbour for masks).
Gradient Handling, b-vector rotation synchronized with all applied transforms.
This pipeline is config-driven. Edit config.py once and reuse across all scripts (b0_correction.py, process_eddy.py, brain_extraction.py, run_reg_mni.py, run_dtifit_dipy.py, run_final_qc.py, dti_qc.py).
FSL environment
FSL_HOME, FSL_BIN, FSL_ENV, core FSL paths and env vars.
setup_fsl_env(), helper to source FSL config into the current process.
Correct susceptibility-induced distortions using FSL TOPUP (Andersson et al., 2003). This step estimates a field map from images with opposite phase-encoding directions and applies it to unwarp distorted diffusion volumes.
2) Eddy Current and Motion Correction, process_eddy.py
Correct distortions caused by eddy currents and subject motion using FSL EDDY (Andersson & Sotiropoulos, 2016). Includes slice-to-volume (S2V) correction and outlier replacement (REPOL).
Steps performed:
Load and merge diffusion-weighted images (AP/PA or reversed polarity)
Prepare acquisition parameters and B0 indices
Run FSL EDDY with slice-to-volume correction (optional)
Generate QC images comparing original vs corrected volumes
Removes non-brain tissue from diffusion MRI data using FSL BET (Smith, 2002). This step performs skull stripping and generates quality control (QC) images and summary files to validate the extracted brain.
Steps performed:
Apply FSL BET to remove non-brain tissue
Generate brain mask and masked output
Compute brain volume (ml) and validate against the expected range
Aligns and merges multiple diffusion MRI runs using FSL FLIRT in case a session is broken down into multiple acquisitions. Rigid transformations are estimated between B0 reference images, applied to corresponding diffusion volumes, and propagated to b-vectors to ensure orientation consistency across runs.
Steps performed:
Register B0 images between runs using FLIRT rigid-body transform
Apply transforms to diffusion volumes (DWI)
Rotate b-vectors using the computed transformation matrix
Merge registered DWI volumes, b-vectors, and b-values
Save combined outputs for downstream processing
5) Registration to MNI Space, run_reg_mni.py
Registers diffusion images to the MNI152 template using a two-step approach with FSL FLIRT (rigid + affine). Corresponding b-vectors are rotated to preserve orientation consistency. The pipeline also applies the transforms to the diffusion volumes and masks, and prepares final outputs for downstream analysis.
Steps performed:
Register B0 to MNI (rigid, 6 DOF), save the matrix and registered B0
Refine B0→MNI with affine (12 DOF), save matrix, and registered B0
Apply rigid and then affine transforms to DWI
Rotate b-vectors using the previously computed transformations
Copy b-values (bval_final.bval) for consistency
Register mask with nearest-neighbour interpolation using the previously computed transformations
6) Diffusion Tensor Model Fitting, run_dtifit_dipy.py
Fits a diffusion tensor model using DIPY (Garyfallidis et al., 2014). This script takes preprocessed diffusion MRI data (DWI, bvec, bval, mask) and outputs standard DTI-derived measures including fractional anisotropy (FA), mean diffusivity (MD), radial diffusivity (RD), and axial diffusivity (AD). Eigenvectors of the tensor are also saved for visualization.
Steps performed:
Load diffusion MRI data, b-values, b-vectors, and brain mask
Save DTI-derived tensor components and maps: FA, MD, RD, AD, and eigenvectors (V1, V2, V3)
Generate QC images showing a color FA map
References:
Basser, P.J., Mattiello, J., & LeBihan, D. (1994). MR diffusion tensor spectroscopy and imaging. Biophysical Journal, 66(1), 259–267. https://pubmed.ncbi.nlm.nih.gov/8130344/
Garyfallidis, E., Brett, M., Correia, M.M., Williams, G.B., & Nimmo-Smith, I. (2014). DIPY, a library for the analysis of diffusion MRI data. Frontiers in Neuroinformatics, 8, 8. https://pmc.ncbi.nlm.nih.gov/articles/PMC3931231/
7) Quality Control of Final Outputs, run_final_qc.py
Performs automated, session-aware QC checks on diffusion pipeline outputs. This script validates file existence and assesses registration quality using overlap metrics (Dice) between warped images and the MNI template. Results are written to per-session CSV reports for downstream review.
What it checks:
File existence validation (key outputs, matrices, QC images)
Registration to MNI (rigid + affine), Dice coefficient vs. MNI template
Within-session registration (if NUM_SCANS_PER_SESSION > 1) Dice on b0-to-b0
Session discovery and per-session reporting
Structured logging to file + console
Outputs (CSV per subject/session)(filenames as written by the current code):
QC/file_existance.csv
QC/within_subject_registraction_qc.csv (only if NUM_SCANS_PER_SESSION > 1)
QC/mni_registraction_qc.csv
Notes: Uses thresholds for PASS/WARNING based on Dice (configurable in code). Relies on TEMPLATE_PATH and derivative folders from config.py. Designed to run after registration steps have completed.
Generates automated, subject-level QC reports that summarize and visualize the outputs of the DTI preprocessing pipeline. This script reads existing QC CSVs and QC images from each step and compiles them into a clickable HTML report along with CSV/JSON summaries. If FA/MD maps are available, it also computes basic statistics.
Summarized in the report:
Raw vs. corrected B0 (Topup), QC images (before/after)
We apply a rigorous Quality Control (QC) process across all modalities to ensure that the imaging data is accurate, consistent, and ready for downstream analysis. QC is performed at multiple stages of preprocessing, and results are documented in both numerical metrics and visual reports.
An automated HTML QC report is generated for all modalities, structural MRI (sMRI), functional MRI (fMRI), and diffusion MRI (DTI), providing a standardized and accessible summary of quality metrics and visual inspections for each subject.
We provide open-source preprocessing and quality control scripts for three major neuroimaging modalities. These tools are designed to standardize workflows, ensure reproducibility, and support downstream analysis.
We aim to establish comprehensive harmonization procedures. This process involves multiple steps. The first step ensures that all outputs follow a consistent format and are integrated into a unified structure, currently completed for the T1 and T2 modalities across the available datasets. In the next steps, our goal is to harmonize data across different scan types and other relevant factors. Additional details will be provided soon.