Skip to content
Santtu Söderholm edited this page May 16, 2024 · 13 revisions

This document cover the necessary step of installing and setting up the FreeSurfer and provides instructions for preparing and importing MRI data into Zeffiro Interface. The process involves following steps:

  1. Perform a reconstruction of the cortical surfaces
  2. Convert files from .mgz to .asc format
  3. Import the reconstructed data into Zeffiro Interface

File Formats

Image data

DICOM (Digital Imaging and Communications in Medicine) is a widely used file format for medical imaging, including MRI. Every single file stands for a single layer image, so there are typically a large number of such files for a single session.

NII or NIFTI (Neuroimaging Informatics Technology Initiative) is another common file format for medical imaging, including MRI. NIFTI aggregates images from all layers in one file and takes less space on a hard drive.

Reconstructed data

MGZ: FreeSurfer-specific format containing both image data and metadata, optimized for use with FreeSurfer but not compatible with other software.

ASC: Simple ASCII text format, which is used for importing data into Zeffiro.

Installing FreeSurfer

FreeSurfer is an open-source software package for analyzing and visualizing MRI data of the brain. It provides a suite of tools for automatically segmenting brain regions, creating surface models, and analyzing brain structure and function.

We will need this tool to convert the subject MRI images to a set of .mgz files by performing the cortical reconstruction using available command line utilities.

You should install FreeSurfer using the instructions provided on their website. Alternatively, you may use the official Docker Image.

⚠️ Working on Windows is not guaranteed
Note that installing FreeSurfer on computer with Windows OS will require using Windows Subsystem for Linux (WSL) which goes out of the scope of this article and was never tested by the developers of Zeffiro.

After the installation is complete you will need to set the $FREESURFER_HOME environment variable in your .bashrc file, or via any other suitable means if you use a shell other than Bash ( run echo $SHELL to find it out).

Also, that script relies on matlab executable file, so its parent directory should also be added to $PATH

echo 'export PATH="$PATH:/Applications/MATLAB_R2021b.app/bin/"' >> ~/.zshrc
echo 'export FREESURFER_HOME=/Applications/freesurfer/7.3.2/' >> ~/.zshrc
echo 'export FS_FREESURFERENV_NO_OUTPUT=true' >> ~/.zshrc
echo 'source $FREESURFER_HOME/SetUpFreeSurfer.sh' >> ~/.zshrc

⚠️ Before running command above, make sure the paths are correct and lead to the installed version of the apps

You can validate if the installation was successful by opening a new terminal session and running command

recon-all --version; matlab -help | head

The expected output will be similar to the following

freesurfer-darwin-macOS-7.3.2-20220804-6354275

    Usage:  matlab [-h|-help] | [-n | -e]
                   [v=variant]
                   [-c licensefile] [-display Xdisplay | -nodisplay]
                   [--noFigureWindows]
                   [-nosplash] [-debug]
                   [-softwareopengl | -nosoftwareopengl]
                   [-desktop | -nodesktop | -nojvm]
                   [-batch MATLAB_command | -r MATLAB_command]
                   [-sd folder | -useStartupFolderPref]

After the FreeSurfer is successfully installed you will need to get a license file by filling the form on FreeSurfer registration page. They will send you a license.txt file that should be renamed to .license and placed into the application's directory.

Reconstruction

The module utilities.fs2zef in the Zeffiro Interface root folder contains the Matlab function run, which can be used to generate a segmentation with the aid of the FreeSurfer software suit.

This function will perform steps 1 and 2 from and convert given files from nii or dcm format to mgz and then to asc.

Running the script

ℹ️ It requires Matlab version > r2019a.

First navigate to the Zeffiro Interface root folder and invoke function on the Matlab command line:

utilities.fs2zef.run(segmentation_output_folder, recon_all_output_folder [,recon_all_input_files])

where

  • segmentation_output_folder is the (already existing) folder you want the segmentation ASCII files to end up into,
  • recon_all_output_folder is the folder that contains (or is to contain) the output of the FreeSurfer program recon-all.
  • recon_all_input_files is an optional parameter with path to recon-all input files, either NIFTI (.nii) or DICOM (.dcm) files. If the third argument is provided it will run the recon-all under the hood to perform the 1st step of the pipeline. If not provided, the function will expect to find the reconstructed mgz files in the recon_all_output_folder folder. This would mean that the step 1 (the reconstruction) was already done by running recon-all manually.

Alternatively, one might want to run the segmentation generation via a regular terminal, external to Matlab. This might happen when connecting to a remote workstation via SSH, for example. In this case, once again navigate to the Zeffiro Interface root folder and type

matlab -nodisplay -nosplash -nodesktop -batch 'utilities.fs2zef.run("/path/to/segmentation_output_folder", "/path/to/recon_all_output_folder" [,"/path/to/recon_all_input_files"])' &> fs2zef.log &

See the difference between single and double quotation marks ' and ". This will run the job in the background, and writes the output of the program into the file fs2zef.log in the folder that the command was invoked from.

To monitor the recon-all logs by examining the /path/to/recon_all_output_folder/scripts/recon-all.log file, for example by using tail -f.

