Brain Extraction Tools#
Author: Monika Doerig
Date: 10 June 2025
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). https://doi.org/10.1038/s41598-021-87564-6
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; https://doi.org/10.1016/j.neuroimage.2022.119474
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. https://doi.org/10.1002/hbm.10062
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-37
ANTs Brain Templates:
Avants, Brian; Tustison, Nick (2018). ANTs/ANTsR Brain Templates. figshare. Dataset. https://doi.org/10.6084/m9.figshare.915436.v2
Install and import python libraries#
%%capture
!pip install nilearn nibabel scipy numpy
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, Image
Introduction#
Since fMRI studies focus on brain tissue, our first step is 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:
Advanced Normalization Tools (ANTs): antsBrainExtraction.sh
Analysis of Functional NeuroImages (AFNI): 3dSkullStrip
FreeSurfer: SynthStrip
FSL (FMRIB Software Library, created by the University of Oxford): BET - Brain Extraction Tool
Each package is maintained by a team of professionals, and each is updated at least every few years or so.
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.
import module
await module.load('ants/2.3.1')
await module.list()
Lmod Warning: MODULEPATH is undefined.
Lmod has detected the following error: The following module(s) are unknown:
"ants/2.3.1"
Please check the spelling or version number. Also try "module spider ..."
It is also possible your cache file is out-of-date; it may help to try:
$ module --ignore_cache load "ants/2.3.1"
Also make sure that all modulefiles written in TCL start with the string
#%Module
[]
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')
await module.list()
Lmod Warning: MODULEPATH is undefined.
Lmod has detected the following error: The following module(s) are unknown:
"afni/24.1.02"
Please check the spelling or version number. Also try "module spider ..."
It is also possible your cache file is out-of-date; it may help to try:
$ module --ignore_cache load "afni/24.1.02"
Also make sure that all modulefiles written in TCL start with the string
#%Module
[]
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/7.3.2')
await module.list()
Lmod Warning: MODULEPATH is undefined.
Lmod has detected the following error: The following module(s) are unknown:
"freesurfer/7.3.2"
Please check the spelling or version number. Also try "module spider ..."
It is also possible your cache file is out-of-date; it may help to try:
$ module --ignore_cache load "freesurfer/7.3.2"
Also make sure that all modulefiles written in TCL start with the string
#%Module
[]
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.
await module.load('fsl/6.0.7.4')
await module.list()
Lmod Warning: MODULEPATH is undefined.
Lmod has detected the following error: The following module(s) are unknown:
"fsl/6.0.7.4"
Please check the spelling or version number. Also try "module spider ..."
It is also possible your cache file is out-of-date; it may help to try:
$ module --ignore_cache load "fsl/6.0.7.4"
Also make sure that all modulefiles written in TCL start with the string
#%Module
[]
Download Data#
T1 Image for brain extraction#
PATTERN = "sub-08/anat"
! datalad install https://github.com/OpenNeuroDatasets/ds000102.git
! cd ds000102 && datalad get $PATTERN
It is highly recommended to configure Git before using DataLad. Set both 'user.name' and 'user.email' configuration variables.
Cloning: 0%| | 0.00/2.00 [00:00<?, ? candidates/s]
Enumerating: 0.00 Objects [00:00, ? Objects/s]
Counting: 0%| | 0.00/27.0 [00:00<?, ? Objects/s]
Compressing: 0%| | 0.00/23.0 [00:00<?, ? Objects/s]
Receiving: 0%| | 0.00/2.15k [00:00<?, ? Objects/s]
Resolving: 0%| | 0.00/537 [00:00<?, ? Deltas/s]
[INFO ] Remote origin not usable by git-annex; setting annex-ignore
[INFO ] https://github.com/OpenNeuroDatasets/ds000102.git/config download failed: Not Found
[INFO ] Author identity unknown
|
| *** Please tell me who you are.
|
| Run
|
| git config --global user.email "you@example.com"
| git config --global user.name "Your Name"
|
| to set your account's default identity.
| Omit --global to set the identity only in this repository.
|
| fatal: unable to auto-detect email address (got 'root@2a8daca840e9.(none)')
[INFO ] git-annex: user error (git ["--git-dir=.git","--work-tree=.","--literal-pathspecs","-c","annex.dotfiles=true","commit-tree","c5e060bdab4258bcbd7ab2c4fbb6d6a9ff003efb","--no-gpg-sign","-p","refs/heads/git-annex"] exited 128)
install(error): /tmp/tmp0ydsgwgz/ds000102 (dataset) [CommandError: 'git -c diff.ignoreSubmodules=none -c core.quotepath=false annex init -c annex.dotfiles=true' failed with exitcode 1 under /tmp/tmp0ydsgwgz/ds000102] [CommandError: 'git -c diff.ignoreSubmodules=none -c core.quotepath=false annex init -c annex.dotfiles=true' failed with exitcode 1 under /tmp/tmp0ydsgwgz/ds000102]
/bin/bash: line 1: cd: ds000102: No such file or directory
input_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
--2025-12-05 08:12:00-- https://ndownloader.figshare.com/files/3133832
Resolving ndownloader.figshare.com (ndownloader.figshare.com)...
52.214.13.182, 52.212.54.36, 54.229.133.28, ...
Connecting to ndownloader.figshare.com (ndownloader.figshare.com)|52.214.13.182|: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/20251205/eu-west-1/s3/aws4_request&X-Amz-Date=20251205T081201Z&X-Amz-Expires=10&X-Amz-SignedHeaders=host&X-Amz-Signature=5056a13ddae7a0ebb1ba85c5260e7455f45ff5e7c0025a2035f910e3e6974c33 [following]
--2025-12-05 08:12:01-- https://s3-eu-west-1.amazonaws.com/pfigshare-u-files/3133832/Oasis.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIYCQYOYV5JSSROOA/20251205/eu-west-1/s3/aws4_request&X-Amz-Date=20251205T081201Z&X-Amz-Expires=10&X-Amz-SignedHeaders=host&X-Amz-Signature=5056a13ddae7a0ebb1ba85c5260e7455f45ff5e7c0025a2035f910e3e6974c33
Resolving s3-eu-west-1.amazonaws.com (s3-eu-west-1.amazonaws.com)... 3.5.69.183, 3.5.68.198, 3.5.67.9, ...
Connecting to s3-eu-west-1.amazonaws.com (s3-eu-west-1.amazonaws.com)|3.5.69.183|:443...
connected.
HTTP request sent, awaiting response...
200 OK
Length: 55360609 (53M) [binary/octet-stream]
Saving to: ‘OASIS.zip’
OASIS.zip 0%[ ] 0 --.-KB/s
OASIS.zip 0%[ ] 32.43K 114KB/s
OASIS.zip 0%[ ] 83.43K 146KB/s
OASIS.zip 0%[ ] 151.43K 177KB/s
OASIS.zip 0%[ ] 338.43K 296KB/s
OASIS.zip 1%[ ] 678.43K 476KB/s
OASIS.zip 2%[ ] 1.34M 804KB/s
OASIS.zip 5%[> ] 2.70M 1.35MB/s
OASIS.zip 9%[> ] 5.26M 2.32MB/s
OASIS.zip 15%[==> ] 8.23M 3.22MB/s
OASIS.zip 21%[===> ] 11.21M 3.95MB/s
OASIS.zip 26%[====> ] 14.18M 4.54MB/s eta 9s
OASIS.zip 32%[=====> ] 17.17M 5.04MB/s eta 9s
OASIS.zip 37%[======> ] 20.02M 5.42MB/s eta 9s
OASIS.zip 43%[=======> ] 23.01M 5.79MB/s eta 9s
OASIS.zip 49%[========> ] 25.95M 6.09MB/s eta 4s
OASIS.zip 54%[=========> ] 28.76M 6.33MB/s eta 4s
OASIS.zip 60%[===========> ] 31.70M 6.56MB/s eta 4s
OASIS.zip 65%[============> ] 34.65M 6.77MB/s eta 4s
OASIS.zip 70%[=============> ] 37.35M 6.92MB/s eta 2s
OASIS.zip 75%[==============> ] 40.07M 7.05MB/s eta 2s
OASIS.zip 81%[===============> ] 43.04M 7.57MB/s eta 2s
OASIS.zip 87%[================> ] 45.96M 8.07MB/s eta 2s
OASIS.zip 92%[=================> ] 48.77M 8.55MB/s eta 1s
OASIS.zip 97%[==================> ] 51.71M 9.04MB/s eta 1s
OASIS.zip 100%[===================>] 52.80M 9.08MB/s in 6.9s
2025-12-05 08:12:10 (7.63 MB/s) - ‘OASIS.zip’ saved [55360609/55360609]
Archive: OASIS.zip
inflating: OASIS/MICCAI2012-Multi-Atlas-Challenge-Data/T_template0.nii.gz
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_BrainCerebellumProbabilityMask.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. ANTs#
First, we will perform brain extraction with this ANTs commands:
! antsBrainExtraction.sh
/bin/bash: line 1: antsBrainExtraction.sh: command not found
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_
/bin/bash: line 1: antsBrainExtraction.sh: command not found
The 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.
2. AFNI#
Next, we will use AFNI’s 3dSkullStrip for brain extraction
! 3dSkullStrip -help
/bin/bash: line 1: 3dSkullStrip: command not found
# 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_vol
/bin/bash: line 1: 3dSkullStrip: command not found
/bin/bash: line 1: 3dSkullStrip: command not found
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.
3. 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 --help
/bin/bash: line 1: mri_synthstrip: command not found
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.gz
/bin/bash: line 1: mri_synthstrip: command not found
4. FSL#
Another option for brain extraction is FSL’s BET (Brain Extraction Tool):
! bet
/bin/bash: line 1: bet: command not found
! bet $input_image anat_bet.nii.gz -m
/bin/bash: line 1: bet: command not found
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("### ANTs BrainExtraction"))
nv_ANTS = NiiVue()
nv_ANTS.load_volumes([{"path": "ANTS_Stripped_BrainExtractionBrain.nii.gz"}])
nv_ANTS
ANTs BrainExtraction
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[19], line 4
1 display(Markdown("### ANTs BrainExtraction"))
3 nv_ANTS = NiiVue()
----> 4 nv_ANTS.load_volumes([{"path": "ANTS_Stripped_BrainExtractionBrain.nii.gz"}])
5 nv_ANTS
File /opt/conda/lib/python3.13/site-packages/ipyniivue/widget.py:581, in NiiVue.load_volumes(self, volumes)
560 def load_volumes(self, volumes: list):
561 """
562 Load a list of volume objects.
563
(...) 579
580 """
--> 581 volumes = [Volume(**item) for item in volumes]
582 self.volumes = volumes
File /opt/conda/lib/python3.13/site-packages/ipyniivue/widget.py:254, in Volume.__init__(self, **kwargs)
239 include_keys = {
240 "path",
241 "paired_img_path",
(...) 251 "colormap_label",
252 }
253 filtered_kwargs = {k: v for k, v in kwargs.items() if k in include_keys}
--> 254 super().__init__(**filtered_kwargs)
File /opt/conda/lib/python3.13/site-packages/anywidget/widget.py:62, in AnyWidget.__init__(self, *args, **kwargs)
57 anywidget_traits[_ANYWIDGET_ID_KEY] = t.Unicode(
58 f"{self.__class__.__module__}.{self.__class__.__name__}",
59 ).tag(sync=True)
61 self.add_traits(**anywidget_traits)
---> 62 super().__init__(*args, **kwargs)
63 _register_anywidget_commands(self)
File /opt/conda/lib/python3.13/site-packages/ipywidgets/widgets/widget.py:506, in Widget.__init__(self, **kwargs)
503 super().__init__(**kwargs)
505 Widget._call_widget_constructed(self)
--> 506 self.open()
File /opt/conda/lib/python3.13/site-packages/ipywidgets/widgets/widget.py:525, in Widget.open(self)
523 """Open a comm to the frontend if one isn't already open."""
524 if self.comm is None:
--> 525 state, buffer_paths, buffers = _remove_buffers(self.get_state())
527 args = dict(target_name='jupyter.widget',
528 data={'state': state, 'buffer_paths': buffer_paths},
529 buffers=buffers,
530 metadata={'version': __protocol_version__}
531 )
532 if self._model_id is not None:
File /opt/conda/lib/python3.13/site-packages/ipywidgets/widgets/widget.py:615, in Widget.get_state(self, key, drop_defaults)
613 for k in keys:
614 to_json = self.trait_metadata(k, 'to_json', self._trait_to_json)
--> 615 value = to_json(getattr(self, k), self)
616 if not drop_defaults or not self._compare(value, traits[k].default_value):
617 state[k] = value
File /opt/conda/lib/python3.13/site-packages/ipyniivue/utils.py:47, in file_serializer(instance, widget)
45 # Make sure we have a pathlib.Path instance
46 instance = pathlib.Path(instance)
---> 47 return {"name": instance.name, "data": instance.read_bytes()}
File /opt/conda/lib/python3.13/pathlib/_abc.py:625, in PathBase.read_bytes(self)
621 def read_bytes(self):
622 """
623 Open the file in bytes mode, read it, and close the file.
624 """
--> 625 with self.open(mode='rb') as f:
626 return f.read()
File /opt/conda/lib/python3.13/pathlib/_local.py:537, in Path.open(self, mode, buffering, encoding, errors, newline)
535 if "b" not in mode:
536 encoding = io.text_encoding(encoding)
--> 537 return io.open(self, mode, buffering, encoding, errors, newline)
FileNotFoundError: [Errno 2] No such file or directory: 'ANTS_Stripped_BrainExtractionBrain.nii.gz'
Image(url='https://raw.githubusercontent.com/NeuroDesk/example-notebooks/refs/heads/main/books/images/ANTS_brain_extraction.png')

