Installation and use of FreeSurfer and FSL (removal of skull from brain image + affine alignment of image and label at the same time) tutorial

FreeSurfer currently only supports Linux systems and Mac OS. The system I use is Ubuntu 16.0.4. The installation of FreeSurfer takes less time, but the processing time is longer. It may take several hours or even a day. This depends on the performance of the machine, but it does not seem to be too much with the GPU. relationship. The general installation steps are given below first, and then the detailed installation steps are given separately.

First, give a few articles I refer to:

  1. FreeSurfer-Introduction
  2. FSL/FreeSurfer installation tutorial
  3. FreeSurfer User Manual
  4. Use Voxelmorph to register IXI: Skull removal and affine alignment of data preprocessing

The second reference article also installs FSL. I am not very clear about what this FSL is. According to my installation and use results, there is no need to install it separately. FSL should be integrated in FreeSurfer. (2020.09.15 update, added FSL installation and usage instructions in the fourth part of the article)

One, FreeSurfer total installation steps

wget https://surfer.nmr.mgh.harvard.edu/pub/dist/freesurfer/7.1.0/freesurfer-linux-centos6_x86_64-7.1.0.tar.gz #下载安装包
tar -zxv -f freesurfer-linux-centos6_x86_64-7.1.0.tar.gz #解压缩
# 注册,得license.txt,并将license.txt拷贝到./freesurfer目录下
sudo chmod -R 777 ./freesurfer #改变freesurfer的权限
vi ~/.bashrc
# 在~/.bashrc文件中添加以下两行
export FREESURFER_HOME=/home/syzhou/zuzhiang/freesurfer
source $FREESURFER_HOME/SetUpFreeSurfer.sh
source ~/.bashrc
sudo apt-get install tcsh #安装tcsh,类似与bash,不安装运行的时候会报错

Step-by-step introduction to FreeSurfer installation

1. Download the FreeSurfer compressed package

First go to the official website to download the corresponding installation package. The download interface is as shown in the figure below. It is optimistic whether to download under Linux or MacOS. Although the installation package under Linux is written in CentOS, it also supports Ubuntu. Right-click on the red box and select "Copy Download Connection", then select the corresponding path under the Linux system, and use the command to wget https://surfer.nmr.mgh.harvard.edu/pub/dist/freesurfer/7.1.0/freesurfer-linux-centos6_x86_64-7.1.0.tar.gzdownload the installation package.
Insert picture description here

2. Installation

Although it is installation, in fact, you only need to decompress it. Use the command tar -zxv -f freesurfer-linux-centos6_x86_64-7.1.0.tar.gzto decompress. If you download a version that is not the same as mine, you need to change the file name of the compressed file, the same below. After decompression, a freesurferfolder named will be generated in the current directory .

3. Registration

Go to the official registration website to register. After a while, you will receive an email with license.txta file named in the attachment . Download it and put freesurferit under the folder. The registration page is shown in the figure below.
Insert picture description here

4. Change the permissions of the freesurfer folder

Use commands to sudo chmod -R 777 ./freesurferchange the folder permissions, the folder path may need to be adjusted accordingly.

5. Add environment variables

Use the vi ~/.bashrccommand to open the environment variable file and ~/.bashrcadd the following two lines to the file:

export FREESURFER_HOME=/home/syzhou/zuzhiang/freesurfer
source $FREESURFER_HOME/SetUpFreeSurfer.sh

And use the source ~/.bashrccommand to make the changed environment variable take effect immediately. Then the information shown in the figure below will be displayed.
Insert picture description here

6. Install tcsh

Use the sudo apt-get install tcshcommand to install tcsh, tcsh is similar to bash, if it is not installed, an error will be reported when running.

7. Testing

Enter the recon-al --helpcommand in the command line . If the help message is displayed, the installation is successful. If the prompt command does not exist or only the path information is displayed, it indicates that there is a problem with the installation. The former can be solved by reinstalling, and the latter should be the sixth step of the installation. problem.

Three, the use of FreeSurfer

Here, FreeSurfer is mainly used to remove the skull from the brain image. The referenced article is the fourth one mentioned at the beginning.

!!!

It is important to note that every time you enter the terminal to use FreeSurfer, you need to enter the command:

export FREESURFER_HOME=/home/syzhou/zuzhiang/freesurfer
source $FREESURFER_HOME/SetUpFreeSurfer.sh

Otherwise, it cannot be used normally.

!!!

The following is the use of FreeSurfer to perform operations such as skull removal and affine alignment on images in batches. Wherein the path/a/b/cvalues of the variables needs to be changed according to the actual situation. In line 19 of the code, if the format name of the image file is different, the length of the string to be retained is also different, and only the file name (excluding the extension) is required.

cmdAmong the commands corresponding to the variables a/b/care the environment variable configuration commands, recon-allthe skull removal commands, mri_convertand the format conversion from mgz to nii.gz, just for the convenience of viewing, mri_convert --apply_transformand the affine alignment operation.

import os
import glob