Notes

  • You might also want to run a converter task in a background. The nohup command (short for "no hangup") allows you to run a process in the background and prevents it from being terminated when you close your terminal or log out.

  • The reconstruction takes a lot of time to reconstruct a single model from T1 head MRI images

    • 6-8 hours on a laptop with Intel Core i7-8569U @2.80GHz
    • 3-5 hours on a desktop with Ryzen R7 5700X @4.65Ghz

    During conversion it utilizes a single CPU core. Thus you can significantly speed up the process by converting multiple subjects simultaneously. The Step-wise Directives section provides a table with an overview on the time needed to perform each step of reconstruction.

  • If you wish to keep the job running after logging out from the SSH session or closing your terminal, which is especially useful if one has chosen to run recon-all, you should disown it:

    disown %fs2zef_job_number

    where fs2zef_job_number can be discovered by typing

    jobs

    into the terminal. After disowning, the job should have disappeared from the list of jobs.

  • To see help for fs2zef, type

    help utilities.fs2zef.run

    or

    doc utilities.fs2zef.run

    on the Matlab command line.

Full pipeline example

###### DEFINE YOUR PATHS HERE ######

# Zeffiro Interface root folder
cd ~/Documents/MATLAB/zeffiro_interface

# Subject MRI data
export INPUT_DATA=~/Downloads/IXI-T1/IXI012-HH-1211-T1.nii.gz

# output directory
export SEGMENTATION_OUTPUT=~/segmentation

# Name or id or a subject
export SUBJECT_NAME=Anonymous # name or id or a subject


####### DO NOT CHANGE THE CODE BELOW ###### 

mkdir -p ${SEGMENTATION_OUTPUT}/${SUBJECT_NAME}
mkdir -p $SUBJECTS_DIR

nohup matlab -nodisplay -nosplash -nodesktop -batch 'utilities.fs2zef.run(fullfile(getenv("SEGMENTATION_OUTPUT"), getenv("SUBJECT_NAME")), fullfile(getenv("SUBJECTS_DIR"), getenv("SUBJECT_NAME")), getenv("INPUT_DATA"))' &

# ctrl+c to stop reading logs
sleep 10 && cat nohup.out && tail -f ${SUBJECTS_DIR}/${SUBJECT_NAME}/scripts/recon-all.log

# After the reconstruction is done check also the `nohup.out` file
tail -f ./nohup.out

Copy-pasting these lines into a terminal may cause several zsh: command not found: # errors that may be safely ignored.

Importing into Zeffiro

When the reconstruction and conversion is done, the ~/segmentation/subject_name will have a segmentation import metadata file import_segmentation.zef, which is to be given to Zeffiro Interface to import the segmentation data.

The segmentation is imported by going into Zeffiro Interface → Menu tool → Import → Import data to a new project, and navigating to the import_segmentation.zef file in the segmentation_output_folder of fs2zef. The segmentation will then be imported to Zeffiro.

import_segmentation.zef format

The import_segmentation.zef allows one to import a surface segmentation consisting of a set of ASCII files. For importing, this file should be placed in the folder containing the files. The files can be either DAT files containing either points or triangles, or ASC files exported from the [FreeSurfer].

In the former case, the folder must contain two files per each triangular tissue surface mesh (filename_points.dat and filename_triangles.dat), whereas in the latter case a single file is needed (filename.asc) per a mesh. Each line in the list below corresponds to a single mesh. Each compartment in the segmentation is described by one or more meshes which will be automatically merged in the import process. The compartment identifiers are the following:

sensor_points, sensor_directions, white_matter, grey_matter, csf, skull, skin, detail_1, detail_2, …, detail_22.

Of these, a mesh for each tissue compartment is specified by a single comma-separated line of the following form:

filename, compartment_name, scaling, sigma, priority, activity, name, invert, extension

Here, the filename appears without any extensions; compartment_name is as in the list above, scaling, sigma and priority parameters are as in ZI's segmentation window with 0 corresponding to the default value; activity is a number describing the activity of the compartment (0 = inactive, 1 = constrained activity, 2 = unconstrained activity, or 3 = inner cortex [for white_matter only]); name is the compartment name as it appears in ZI; invert is for inverting an inward-pointing surface normal (0=not inverted, 1=inverted); and extension is either .asc or .dat for FreeSurfer and other meshes, respectively.

In the special case of sensor_points and sensor_directions, it is only possible to use the DAT format. Each one of these is imported via a single file (filename.dat), and the line for importing is of the form

filename, compartment name, scaling, x-translation, y-translation, z-translation, xy-rotation, yz-rotation, zx-rotation

The scaling, translating and rotation parameters are as they appear in ZI's segmentation tool, and selecting 0 for them, means that the default value will be used. Each compartment-specific parameter can be imported only once. In case there are multiple definitions in the list for a single compartment, only the first one counts.

Troubleshooting

Useful links

  1. FreeSurver7 download page
  2. How to install FreeSurfer on Mac Demo video
  3. FreeSurfer registration
  4. What is .bashrc file in Linux?
  5. recon-all documentation
  6. Tutorial: Converting DICOM to NIFTI (with video)