Run this notebook
Author: Monika Doerig
Date: 10 June 2025
License:
Note: If this notebook uses neuroimaging tools from Neurocontainers, those tools retain their original licenses. Please see Neurodesk citation guidelines for details.
Citation and Resources:¶
Educational resources¶
Andy’s Brain Book:
This brain extraction example is based on the Advanced Normalization Tools (ANTs) chapter from Andy’s Brain Book (Jahn, 2022. doi:10
.5281 /zenodo .5879293)
Tools included in this workflow¶
ANTs - antsBrainExtraction.sh:
Tustison, N.J., Cook, P.A., Holbrook, A.J. et al. The ANTsX ecosystem for quantitative biological and medical imaging. Sci Rep 11, 9068 (2021). Tustison et al. (2021)
AFNI - 3dSkullStrip:
Cox RW (1996). AFNI: software for analysis and visualization of functional magnetic resonance neuroimages. Comput Biomed Res 29(3):162-173. doi:10.1006/cbmr.1996.0014 https://
pubmed .ncbi .nlm .nih .gov /8812068/ RW Cox, JS Hyde (1997). Software tools for analysis and visualization of FMRI Data. NMR in Biomedicine, 10: 171-178. https://
pubmed .ncbi .nlm .nih .gov /9430344/
FreeSurfer - SynthStrip:
SynthStrip: Skull-Stripping for Any Brain Image; Andrew Hoopes, Jocelyn S. Mora, Adrian V. Dalca, Bruce Fischl*, Malte Hoffmann* (*equal contribution); NeuroImage 260, 2022, 119474; Hoopes et al. (2022)
Boosting skull-stripping performance for pediatric brain images; William Kelley, Nathan Ngo, Adrian V. Dalca, Bruce Fischl, Lilla Zöllei*, Malte Hoffmann* (*equal contribution); IEEE International Symposium on Biomedical Imaging (ISBI), 2024, forthcoming; https://
arxiv .org /abs /2402 .16634
FSL - BET:
M. Jenkinson, C.F. Beckmann, T.E. Behrens, M.W. Woolrich, S.M. Smith. FSL. NeuroImage, 62:782-90, 2012
Smith S. M. (2002). Fast robust automated brain extraction. Human brain mapping, 17(3), 143–155. Smith (2002)
HD-BET:
Isensee F, Schell M, Tursunova I, Brugnara G, Bonekamp D, Neuberger U, Wick A, Schlemmer HP, Heiland S, Wick W, Bendszus M, Maier-Hein KH, Kickingereder P. Automated brain extraction of multi-sequence MRI using artificial neural networks. Hum Brain Mapp. 2019; 1–13. Isensee et al. (2019)
Isensee, F., Jaeger, P.F., Kohl, S.A.A. et al. nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation. Nat Methods 18, 203–211 (2021). Isensee et al. (2020)
Dataset¶
Opensource Data from OpenNeuro:
Kelly AMC and Uddin LQ and Biswal BB and Castellanos FX and Milham MP (2018). Flanker task (event-related). OpenNeuro Dataset ds000102
Kelly, A. M., Uddin, L. Q., Biswal, B. B., Castellanos, F. X., & Milham, M. P. (2008). Competition between functional brain networks mediates behavioral variability. NeuroImage, 39(1), 527–537. [Kelly et al. (2008)](- Kelly, A. M., Uddin, L. Q., Biswal, B. B., Castellanos, F. X., & Milham, M. P. (2008). Competition between functional brain networks mediates behavioral variability. NeuroImage, 39(1), 527–537. https://
doi .org /10 .1016 /j .neuroimage .2007 .08 .008)
ANTs Brain Templates:
Avants, Brian; Tustison, Nick (2018). ANTs/ANTsR Brain Templates. figshare. Dataset. Avants & Tustison (2018)
Install and import python libraries¶
%%capture
!pip install nilearn==0.13.1 nibabel==5.4.2 scipy==1.17.1 numpy==2.4.6import os, pathlib
import nibabel as nib
import numpy as np
from scipy import ndimage
from nilearn import plotting
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from ipyniivue import NiiVue
from IPython.display import display, Markdown, ImageIntroduction¶
Since MR imaging studies focus on brain tissue, skull stripping is one of the first steps in any MR imaging processing pipeline to remove the skull and non-brain areas from the image.
In order to analyze fMRI data, you will need to load an fMRI analysis package. In this example we will use the following packages and algorithms to skull-strip the anatomical image:
FSL (FMRIB Software Library, created by the University of Oxford): BET - Brain Extraction Tool
HD-BET: An artificial neural network-based brain extraction tool showing robust performance in the presence of pathology
Analysis of Functional NeuroImages (AFNI): 3dSkullStrip
FreeSurfer: SynthStrip
Advanced Normalization Tools (ANTs): `antsBrainExtraction.sh`Each package is maintained by a team of professionals, and each is updated at least every few years or so.
FMRIB Software Library (FSL)¶
FSL is a comprehensive library of analysis tools for FMRI, MRI and diffusion brain imaging data. FSL has a tool to skull-strip an anatomical image called bet, or the Brain Extraction Tool.
import module
await module.load('fsl/6.0.7.19')HD-BET (High Definition Brain Extraction Tool)¶
HD-BET is the result of a joint project between the Department of Neuroradiology at the Heidelberg University Hospital, the Divison for Computational Radiology & Clinical AI, University Hospital Bonn and the Division of Medical Image Computing at the German Cancer Research Center (DKFZ). It was developed for robust brain extraction across different MRI sequences and scanners.
# hdbet/2.0.1 ships its model weights baked into the container at
# /opt/HD-BET/hd-bet_params, so no download or bind mount is needed.
import module
await module.load('hdbet/2.0.1')Analysis of Functional NeuroImages (AFNI)¶
AFNI is a suite of programs designed to analyze fMRI data. Created in the mid-1990’s by Bob Cox, AFNI is now used by hundreds of imaging labs around the world.
await module.load('afni/24.1.02')FreeSurfer¶
FreeSurfer is a software package that enables you to analyze structural MRI images - in other words, you can use FreeSurfer to quantify the amount of grey matter and white matter in specific regions of the brain. You will also be able to calculate measurements such as the thickness, curvature, and volume of the different tissue types, and be able to correlate these with covariates; or, you can contrast these structural measurements between groups.
await module.load('freesurfer/8.1.0')Advanced Normalization Tools (ANTs)¶
ANTs is a software package for normalizing data to a template.
Templates for public neuroimaging datasets, such as those from IXI, Oasis, NKI-1, and Kirby/MMRR, are intended for use with ANTs and are available for download from figshare. These templates include an average T1 neuroimage of the head and various tissue priors for cortex, white matter, cerebrospinal fluid, deep gray matter, brainstem and the cerebellum.
await module.load('ants/2.6.5')
await module.list()['fsl/6.0.7.19',
'hdbet/2.0.1',
'afni/24.1.02',
'freesurfer/8.1.0',
'ants/2.6.5']PATTERN = "sub-08/anat"
! datalad install https://github.com/OpenNeuroDatasets/ds000102.git
! cd ds000102 && datalad get $PATTERNinput_image = 'ds000102/sub-08/anat/sub-08_T1w.nii.gz'ANTs Brain Templates¶
You will need templates to perform the brain extraction with ANTs. For this, we will use the OASIS brain templates, which are intended for use with ANTs medical image processing tools. However, it is up to you to determine which template works best for your data.
# Download the OASIS templates using wget
! wget -nc https://ndownloader.figshare.com/files/3133832 -O OASIS.zip
# Unzip the downloaded file
! unzip -n OASIS.zip -d OASIS
# Remove zip file
! rm -f OASIS.zip
# Delete templates that are not needed
! find OASIS/MICCAI2012-Multi-Atlas-Challenge-Data -type f ! -name 'T_template0.nii.gz' ! -name 'T_template0_BrainCerebellumProbabilityMask.nii.gz' -exec rm {} +
# Delete Priors2 subfolder
! rm -rf OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2--2026-10-04 22:02:46-- https://ndownloader.figshare.com/files/3133832
Resolving ndownloader.figshare.com (ndownloader.figshare.com)... 52.17.73.240, 54.217.216.206, 34.253.125.74, ...
Connecting to ndownloader.figshare.com (ndownloader.figshare.com)|52.17.73.240|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://s3-eu-west-1.amazonaws.com/pfigshare-u-files/3133832/Oasis.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIYCQYOYV5JSSROOA/20261004/eu-west-1/s3/aws4_request&X-Amz-Date=20261004T220247Z&X-Amz-Expires=10&X-Amz-SignedHeaders=host&X-Amz-Signature=77a65a85f84a7275b5ae6be72c6857fe058ab2c88cedce977ce3e1bc3a2bb739 [following]
--2026-10-04 22:02:47-- https://s3-eu-west-1.amazonaws.com/pfigshare-u-files/3133832/Oasis.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIYCQYOYV5JSSROOA/20261004/eu-west-1/s3/aws4_request&X-Amz-Date=20261004T220247Z&X-Amz-Expires=10&X-Amz-SignedHeaders=host&X-Amz-Signature=77a65a85f84a7275b5ae6be72c6857fe058ab2c88cedce977ce3e1bc3a2bb739
Resolving s3-eu-west-1.amazonaws.com (s3-eu-west-1.amazonaws.com)... 52.92.36.192, 3.5.75.87, 52.92.17.128, ...
Connecting to s3-eu-west-1.amazonaws.com (s3-eu-west-1.amazonaws.com)|52.92.36.192|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 55360609 (53M) [binary/octet-stream]
Saving to: ‘OASIS.zip’
OASIS.zip 100%[===================>] 52.80M 8.89MB/s in 5.9s
2026-10-04 22:02:55 (8.89 MB/s) - ‘OASIS.zip’ saved [55360609/55360609]
Archive: OASIS.zip
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0_BrainCerebellum.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0_BrainCerebellumExtractionMask.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0_BrainCerebellumMask.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0_BrainCerebellumRegistrationMask.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0_glm_4labelsJointFusion.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0_glm_6labelsJointFusion.nii.gz
creating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2/
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2/priors1.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2/priors2.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2/priors3.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2/priors4.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2/priors5.nii.gz
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/Priors2/priors6.nii.gz
brain_template = 'OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0.nii.gz'
brain_prior = 'OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0_BrainCerebellumProbabilityMask.nii.gz'Brain Extraction¶
1. FSL¶
First, we will do brain extraction with FSL’s BET (Brain Extraction Tool):
! bet
Usage: bet <input> <output> [options]
Main bet2 options:
-o generate brain surface outline overlaid onto original image
-m generate binary brain mask
-s generate approximate skull image
-n don't generate segmented brain image output
-f <f> fractional intensity threshold (0->1); default=0.5; smaller values give larger brain outline estimates
-g <g> vertical gradient in fractional intensity threshold (-1->1); default=0; positive values give larger brain outline at bottom, smaller at top
-r <r> head radius (mm not voxels); initial surface sphere is set to half of this
-c <x y z> centre-of-gravity (voxels not mm) of initial mesh surface.
-t apply thresholding to segmented brain image and mask
-e generates brain surface as mesh in .vtk format
Variations on default bet2 functionality (mutually exclusive options):
(default) just run bet2
-R robust brain centre estimation (iterates BET several times)
-S eye & optic nerve cleanup (can be useful in SIENA - disables -o option)
-B bias field & neck cleanup (can be useful in SIENA)
-Z improve BET if FOV is very small in Z (by temporarily padding end slices)
-F apply to 4D FMRI data (uses -f 0.3 and dilates brain mask slightly)
-A run bet2 and then betsurf to get additional skull and scalp surfaces (includes registrations)
-A2 <T2> as with -A, when also feeding in non-brain-extracted T2 (includes registrations)
Miscellaneous options:
-v verbose (switch on diagnostic messages)
-h display this help, then exits
-d debug (don't delete temporary intermediate images)
! bet $input_image anat_bet.nii.gz -m 2. HD-BET¶
HD-BET is an artificial neural network-based brain extraction tool trained on multicentric clinical data across 37 institutions, designed to be robust across multiple MRI sequences (T1-w, T2-w, FLAIR), different scanner hardware, and pathological conditions such as brain tumors and lesions.
Since we are running on CPU, we use the -device cpu flag along with --disable_tta to disable test time data augmentation, which provides an 8x speedup and is recommended when running without a GPU:
! hd-bet -h
########################
If you are using hd-bet, please cite the following papers:
Isensee F, Schell M, Tursunova I, Brugnara G, Bonekamp D, Neuberger U, Wick A, Schlemmer HP, Heiland S, Wick W, Bendszus M, Maier-Hein KH, Kickingereder P. Automated brain extraction of multi-sequence MRI using artificial neural networks. arXiv preprint arXiv:1901.11341, 2019.
Isensee, F., Jaeger, P. F., Kohl, S. A., Petersen, J., & Maier-Hein, K. H. (2021). nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation. Nature methods, 18(2), 203-211.
########################
usage: hd-bet [-h] -i INPUT [-o OUTPUT] [-device DEVICE] [--disable_tta]
[--save_bet_mask] [--no_bet_image] [--verbose]
options:
-h, --help show this help message and exit
-i INPUT, --input INPUT
input. Can be either a single file name or an input
folder. If file: must be nifti (.nii.gz) and can only
be 3D. No support for 4d images, use fslsplit to split
4d sequences into 3d images. If folder: all files
ending with .nii.gz within that folder will be brain
extracted.
-o OUTPUT, --output OUTPUT
output. Can be either a filename or a folder. If it
does not exist, the folder will be created
-device DEVICE used to set on which device the prediction will run.
Can be 'cuda' (=GPU), 'cpu' or 'mps'. Default: cuda
--disable_tta Set this flag to disable test time augmentation. This
will make prediction faster at a slight decrease in
prediction quality. Recommended for device cpu
--save_bet_mask Set this flag to keep the bet masks. Otherwise they
will be removed once HD_BET is done
--no_bet_image Set this flag to disable generating the skull
stripped/brain extracted image. Only makes sense if
you also set --save_bet_mask
--verbose Talk to me.
! hd-bet -i $input_image -o anat_hd_bet.nii.gz --save_bet_mask -device cpu --disable_tta
########################
If you are using hd-bet, please cite the following papers:
Isensee F, Schell M, Tursunova I, Brugnara G, Bonekamp D, Neuberger U, Wick A, Schlemmer HP, Heiland S, Wick W, Bendszus M, Maier-Hein KH, Kickingereder P. Automated brain extraction of multi-sequence MRI using artificial neural networks. arXiv preprint arXiv:1901.11341, 2019.
Isensee, F., Jaeger, P. F., Kohl, S. A., Petersen, J., & Maier-Hein, K. H. (2021). nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation. Nature methods, 18(2), 203-211.
########################
perform_everything_on_device=True is only supported for cuda devices! Setting this to False
There are 1 cases in the source folder
I am process 0 out of 1 (max process ID is 0, we start counting with 0!)
There are 1 cases that I would like to predict
Predicting anat_hd_bet_bet.nii.gz:
perform_everything_on_device: False
100%|██████████████████████████████████████████| 10/10 [00:51<00:00, 5.11s/it]
sending off prediction to background worker for resampling and export
done with anat_hd_bet_bet.nii.gz
GPU prediction completed. Waiting for remaining segmentation exports to finish...
Collecting results: 100%|████████████████████████| 1/1 [00:00<00:00, 3.69it/s]
Segmentation export complete.
3. AFNI¶
Next, we will use AFNI’s 3dSkullStrip for brain extraction:
! 3dSkullStrip -help# Get skull-stripped output and a mask-volume
! 3dSkullStrip -input $input_image -prefix AFNI_ss.nii.gz -push_to_edge
! 3dSkullStrip -input $input_image -prefix AFNI_mask.nii.gz -push_to_edge -mask_vol3dSkullStrip: Pushing to Edge ...
** ERROR: output dataset name 'AFNI_ss.nii.gz' conflicts with existing file
** ERROR: dataset NOT written to disk!
The intensity in the output dataset is a modified version
of the intensity in the input volume.
To obtain a masked version of the input with identical values inside
the brain, you can either use 3dSkullStrip's -orig_vol option
or run the following command:
3dcalc -a ds000102/sub-08/anat/sub-08_T1w.nii.gz -b ./AFNI_ss.nii.gz+orig -expr 'a*step(b)' \
-prefix ./AFNI_ss.nii.gz_orig_vol
to generate a new masked version of the input.
3dSkullStrip: Pushing to Edge ...
** ERROR: output dataset name 'AFNI_mask.nii.gz' conflicts with existing file
** ERROR: dataset NOT written to disk!
The output dataset is a mask reflecting where voxels in the
input dataset lie in the brain.
To obtain a masked version of the input with identical values inside
the brain, you can either use 3dSkullStrip's -orig_vol option
or run the following command:
3dcalc -a ds000102/sub-08/anat/sub-08_T1w.nii.gz -b ./AFNI_mask.nii.gz+orig -expr 'a*step(b)' \
-prefix ./AFNI_mask.nii.gz_orig_vol
to generate a new masked version of the input.
From AFNI’s documentation:
-push_to_edge: Adds an aggressive push to brain edges. Use this option when the chunks of gray matter are not included. This option might cause the mask to leak into non-brain areas.
4. FreeSurfer¶
FreeSurfer’s SynthStrip is a skull-stripping tool that extracts brain voxels from a landscape of image types, ranging across imaging modalities, resolutions, and subject populations. It leverages a deep learning strategy to synthesize arbitrary training images from segmentation maps, yielding a robust model agnostic to acquisition specifics.
! mri_synthstrip --helpusage: mri_synthstrip [-h] -i FILE [-o FILE] [-m FILE] [-d FILE] [-g]
[-b BORDER] [-t THREADS] [--no-csf] [--model FILE]
Robust, universal skull-stripping for brain images of any type.
optional arguments:
-h, --help show this help message and exit
-i FILE, --image FILE
input image to skullstrip
-o FILE, --out FILE save stripped image to file
-m FILE, --mask FILE save binary brain mask to file
-d FILE, --sdt FILE save distance transform to file
-g, --gpu use the GPU
-b BORDER, --border BORDER
mask border threshold in mm, defaults to 1
-t THREADS, --threads THREADS
PyTorch CPU threads, PyTorch default if unset
--no-csf exclude CSF from brain border
--model FILE alternative model weights
If you use SynthStrip in your analysis, please cite:
----------------------------------------------------
SynthStrip: Skull-Stripping for Any Brain Image
A Hoopes, JS Mora, AV Dalca, B Fischl, M Hoffmann
NeuroImage 206 (2022), 119474
https://doi.org/10.1016/j.neuroimage.2022.119474
Website: https://synthstrip.io
Next, you can run SynthStrip using the following syntax. In this command, “synth_stripped.nii.gz” will be the skull-stripped version of the input image “sub-08_T1w.nii.gz.” Use the -m flag to save a binary brain mask:
! mri_synthstrip -i $input_image -o synth_stripped.nii.gz -m synth_mask.nii.gzConfiguring model on the CPU
Running SynthStrip model version 1
Input image read from: ds000102/sub-08/anat/sub-08_T1w.nii.gz
Processing frame (of 1): 1 done
Masked image saved to: synth_stripped.nii.gz
Binary brain mask saved to: synth_mask.nii.gz
If you use SynthStrip in your analysis, please cite:
----------------------------------------------------
SynthStrip: Skull-Stripping for Any Brain Image
A Hoopes, JS Mora, AV Dalca, B Fischl, M Hoffmann
NeuroImage 206 (2022), 119474
https://doi.org/10.1016/j.neuroimage.2022.119474
Website: https://synthstrip.io
5. ANTs¶
Lastly, we will perform brain extraction with this ANTs commands:
! antsBrainExtraction.sh
antsBrainExtraction.sh performs template-based brain extraction.
Usage:
antsBrainExtraction.sh -d imageDimension
-a anatomicalImage
-e brainExtractionTemplate
-m brainExtractionProbabilityMask
<OPT_ARGS>
-o outputPrefix
Example:
bash /opt/ants-2.6.5/bin/antsBrainExtraction.sh -d 3 -a t1.nii.gz -e brainWithSkullTemplate.nii.gz -m brainPrior.nii.gz -o output
Required arguments:
-d: Image dimension 2 or 3 for 2- or 3-dimensional image (default = 3)
-a: Anatomical image Structural image, typically T1. If more than one
anatomical image is specified, subsequently specified
images are used during the segmentation process. However,
only the first image is used in the registration of priors.
Our suggestion would be to specify the T1 as the first image.
-e: Brain extraction template Anatomical template.
-m: Brain extraction probability mask Brain probability mask, with intensity range 1 (definitely brain)
to 0 (definitely background).
-o: Output prefix Output directory + file prefix.
Optional arguments:
-c: Tissue classification A k-means segmentation is run to find gray or white matter around
the edge of the initial brain mask warped from the template.
This produces a segmentation image with K classes, ordered by mean
intensity in increasing order. With this option, you can control
K and tell the script which classes represent CSF, gray and white matter.
Format (\"KxcsfLabelxgmLabelxwmLabel\").
Examples:
-c 3x1x2x3 for T1 with K=3, CSF=1, GM=2, WM=3 (default)
-c 3x3x2x1 for T2 with K=3, CSF=3, GM=2, WM=1
-c 3x1x3x2 for FLAIR with K=3, CSF=1 GM=3, WM=2
-c 4x4x2x3 uses K=4, CSF=4, GM=2, WM=3
-f: Brain extraction registration mask Mask used for registration to limit the metric computation to
a specific region.
-k: Keep temporary files Keep brain extraction/segmentation warps, etc (default = 0).
-q: Use single floating point precision Use antsRegistration with single (1) or double (0) floating point precision (default = 0).
-r: Initial moving transform An ITK affine transform (eg, from antsAI or ITK-SNAP) for the moving image.
Without this option, this script calls antsAI to search for a good initial moving
transform.
-R: Rotation search parameters Rotation search parameters for antsAI in format step,arcFraction. The step is in
degrees, the arc fraction goes from 0 (no search) to 1 (search -180 to 180
degree rotations in increements of step). The search begins at -(180*arcFraction)
in each dimension - users should choose parameters so that there is a search point
near zero rotation. Default = 20,0.12.
-s: Image file suffix Any of the standard ITK IO formats e.g. nrrd, nii.gz, mhd (default = nii.gz)
-T: Translation search parameters Translation search parameters for antsAI in format step,range. The step is in
mm, -range to range will be tested in each dimension. The default does not search
left-right translations because the brain is usually well-centered along this
dimension in human images. Default = 40,0x40x40.
-u: Use random seeding Use random number generated from system clock (1) or a fixed seed (0). To produce identical
results, multi-threading must also be disabled by setting the environment variable
ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS=1. Default = 1.
-z: Test / debug mode If > 0, runs a faster version of the script. Only for debugging, results will not be good.
To run the command using the OASIS templates, you can follow this structure:
! antsBrainExtraction.sh -d 3 -a $input_image -e $brain_template -m $brain_prior -o ANTS_Stripped_ -z 1The option -d 3 means that it is a three-dimensional image; -a indicates the anatomical image to be stripped; and -e is used to supply a an anatomical template (with skull) and -m to provide a brain probability mask for skull-stripping , and -o is the label (prefix) for the output. The flag -z enables test/debug mode: setting -z 1 runs a faster version of the script for debugging (results will be lower quality), while 0 (default) runs the full pipeline.
Results¶
We will begin by visualizing the brain extraction results from each tool individually to assess the quality of the extracted brain images. Then, to better highlight differences between the methods, we will generate an overlay of the brain edges, allowing a direct comparison of how the algorithms define brain boundaries.
display(Markdown("### FSL BET"))
nv_FSL = NiiVue()
nv_FSL.load_volumes([{"url": "https://huggingface.co/datasets/neurodeskorg/neurodeskedu/resolve/main/data/examples/structural_imaging/brain_extraction_different_tools/anat_bet_b7452a26340d.nii.gz"}])
nv_FSLdisplay(Markdown("### HD-BET"))
nv_HD_BET = NiiVue()
nv_HD_BET.load_volumes([{"url": "https://huggingface.co/datasets/neurodeskorg/neurodeskedu/resolve/main/data/examples/structural_imaging/brain_extraction_different_tools/anat_hd_bet_1c252e2f85c7.nii.gz"}])
nv_HD_BETdisplay(Markdown("### AFNI 3dSkullStrip"))
nv_AFNI = NiiVue()
nv_AFNI.load_volumes([{"url": "https://huggingface.co/datasets/neurodeskorg/neurodeskedu/resolve/main/data/examples/structural_imaging/brain_extraction_different_tools/AFNI_ss_1022107b7f66.nii.gz"}])
nv_AFNIdisplay(Markdown("### FreeSurfer SynthStrip"))
nv_FreeSurfer = NiiVue()
nv_FreeSurfer.load_volumes([{"url": "https://huggingface.co/datasets/neurodeskorg/neurodeskedu/resolve/main/data/examples/structural_imaging/brain_extraction_different_tools/synth_stripped_4c4517e30597.nii.gz"}])
nv_FreeSurferdisplay(Markdown("### ANTs BrainExtraction"))
nv_ANTS = NiiVue()
nv_ANTS.load_volumes([{"url": "https://huggingface.co/datasets/neurodeskorg/neurodeskedu/resolve/main/data/examples/structural_imaging/brain_extraction_different_tools/ANTS_Stripped_BrainExtractionBrain_69903f651fcb.nii.gz"}])
nv_ANTS Comparison of the different brain extraction methods¶
def extract_edges_from_mask(mask_path):
"""
Detect edges from a binary brain mask using 3D Sobel operator.
Parameters:
mask_path (str): path to the binary brain mask (.nii.gz)
Returns:
nib.Nifti1Image: NIfTI image of the edge mask
"""
img = nib.load(mask_path)
data = img.get_fdata()
# Ensure it's binary
binary = (data > 0).astype(float)
# Compute 3D gradient magnitude using Sobel
grad_x = ndimage.sobel(binary, axis=0)
grad_y = ndimage.sobel(binary, axis=1)
grad_z = ndimage.sobel(binary, axis=2)
grad_mag = np.sqrt(grad_x**2 + grad_y**2 + grad_z**2)
# Threshold to detect edge voxels
edges = (grad_mag > 0).astype(float)
return nib.Nifti1Image(edges, img.affine)
def create_combined_plot(edge_imgs, labels, colors, bg_img, title):
"""Combined plot """
# Initialize combined data
combined_data = np.zeros_like(edge_imgs[0].get_fdata())
# Combine the edge data
for i, edge_img in enumerate(edge_imgs):
edge_data = edge_img.get_fdata()
# Assign different values (1, 2, 3, etc.) for each edge mask
combined_data[edge_data > 0] = i + 1
# Create the combined image
combined_img = nib.Nifti1Image(combined_data, edge_imgs[0].affine)
custom_cmap = ListedColormap(colors)
fig = plt.figure(figsize=(14, 8))
plotting.plot_stat_map(combined_img, bg_img=bg_img,
cmap=custom_cmap,
transparency=0.8,
dim=-1,
threshold=0.5, # Only show actual edge values
title=title,
colorbar=False,
vmin=1,
vmax=len(edge_imgs)) # 5 edge images = values 1-5
# Add legend
legend_elements = [mpatches.Patch(color=colors[i], label=labels[i])
for i in range(len(labels))]
plt.legend(handles=legend_elements, loc='upper left', bbox_to_anchor=(1.02, 1))
plt.subplots_adjust(right=0.82)# Generate edges from the binary brain masks
bet_edges = extract_edges_from_mask("anat_bet_mask.nii.gz")
hd_bet_edges = extract_edges_from_mask("anat_hd_bet_bet.nii.gz")
afni_edges = extract_edges_from_mask("AFNI_mask.nii.gz")
synth_edges = extract_edges_from_mask("synth_mask.nii.gz")
ants_edges = extract_edges_from_mask("ANTS_Stripped_BrainExtractionMask.nii.gz")#Check edges
plotting.plot_anat(synth_edges)<nilearn.plotting.displays._slicers.OrthoSlicer at 0x7717f0fbe900>
edge_imgs = [bet_edges, hd_bet_edges, afni_edges, synth_edges, ants_edges]
labels = ['FSL', 'HD-BET', 'AFNI', 'FreeSurfer', 'ANTS',]
colors = ['#FF0000', '#0000FF', '#00FF00', '#FFA500', '#800080']
create_combined_plot(edge_imgs, labels, colors, input_image, "Brain Extraction Method Comparison")<Figure size 1400x800 with 0 Axes>
Dependencies in Jupyter/Python¶
Using the package watermark to document system environment and software versions used in this notebook, alongside the Neurodesktop version extracted from the
JUPYTER_IMAGEorNEURODESKTOP_VERSIONenvironment variables.
import os
%load_ext watermark
%watermark
%watermark --iversions
neurodesktop_version = (
os.environ.get('JUPYTER_IMAGE', '').split(':')[-1] or
os.environ.get('NEURODESKTOP_VERSION', 'unknown')
)
print(f"Neurodesktop version: {neurodesktop_version}")Last updated: 2026-10-04T22:11:56.709470+00:00
Python implementation: CPython
Python version : 3.13.15
IPython version : 9.17.1
Compiler : GCC 15.3.0
OS : Linux
Release : 6.8.0-111-generic
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
IPython : 9.17.1
ipyniivue : 2.4.4
matplotlib: 3.11.2
nibabel : 5.4.2
nilearn : 0.13.1
numpy : 2.4.6
scipy : 1.17.1
Neurodesktop version: 2026-09-28
- Tustison, N. J., Cook, P. A., Holbrook, A. J., Johnson, H. J., Muschelli, J., Devenyi, G. A., Duda, J. T., Das, S. R., Cullen, N. C., Gillen, D. L., Yassa, M. A., Stone, J. R., Gee, J. C., & Avants, B. B. (2021). The ANTsX ecosystem for quantitative biological and medical imaging. Scientific Reports, 11(1). 10.1038/s41598-021-87564-6
- Hoopes, A., Mora, J. S., Dalca, A. V., Fischl, B., & Hoffmann, M. (2022). SynthStrip: skull-stripping for any brain image. NeuroImage, 260, 119474. 10.1016/j.neuroimage.2022.119474
- Smith, S. M. (2002). Fast robust automated brain extraction. Human Brain Mapping, 17(3), 143–155. 10.1002/hbm.10062
- Isensee, F., Schell, M., Pflueger, I., Brugnara, G., Bonekamp, D., Neuberger, U., Wick, A., Schlemmer, H., Heiland, S., Wick, W., Bendszus, M., Maier‐Hein, K. H., & Kickingereder, P. (2019). Automated brain extraction of multisequence MRI using artificial neural networks. Human Brain Mapping, 40(17), 4952–4964. 10.1002/hbm.24750
- Isensee, F., Jaeger, P. F., Kohl, S. A. A., Petersen, J., & Maier-Hein, K. H. (2020). nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation. Nature Methods, 18(2), 203–211. 10.1038/s41592-020-01008-z
- Kelly, A. M. C., Uddin, L. Q., Biswal, B. B., Castellanos, F. X., & Milham, M. P. (2008). Competition between functional brain networks mediates behavioral variability. NeuroImage, 39(1), 527–537. 10.1016/j.neuroimage.2007.08.008