path = r"/home/syzhou/zuzhiang/Dataset/MGH10/Heads"
# 读取目录下的.img文件
images = glob.glob(os.path.join(path,"*.img"))
# 下面为freesurfer的环境配置命令
a = "export FREESURFER_HOME=/home/syzhou/zuzhiang/freesurfer;"
b = "source $FREESURFER_HOME/SetUpFreeSurfer.sh;"
# 数据所在的目录
c = "export SUBJECTS_DIR="+path+";"

#images=['/home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127.img']
for image in images:
    # 将文件路径和文件名分离
    filename = os.path.split(image)[1] # 将路径名和文件名分开
    filename = os.path.splitext(filename)[0] #将文件名和扩展名分开,如果为.nii.gz,则认为扩展名是.gz
    # freesurfer环境配置、颅骨去除、未仿射对齐mpz转nii、仿射对齐、仿射对齐mpz转nii.gz格式
    #recon-all是颅骨去除的命令
    # mri_convert是进行格式转换,从mgz转到nii.gz,只是为了方便查看
    # --apply_transform:仿射对齐操作
    # 转格式
    filename=filename[:] #根据扩展名的不同,这里需要做更改,只保留文件名即可
    cur_path=os.path.join(path,filename) 
    print("file name: ",cur_path)
    cmd = a + b + c \
          + "recon-all -parallel -i " + image + " -autorecon1 -subjid " + cur_path + "&&" \
          + "mri_convert " +  cur_path + "/mri/brainmask.mgz " +cur_path + "/mri/"+filename+".nii.gz;"\
          + "mri_convert " + cur_path + "/mri/brainmask.mgz --apply_transform " + cur_path + "/mri/transforms/talairach.xfm -o " + cur_path + "/mri/brainmask_affine.mgz&&" \
          + "mri_convert " + cur_path + "/mri/brainmask_affine.mgz " + cur_path + "/mri/"+filename+"_affine.nii.gz;"
    #print("cmd:\n",cmd)
    os.system(cmd)

To see more intuitive cmdcorresponding instructions listed below when the image file 1127.img, the cmdcorresponding content, for easy viewing I joined the wrap.

 export FREESURFER_HOME=/home/syzhou/zuzhiang/freesurfer;
 
 source $FREESURFER_HOME/SetUpFreeSurfer.sh;
 
 export SUBJECTS_DIR=/home/syzhou/zuzhiang/Dataset/MGH10/Heads;
 
recon-all -i /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127.img -autorecon1 -subjid 1127&&

mri_convert /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127/mri/brainmask.mgz /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127/mri/brainmask.nii.gz;

mri_convert /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127/mri/brainmask.mgz --apply_transform /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127/mri/transforms/talairach.xfm -o /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127/mri/brainmask_affine.mgz&&

mri_convert /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127/mri/brainmask_affine.mgz /home/syzhou/zuzhiang/Dataset/MGH10/Heads/1127/mri/brainmask_affine.nii.gz;

Assuming the image file name is 1127.img, a folder named after the image file name will be generated in the directory corresponding to path, and the processing result will be stored in it. The following figure is the g6.imgcorresponding output folder, the structure inside is as shown in the figure below, we want to get the picture mriunder the folder.
Insert picture description here

mriThe files in the folder are as shown in the figure below, where brainmask.nii.gzthe image after removing the skull is the image after brainmask_affine.nii.gzremoving the skull and affine alignment.
Insert picture description here

The following two figures are the results before and after processing.
Insert picture description here
Insert picture description here
However, it can be found that the above approach has two problems. One is that the image and its corresponding label cannot be affine aligned at the same time, and the other is that the image has moved after the skull is removed, which will cause obstacles to subsequent operations. See the fourth and fifth parts for the solutions to these two problems.

Fourth, the installation and use of FSL

The reason why FSL is used is because when affine alignment is performed on the image, the same affine alignment operation cannot be performed on the labels corresponding to the image at the same time, and FSL is possible. The installation and use of FSL is also carried out under the Ubuntu system.

1. FSL installation

# 下载FSL安装包,这里下载的是压缩版
wget http://fsl.fmrib.ox.ac.uk/fsldownloads/fsl-5.0.9-centos6_64.tar.gz
# 新建一个文件夹作为FSL的安装路径,并改变其权限
sudo chmod -R 777 文件夹名
# 将下载好的安装包解压到该文件夹下
tar -zxv -f fsl-5.0.9-centos6_64.tar.gz
# 配置环境变量
vi ~/.bashrc
# 在~/.bashrc文件中追加以下三行
export FSLDIR=FSL文件夹的绝对路径
export PATH=$PATH:$FSLDIR/bin
source $FSLDIR/etc/fslconf/fsl.sh
# 使环境变量立即生效
source ~/.bashrc
# 查看是否安装成功,如果出现版本信息则说明安装成功
flirt -version

2. Use of FSL

It is said that FSL has an interface, but the server on my side is inconvenient to use the monitor, so I use the command line. Here I only use the affine alignment function of FSL and the function of applying the existing affine matrix to other images, so only these two commands are introduced. See the official website for details .

Interpolation :Tri-Linear; Nearest Neighbour

Linearly register two images:

flirt -in m_img.nii.gz -ref f_img.nii.gz -out m2f_img.nii.gz -omat m2f.mat -dof 12

