https://doi.org/10.5281/zenodo.18843449

FreeSurfer#

Author: Steffen Bollmann

Date: 17 Oct 2024

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:#

Tools included in this workflow#

FreeSurfer:

Dataset#

MP2RAGE T1-weighted average 7T model (human brain model)

  • Bollmann, Steffen, Andrew Janke, Lars Marstaller, David Reutens, Kieran O’Brien, and Markus Barth. “MP2RAGE T1-weighted average 7T model” January 1, 2017. doi:10.14264/uql.2017.266

Load FreeSurfer#

# we can use module to load freesurfer in a specific version
import module
await module.load('freesurfer/8.0.0')
await module.list()
['freesurfer/8.0.0']
# Request a freesurfer license and store it in your homedirectory. This is just an exampe - please replace with your license id:
!echo "Steffen.Bollmann@cai.uq.edu.au" > ~/.license
!echo "21029" >> ~/.license
!echo "*Cqyn12sqTCxo" >> ~/.license
!echo "FSxgcvGkNR59Y" >> ~/.license
!recon-all
USAGE: recon-all

 Required Arguments:
   -subjid <subjid>
   -<process directive>

 Fully-Automated Directive:
  -all           : performs all stages of cortical reconstruction
  -autorecon-all : same as -all

 Manual-Intervention Workflow Directives:
  -autorecon1    : process stages 1-5 (see below)
  -autorecon2    : process stages 6-23
                   after autorecon2, check white surfaces:
                     a. if wm edit was required, then run -autorecon2-wm
                     b. if control points added, then run -autorecon2-cp
                     c. proceed to run -autorecon3
  -autorecon2-cp : process stages 12-23 (uses -f w/ mri_normalize, -keep w/ mri_seg)
  -autorecon2-wm : process stages 15-23
  -autorecon2-inflate1 : 6-18
  -autorecon2-perhemi : tess, sm1, inf1, q, fix, sm2, inf2, finalsurf, ribbon
  -autorecon3    : process stages 24-34
                     if edits made to correct pial, then run -autorecon-pial
  -hemi ?h       : just do lh or rh (default is to do both)

  Autorecon Processing Stages (see -autorecon# flags above):
    1.  Motion Correction and Conform
    2.  NU (Non-Uniform intensity normalization)
    3.  Talairach transform computation
    4.  Intensity Normalization 1
    5.  Skull Strip

    6.  EM Register (linear volumetric registration)
    7.  CA Intensity Normalization
    8.  CA Non-linear Volumetric Registration 
    9.  Remove neck
    10. EM Register, with skull
    11. CA Label (Aseg: Volumetric Labeling) and Statistics

    12. Intensity Normalization 2 (start here for control points)
    13. White matter segmentation
    14. Edit WM With ASeg
    15. Fill (start here for wm edits)
    16. Tessellation (begins per-hemisphere operations)
    17. Smooth1
    18. Inflate1
    19. QSphere
    20. Automatic Topology Fixer
    21. White Surfs (start here for brain edits for pial surf)
    22. Smooth2
    23. Inflate2

    24. Spherical Mapping
    25. Spherical Registration 
    26. Spherical Registration, Contralater hemisphere
    27. Map average curvature to subject
    28. Cortical Parcellation (Labeling)
    29. Cortical Parcellation Statistics
    30. Pial Surfs
    31. WM/GM Contrast
    32. Cortical Ribbon Mask
    33. Cortical Parcellation mapped to ASeg
    34  Brodmann and exvio EC labels

 Step-wise Directives
  See -help

 Expert Preferences
  -pons-crs C R S : col, row, slice of seed point for pons, used in fill
  -cc-crs C R S : col, row, slice of seed point for corpus callosum, used in fill
  -lh-crs C R S : col, row, slice of seed point for left hemisphere, used in fill
  -rh-crs C R S : col, row, slice of seed point for right hemisphere, used in fill
  -nofill        : do not use the automatic subcort seg to fill
  -watershed cmd : control skull stripping/watershed program
  -xmask file : custom external brain mask to replace automated skullstripping
  -wsless : decrease watershed threshold (leaves less skull, but can strip more brain)
  -wsmore : increase watershed threshold (leaves more skull, but can strip less brain)
  -wsatlas : use atlas when skull stripping
  -no-wsatlas : do not use atlas when skull stripping
  -no-wsgcaatlas : do not use GCA atlas when skull stripping
  -wsthresh pct : explicity set watershed threshold
  -wsseed C R S : identify an index (C, R, S) point in the skull
  -norm3diters niters : number of 3d iterations for mri_normalize
  -normmaxgrad maxgrad : max grad (-g) for mri_normalize. Default is 1.
  -norm1-b N : in the _first_ usage of mri_normalize, use control 
               point with intensity N below target (default=10.0) 
  -norm2-b N : in the _second_ usage of mri_normalize, use control 
               point with intensity N below target (default=10.0) 
  -norm1-n N : in the _first_ usage of mri_normalize, do N number 
               of iterations
  -norm2-n N : in the _second_ usage of mri_normalize, do N number 
               of iterations
  -cm           : conform volumes to the min voxel size 
  -no-fix-with-ga : do not use genetic algorithm when fixing topology
  -fix-diag-only  : topology fixer runs until ?h.defect_labels files
                    are created, then stops
  -seg-wlo wlo : set wlo value for mri_segment and mris_make_surfaces
  -seg-ghi ghi : set ghi value for mri_segment and mris_make_surfaces
  -nothicken   : pass '-thicken 0' to mri_segment
  -no-ca-align-after : turn off -align-after with mri_ca_register
  -no-ca-align : turn off -align with mri_ca_label
  -deface      : deface subject, written to orig_defaced.mgz

  -expert file     : read-in expert options file
  -xopts-use       : use pre-existing expert options file
  -xopts-clean     : delete pre-existing expert options file
  -xopts-overwrite : overwrite pre-existing expert options file
  -termscript script : run script before exiting (multiple -termscript flags possible)
   This can be good for running custom post-processing after recon-all
   The script must be in your path. The subjid is passed as the only argument
   The current directory is changed to SUBJECTS_DIR before the script is run
   The script should exit with 0 unless there is an error

  -mprage : assume scan parameters are MGH MP-RAGE protocol
  -washu_mprage : assume scan parameters are Wash.U. MP-RAGE protocol.
                  both mprage flags affect mri_normalize and mri_segment,
                  and assumes a darker gm.
  -schwartzya3t-atlas : for tal reg, use special young adult 3T atlas

  -threads num  : set number of threads to use

 Notification Files (Optional)
  -waitfor file : wait for file to appear before beginning
  -notify  file : create this file after finishing

 Status and Log files (Optional)
  -log     file : default is scripts/recon-all.log
  -status  file : default is scripts/recon-all-status.log
  -noappend     : start new log and status files instead of appending
  -no-isrunning : do not check whether this subject is currently being processed

 Segmentation of substructures of hippocampus and brainstem 
 (These deprecated; please see segmentHA_T1.sh, segmentHA_T1.sh, segmentHA_T1_long.sh, segmentBS.sh)
  -hippocampal-subfields-T1 : segmentation of hippocampal subfields using input T1 scan
  -hippocampal-subfields-T2 file ID : segmentation using an additional scan (given by file);
                                      ID is a user-defined identifier for the analysis
  -hippocampal-subfields-T1T2 file ID : segmentation using additional scan (given by file) and input T1
                                        simultaneously; ID is a user-defined identifier for the analysis
  -brainstem-structures : segmentation of brainstem structures

 Other Arguments (Optional)
  -sd subjectsdir : specify subjects dir (default env SUBJECTS_DIR)
  -mail username  : mail user when done
  -umask umask    : set unix file permission mask (default 002)
  -grp groupid    : check that current group is alpha groupid 
  -onlyversions   : print version of each binary and exit
  -debug          : print out lots of info
  -allowcoredump  : set coredump limit to unlimited
  -dontrun        : do everything but execute each command
  -version        : print version of this script and exit
  -help           : voluminous bits of wisdom

Download data#

![ -f ./mp2rage.nii  ] && echo "$FILE exist." || wget https://imaging.org.au/uploads/Human7T/mp2rageModel_L13_work03-plus-hippocampus-7T-sym-norm-mincanon_v0.8.nii -O ./mp2rage.nii 
 exist.
!ls 
FSL_course_bet.ipynb			freesurfer.ipynb
SYNcro.ipynb				intro.md
brain_extraction_different_tools.ipynb	mp2rage.nii
freesurfer-output			sct_toolbox.ipynb
freesurfer-recon-all-clinical.ipynb

Run#

%%bash
#--------------------------------------------
# FreeSurfer recon-all pipeline
#--------------------------------------------
set -euo pipefail  # Stop on errors or unset variables

#----------------------------
# Config
#----------------------------
# Paths
INPUT_SCAN=./mp2rage.nii
SUBJECT_ID=subjectname
SUBJECTS_DIR=$PWD/freesurfer-output

# Ensure output folder exists
mkdir -p "$SUBJECTS_DIR"

#----------------------------
# Environment Setup
# Allow deeper folder structures in some FreeSurfer builds
#----------------------------
export SUBJECTS_DIR="$SUBJECTS_DIR"
export FS_ALLOW_DEEP=1
export SINGULARITYENV_FS_ALLOW_DEEP=1
export APPTAINERENV_FS_ALLOW_DEEP=1
export FS_LICENSE=~/.license 

#----------------------------
# Start Pipeline
#----------------------------
if [ -f "$SUBJECTS_DIR/$SUBJECT_ID/scripts/recon-all.done" ]; then
    echo "recon-all already completed for $SUBJECT_ID, skipping."
else
    echo "Starting recon-all for $SUBJECT_ID..."
    recon-all -subject "$SUBJECT_ID" -i "$INPUT_SCAN" -all -sd "$SUBJECTS_DIR"
    echo "----- recon-all completed -----"
fi
recon-all already completed for subjectname, skipping.
!ls ./freesurfer-output/subjectname/mri
T1.mgz			      entowm.mgz	      ribbon.mgz
antsdn.brain.mgz	      filled.auto.mgz	      segment.dat
aparc+aseg.mgz		      filled.mgz	      surface.defects.mgz
aparc.DKTatlas+aseg.mgz       lh.ribbon.mgz	      synthseg.rca.mgz
aparc.a2009s+aseg.mgz	      mca-dura.mgz	      synthstrip.mgz
aseg.auto.mgz		      mri_nu_correct.mni.log  talairach.log
aseg.auto_noCCseg.mgz	      mrisps.white.mgz	      tmp
aseg.mgz		      mrisps.wpa.mgz	      transforms
aseg.presurf.hypos.mgz	      norm.mgz		      vsinus.log
aseg.presurf.mgz	      nu.mgz		      vsinus.mgz
brain.finalsurfs.manedit.mgz  orig		      wm.asegedit.mgz
brain.finalsurfs.mgz	      orig.mgz		      wm.mgz
brain.mgz		      rawavg.mgz	      wm.seg.mgz
brainmask.mgz		      rawavg2orig.lta	      wmparc.mgz
ctrl_pts.mgz		      rh.ribbon.mgz
!ls ./freesurfer-output/subjectname/surf
autodet.gw.stats.lh.dat  lh.smoothwm.K1.crv	  rh.inflated.nofix
autodet.gw.stats.rh.dat  lh.smoothwm.K2.crv	  rh.jacobian_white
lh.area			 lh.smoothwm.S.crv	  rh.orig
lh.area.mid		 lh.smoothwm.nofix	  rh.orig.nofix
lh.area.pial		 lh.sphere		  rh.orig.premesh
lh.avg_curv		 lh.sphere.reg		  rh.pial
lh.curv			 lh.sulc		  rh.pial.T1
lh.curv.pial		 lh.thickness		  rh.qsphere.nofix
lh.defect_borders	 lh.volume		  rh.smoothwm
lh.defect_chull		 lh.w-g.pct.mgh		  rh.smoothwm.BE.crv
lh.defect_labels	 lh.white		  rh.smoothwm.C.crv
lh.defects.pointset	 lh.white.H		  rh.smoothwm.FI.crv
lh.fsaverage.sphere.reg  lh.white.K		  rh.smoothwm.H.crv
lh.inflated		 lh.white.preaparc	  rh.smoothwm.K.crv
lh.inflated.H		 lh.white.preaparc.H	  rh.smoothwm.K1.crv
lh.inflated.K		 lh.white.preaparc.K	  rh.smoothwm.K2.crv
lh.inflated.nofix	 rh.area		  rh.smoothwm.S.crv
lh.jacobian_white	 rh.area.mid		  rh.smoothwm.nofix
lh.orig			 rh.area.pial		  rh.sphere
lh.orig.nofix		 rh.avg_curv		  rh.sphere.reg
lh.orig.premesh		 rh.curv		  rh.sulc
lh.pial			 rh.curv.pial		  rh.thickness
lh.pial.T1		 rh.defect_borders	  rh.volume
lh.qsphere.nofix	 rh.defect_chull	  rh.w-g.pct.mgh
lh.smoothwm		 rh.defect_labels	  rh.white
lh.smoothwm.BE.crv	 rh.defects.pointset	  rh.white.H
lh.smoothwm.C.crv	 rh.fsaverage.sphere.reg  rh.white.K
lh.smoothwm.FI.crv	 rh.inflated		  rh.white.preaparc
lh.smoothwm.H.crv	 rh.inflated.H		  rh.white.preaparc.H
lh.smoothwm.K.crv	 rh.inflated.K		  rh.white.preaparc.K

Results#

from ipyniivue import NiiVue

nv = NiiVue(crosshair_color=[0,1,0,1])
nv.load_volumes([{"url": "https://huggingface.co/datasets/neurodeskorg/neurodeskedu/resolve/main/data/examples/structural_imaging/freesurfer/orig_625f9583ffba.mgz"},
                  {"url": "https://huggingface.co/datasets/neurodeskorg/neurodeskedu/resolve/main/data/examples/structural_imaging/freesurfer/aseg_f53f2ed0597f.mgz"}])
nv

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: 2026-03-03T02:27:39.846409+00:00

Python implementation: CPython
Python version       : 3.13.11
IPython version      : 9.9.0

Compiler    : GCC 14.3.0
OS          : Linux
Release     : 5.15.0-170-generic
Machine     : x86_64
Processor   : x86_64
CPU cores   : 32
Architecture: 64bit

ipyniivue: 2.4.4