display(Markdown("### AFNI 3dSkullStrip"))
nv_AFNI = NiiVue()
nv_AFNI.load_volumes([{"path": "AFNI_ss.nii.gz"}])
nv_AFNI
AFNI 3dSkullStrip
Image(url='https://raw.githubusercontent.com/NeuroDesk/example-notebooks/refs/heads/main/books/images/AFNI_brain_extraction.png')

display(Markdown("### FreeSurfer SynthStrip"))
nv_FreeSurfer = NiiVue()
nv_FreeSurfer.load_volumes([{"path": "synth_stripped.nii.gz"}])
nv_FreeSurfer
FreeSurfer SynthStrip
Image(url='https://raw.githubusercontent.com/NeuroDesk/example-notebooks/refs/heads/main/books/images/FreeSurfer_brain_extraction.png')

display(Markdown("### FSL BET"))
nv_FSL = NiiVue()
nv_FSL.load_volumes([{"path": "anat_bet.nii.gz"}])
nv_FSL
FSL BET
Image(url='https://raw.githubusercontent.com/NeuroDesk/example-notebooks/refs/heads/main/books/images/FSL_brain_extraction.png')

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)) # 4 edge images = values 1-4
# 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
ants_edges = extract_edges_from_mask("ANTS_Stripped_BrainExtractionMask.nii.gz")
bet_edges = extract_edges_from_mask("anat_bet_mask.nii.gz")
afni_edges = extract_edges_from_mask("AFNI_mask.nii.gz")
synth_edges = extract_edges_from_mask("synth_mask.nii.gz")
#Check edges
plotting.plot_anat(synth_edges)
<nilearn.plotting.displays._slicers.OrthoSlicer at 0x7f5993867d10>
edge_imgs = [ants_edges, bet_edges, afni_edges, synth_edges]
labels = ['ANTS', 'FSL', 'AFNI', 'FreeSurfer']
colors = ['#FF0000', '#0000FF', '#00FF00', '#FFA500']
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
%load_ext watermark
%watermark
%watermark --iversions
Last updated: 2025-10-30T00:56:49.507799+00:00
Python implementation: CPython
Python version : 3.11.6
IPython version : 8.16.1
Compiler : GCC 12.3.0
OS : Linux
Release : 5.4.0-204-generic
Machine : x86_64
Processor : x86_64
CPU cores : 32
Architecture: 64bit
nilearn : 0.12.1
IPython : 8.16.1
ipyniivue : 2.3.2
nibabel : 5.2.1
matplotlib: 3.8.4
numpy : 2.2.6
scipy : 1.13.0