Its function is to align the input image to the reference image in the manner specified by the dof parameter, and save it as the image specified by the out parameter and the transformation specified by the omat parameter.

Wherein -infollowed by the name of an input image; -reffollowed by the name of the reference image; -outfollowed by the name of the output image; -omatfollowed by the name of the transform matrix, .matthe suffix is not mandatory, but may be other; -dofis an abbreviation Degrees of Freedom, i.e. free Degree, for 3D to 3D registration, 12 is affine transformation, 9 is traditional transformation, 7 is global rescaling transformation, 6 is rigid body transformation, for 2D to 2D registration, only 3 represents rigid body change This kind.

Apply the saved transformation to another image:

flirt -in m_label.nii.gz -ref f_img.nii.gz -out m2f_label.nii.gz -init m2f.mat -applyxfm -interp nearestneighbour

The -initparameter is the saved transformation; it -applyxfmmeans that the saved transformation is applied to the new image; it -interp nearestneighbourmeans that the nearest neighbor interpolation is used. The nearest neighbor interpolation can keep the label category consistent with the original one. The default is linear interpolation.

五、FreeSurfer+FSL

(2020.09.23 update)

In this part, I want to combine FreeSurfer's skull removal and FSL's affine alignment to achieve both the removal of the skull and the affine alignment of the image and the label. However, it is mentioned that the recon-allimage will move when the command is used for skull removal. So I changed a command and used a mri_watershedcommand. This command is recon-allfaster than the command.

import os
import glob


# 使用FreeSurfer对图像进行颅骨剥离
print("FreeSurfer start......\n")
# 图像坐在的目录
#------------------------图像路径需更改------------------------#
path ="/home/syzhou/zuzhiang/Dataset/MGH10/Heads"
# 读取目录下的.img文件列表,*.img表示该目录下所有以.img结尾的文件
#-----------------------图像后缀名需更改--- -------------------#
files = glob.glob(os.path.join(path,"*.img"))
# 输出路径
#------------------------输出路径需更改------------------------#
out_path="/home/syzhou/zuzhiang/MIP/FSL_img/MGH10_results"
print("number: ",len(files))
# 下面为freesurfer的环境配置命令
a = "export FREESURFER_HOME=/home/syzhou/zuzhiang/freesurfer;"
b = "source $FREESURFER_HOME/SetUpFreeSurfer.sh;"
# 数据所在的目录
c = "export SUBJECTS_DIR="+path+";"

for file in files:
    # 将文件路径和文件名分离
    filename = os.path.split(file)[1] # 将路径名和文件名分开
    filename = filename.split(".")[0] # 去除所有扩展名   
    #recon-all是颅骨去除的命令
    # mri_convert是进行格式转换,从mgz转到nii.gz,只是为了方便查看
    filename=filename[:] #根据扩展名的不同,这里需要做更改,只保留文件名即可
    # 当前输出文件路径,以.nii.gz格式保存
    cur_out_path=os.path.join(out_path,filename+".nii.gz")
    print("file name: ",file)
    cmd = a + b + c + "mri_watershed "+file+" "+ cur_out_path
    #print(cmd,"\n")
    os.system(cmd)


# 使用FSL对图像和对应的label进行仿射对齐
print("FSL start......\n")
# fixed图像的路径
#---------------去除头骨后的fixed图像名需更改-------------------#
f_path= os.path.join(out_path,"g1.nii.gz")
# moving图像的路径
m_path=out_path
# label的路径
#-----------------------label路径需更改-----------------------#
label_path="/home/syzhou/zuzhiang/Dataset/MGH10/Atlases"
files=glob.glob(os.path.join(m_path,"*.nii.gz"))
print("number: ",len(files))
for file in files:
    print("file: ",file)
    # 根据图像名找到对应的label名
    filename=os.path.split(file)[1]
    filename = filename.split(".")[0] # 去除所有扩展名
    #---------------------label后缀名需更改--------------------#
    label=os.path.join(label_path,filename+".img")
    # 下面分别是输出图像名/转换矩阵名/label名,
    out_img=os.path.join(out_path,filename+"_img.nii.gz")
    out_mat=os.path.join(out_path,filename+".mat")
    out_label=os.path.join(out_path,filename+"_label.nii.gz")
    # 如果当前文件和fixed图像一样则只将对应label格式转换为.nii.gz
    if f_path==file:
        convert="mri_convert " + label +" " + out_label
        os.system(convert)
        print("continue.........")
        continue    
    # 将moving图像对齐到fixed图像
    flirt_img="flirt -in "+file+ " -ref "+f_path+" -out "+out_img+" -omat "+out_mat+ " -dof 12"
    # 将上一步的仿射变换矩阵作用在图像对应的label上
    flirt_label="flirt -in "+label+" -ref "+f_path+" -out "+out_label+" -init "+out_mat+" -applyxfm -interp nearestneighbour"
    #print(flirt_img,"\n")
    #print(flirt_label,"\n")
    os.system(flirt_img)
    os.system(flirt_label)

print("\n\nEnd")

Guess you like

Origin blog.csdn.net/zuzhiang/article/details/107562854