【FSL】FSLを用いたVoxel-Based Morphometry: VBM



1. 目的
2. VBMとは
2.1. 3D-T1WIの準備
2.2. fslvbm_1_bet: 3D-T1WIの脳頭蓋除去
2.3. fslvbm_2_template: 被験者の脳から灰白質テンプレート画像を生成
2.4. fslvbm_3_proc: すべての被験者の灰白質を灰白質テンプレート画像に位置合わせし、ボクセルをモジュレーション後、平滑化
2.5. randomise:GLMと並べ替え検定(permutation test)
3. おまけ


1. 目的

  • FSLを用いたVoxel-Based Morphometry: VBM

2. VBMとは

Voxel-Based Morphometry(VBM)は、脳構造解析手法の一つであり、特に脳容積を対象に解析する。

VBMは、古典的なマニュアルの脳容積計測とは異なり、自動処理によって全脳を客観的に評価することができ、現在では脳科学の分野において幅広く用いられている。

VBM解析では、次のような処理をする。

  1. 3D-T1WIの準備
  2. fslvbm_1_bet: 3D-T1WIの脳頭蓋除去
  3. fslvbm_2_template: 被験者の脳から灰白質テンプレート画像を生成
  4. fslvbm_3_proc: すべての被験者の灰白質を灰白質テンプレート画像に位置合わせし、ボクセルをモジュレーション後、平滑化
  5. randomise:GLMと並べ替え検定(permutation test)

2.1. 1. 3D-T1WIの準備

各被験者の3D-T1WIを準備する。

ここでは、健常者10名(ID: Con0001~Con0010)と患者10名(ID: Pat0001~Pat0010)いることを想定する。

.
├── Con0001_T1w.nii.gz
├── Con0002_T1w.nii.gz
├── Con0003_T1w.nii.gz
...
└── Pat0010_T1w.nii.gz

2.2. 2. fslvbm_1_bet: 3D-T1WIの脳頭蓋除去

ファイルの準備ができたら、fslvbm_1_betコマンドを実行して脳頭蓋除去をする。3D-T1WIに首を含まない場合、-bオプションを指定し、首を含む場合は-Nオプションを指定する。

ここでは、3D-T1WIに首を含んでいたとして、-Nオプションを指定する。

fslvbm_1_bet -N  # 首を含む場合
# fslvbm_1_bet -b  # 首を含まない場合

処理が完了すると「strucフォルダ」が生成され、その中に頭蓋除去後の画像が保存される。頭蓋除去後の画像は「*_brain.nii.gz」というファイル名で保存される。頭蓋除去前後の画像一覧をみるには、「struc/slicesdir/index.html」を開く。下地が頭蓋除去前の画像であり、赤い線が頭蓋除去後の画像である。

2.3. 3. fslvbm_2_template: 被験者の脳から灰白質テンプレート画像を生成

次に、脳の解剖学的標準化で用いるターゲット画像(標準脳)を、頭蓋除去済みの被験者脳から生成する。

まず最初に、標準脳を生成するために用いる被験者の脳画像リスト(template_list)を作成する。このとき、バイアスがかからないように健常者と患者の人数が同じになるようにリストを作る。

ここでは、健常者10名(ID: Con0001~Con0010)と患者10名(ID: Pat0001~Pat0010)の合計20名を「template_list」に記載した。

cat template_list
Con0001_T1w.nii.gz
Con0001_T1w.nii.gz
Con0001_T1w.nii.gz
...
Pat0010_T1w.nii.gz

template_listは、3D-T1WI(*_T1w.nii.gz)と同じ階層に配置する。

.
├── template_list   # ここに配置
├── Con0001_T1w.nii.gz
├── Con0002_T1w.nii.gz
├── Con0003_T1w.nii.gz
...
└── Pat0010_T1w.nii.gz

標準脳を生成するために用いる被験者の脳画像リスト(template_list)が準備できたら、頭蓋除去済みの脳画像を、灰白質・白質・脳脊髄液にセグメントする。次に、全ての被験者の灰白質(*_struc_GM.nii.gz)を元々ある灰白質標準脳(ICBM-152)にアフィン変換で位置合わせし、平均化する。このようにして得られた平均灰白質画像を、x軸に対して反転し再度平均化して、左右対称の平均灰白質画像(template_GM_init.nii.gz)を生成する。既に作成した「template_list」に記載されている灰白質画像を、先ほど作成した平均灰白質画像に位置合わせをし、平均化、さらに左右反転後に再度平均化する。最後に、元々ある灰白質標準脳(ICBM-152)に非線形位置合わせをし、2x2x2 mm^3の灰白質テンプレートを標準空間に生成する。

fslvbm_2_templateコマンドにはオプションがあり、各被験者の灰白質画像を元々ある灰白質標準脳(ICBM-152)に位置合わせする際に、アフィン変換を用いる場合は-aオプションを、非線形変換を用いる場合は-nオプションを指定する。

ここでは、fslvbm_2_template-aオプションを指定して実行する。

fslvbm_2_template -a  # Affine registration
# fslvbm_2_template -n  # non-linear registration

処理が完了するとstrucフォルダに灰白質テンプレート(template_GM_4D.nii.gz)が生成される。

2.4. fslvbm_3_proc: すべての被験者の灰白質を灰白質テンプレート画像に位置合わせし、ボクセルをモジュレーション後、平滑化

非線形変換を用いた位置合わせで、各被験者の灰白質画像を作成した灰白質テンプレート(template_GM_4D.nii.gz)に合わせ、statsフォルダに全被験者の灰白質4D画像を作る(GM_merg.nii.gz)。この時、被験者ごとの灰白質容積の違いを反映できるよう、非線形変換の際に収縮・拡大された度合いに応じて、灰白質画像のボクセル値を補正(モジュレーション)する。実際には、warp fieldのヤコビアンを灰白質画像の各ボクセルにかけ合わせる。その後、モジュレーションされた画像(GM_mod_merg.nii.gz)はσ=2, 3, 4mm (およそFWHM=2×2.3=4.6mmからFWHM=9mm)のガウシアンフィルタで平滑化する(GM_mod_merg_s[2,3,4].nii.gz)。

fslvbm_3_proc

以下は、モジュレーションした灰白質画像(GM_mod_merg.nii.gz)とσ=3mmのガウシアンフィルタで平滑化した灰白質画像(GM_mod_merg_s3.nii.gz)である。

2.5. randomise:GLMと並べ替え検定(permutation test)

ガウシアンフィルタで平滑化した灰白質画像を用いて、健常群と患者群の群間比較をする。

まず、GLMのデザインマトリックス(計画行列)とコントラストを設定する。

今回は、健常者10名(ID: Con0001~Con0010)と患者10名(ID: Pat0001~Pat0010)のデータがある。すべての被験者の3D-T1WIをlsコマンドでみると、先に健常者10名の3D-T1WI、次に患者10名の3D-T1WIが並んでいることが分かる。

ls |grep nii
Con0001_T1w.nii.gz
Con0002_T1w.nii.gz
Con0003_T1w.nii.gz
...
Pat0010_T1w.nii.gz

次に、GLMのデザインマトリックス(計画行列)とコントラストを決める設定ファイルを生成する。design_ttest2 <出力ファイル> <健常者数> <患者数>でコマンドを実行。

design_ttest2 stats/design 10 10

statsフォルダに、デザインマトリックス(design.mat)とコントラスト(design.con)が生成される。

デザインマトリックス(design.mat)の中身を確認。

/Matrixの一列目は健常者データであるかどうか、二列目は患者データであるかを0, 1で表している。行の順番は、被験者ファイルの順番(昇順)に対応する。したがって、これらは対応があるようにしておかなければならない。

cat stats/design.mat
/NumWaves 2
/NumPoints 20
/PPheights 1 1
/Matrix
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1

コントラスト(design.con)の中身を確認してみる。

/Matrix一列目は健常者の偏回帰係数、二列目は患者の偏回帰係数に対するもので、行は別々のコントラストである。この場合、一行目は健常者>患者の検定、二行目は健常者<患者の検定に相当する。

cat stats/design.con
/NumWaves 2
/NumContrasts 2
/PPheights 1 1
/Matrix
1 -1
-1 1

デザインマトリックス(計画行列)とコントラストの確認ができたら、randomiseコマンド使ってGLMと並べ替え検定(permutation test)を実行する。

randomiseコマンドの各オプションは、次の通り。

  • -i:入力画像
  • -m:マスク画像
  • -o :出力画像
  • -o :デザインマトリックス
  • -o :デザインコントラスト
  • -n:並べ替え検定の数
  • –T2:2D最適化を用いたTFCE
  • -x:voxel-wiseのcorrected P値マップ
  • –uncorrp:un-corrected P値マップ
  • -R:統計値マップ
fsleyes $FSLDIR/data/standard/MNI152_T1_2mm \
    stats/fslvbm_tfce_corrp_tstat1 \
    -cm Red-Yellow -dr 0.95,1

次のようなファイルが、生成される。

TFCEを用いた”健常群>患者群”の検定で、FWE補正をされたP値マップ(fslvbm_tfce_corrp_tstat1.nii.gz)を確認する。ここで、得られたP値マップは1-P値のマップであることに注意する。つまり、P<.05を有意とするのであれば、P値マップで0.95-1.00の値を見ればよい

fsleyes $FSLDIR/data/standard/MNI152_T1_2mm \
                 stats/fslvbm_tfce_corrp_tstat1 -cm Red-Yellow

3. おまけ

検定数が多い場合、有意差があったかどうかをすべて確認するのは大変である。そこで、一目で有意差があるかどうかを判断できるように、各検定ごとのP値マップの最大値を自動計測し、テキスト(corrected_P_report.txt)としてまとめる。

for PMAP in $(ls stats/ | grep tfce_corrp); do
    PMAX=$(fslstats stats/${PMAP} -R | cut -d " " -f2)
    echo ${PMAP} >>stats/tmp1.txt
    echo ${PMAX} >>stats/tmp2.txt
done
paste stats/tmp* >stats/tmp_corrected_P_report.txt
echo -e "$(cat stats/tmp_corrected_P_report.txt)\n\n\n$(cat stats/tmp_corrected_P_report.txt | sort -r -n -k 2)" \
    >stats/corrected_P_report.txt
rm stats/tmp*

上のコマンドを実行すると、statsフォルダに各検定とそのP値マップの最大値が記された「corrected_P_report.txt」が出力される。

検定結果を、ファイル名でソート(上段)したものと、P値でソートしたもの(下段)に分けて保存している。

cat stats/corrected_P_report.txt
fslvbm_tfce_corrp_tstat1.nii.gz 0.982391
fslvbm_tfce_corrp_tstat2.nii.gz 0.993181


fslvbm_tfce_corrp_tstat2.nii.gz 0.993181
fslvbm_tfce_corrp_tstat1.nii.gz 0.982391

【FSL】FSLを用いた拡散テンソルイメージング: DTI


1. 目的
2. コマンド
3. 使用例


1. 目的

  • FSLを用いた拡散テンソルイメージング: DTI

2. コマンド

FSLを用いて、拡散テンソルイメージング(DTI)をするには、dtifitコマンドを用いる。

dtifitのヘルプは、次の通り。

クリックして展開
Usage: 
dtifit -k <filename>
 dtifit --verbose


Compulsory arguments (You MUST set one or more of):
	-k,--data	dti data file
	-o,--out	Output basename
	-m,--mask	Bet binary mask file
	-r,--bvecs	b vectors file
	-b,--bvals	b values file

Optional arguments (You may optionally specify one or more of):
	-V,--verbose	switch on diagnostic messages
	-h,--help	display this message
	--cni	Input confound regressors
	--sse	Output sum of squared errors
	-w,--wls	Fit the tensor with weighted least squares
	--kurt	Output mean kurtosis map (for multi-shell data)
	--kurtdir	Output  parallel/perpendicular kurtosis maps (for multi-shell data)
	--littlebit	Only process small area of brain
	--save_tensor	Save the elements of the tensor
	-z,--zmin	min z
	-Z,--zmax	max z
	-y,--ymin	min y
	-Y,--ymax	max y
	-x,--xmin	min x
	-X,--xmax	max x
	--gradnonlin	Gradient Nonlinearity Tensor file

基本的な使い方は、以下の通り。

dtifit -k <DWI images> -o <OUTPUT> -m <MASK> -r <b-vectors file> -b <b-values file>

3. 使用例

まず、次のファイルを用意する。

.
├── DWI.nii.gz  # 拡散MRI
├── DWI_mask.nii.gz  # 拡散MRIのマスク画像
├── bvals  # b-values
└── bvecs  # b-vectors

ファイルの用意ができたら、dtifitを次のように実行する

dtifit -k DWI.nii.gz -o output -m DWI_mask.nii.gz -r bvecs -b bvals

処理が終わると次のファイルが生成される。

  • output_V1 – 1st eigenvector (固有ベクトル)
  • output_V2 – 2nd eigenvector
  • output_V3 – 3rd eigenvector
  • output_L1 – 1st eigenvalue (固有値)
  • output_L2 – 2nd eigenvalue
  • output_L3 – 3rd eigenvalue
  • output_MD – mean diffusivity
  • output_FA – fractional anisotropy (isotropic ~ 0; stick-like ~1)
  • output_MO – mode of the anisotropy (oblate ~ -1; isotropic ~ 0; prolate ~ 1)
  • output_S0 – raw T2 signal with no diffusion weighting

FA, MD, L1の画像は、以下。

【MRtrix】MRtrixを用いた5TT(five-tissue-type)画像の生成


1. 目的
2. コマンド
3. 使用例
3.1. FSLアルゴリズムを用いる場合
3.2. FreeSurferアルゴリズムを用いる場合
4. 結果


1. 目的

  • MRtrixを用いた5TT(five-tissue-type)画像の生成

2. コマンド

MRtrixの5ttgenを用いて、次の5つの組織(five-tissue-type: 5TT)画像を生成する。

  1. Cortical grey matter
  2. Sub-cortical grey matter
  3. White matter
  4. CSF
  5. Pathological tissue

5ttgenのヘルプは、次の通り。

クリックして展開
SYNOPSIS

     Generate a 5TT image suitable for ACT

USAGE

     5ttgen [ options ] algorithm ...

        algorithm    Select the algorithm to be used to complete the script operation;
                     additional details and options become available once an
                     algorithm is nominated. Options are: freesurfer, fsl, gif,
                     hsvs

DESCRIPTION

     5ttgen acts as a 'master' script for generating a five-tissue-type (5TT)
     segmented tissue image suitable for use in Anatomically-Constrained
     Tractography (ACT). A range of different algorithms are available for
     completing this task. When using this script, the name of the algorithm to
     be used must appear as the first argument on the command-line after
     '5ttgen'. The subsequent compulsory arguments and options available depend
     on the particular algorithm being invoked.

     Each algorithm available also has its own help page, including necessary
     references; e.g. to see the help page of the 'fsl' algorithm, type '5ttgen
     fsl'.

Options common to all 5ttgen algorithms

  -nocrop
     Do NOT crop the resulting 5TT image to reduce its size (keep the same
     dimensions as the input image)

  -sgm_amyg_hipp
     Represent the amygdalae and hippocampi as sub-cortical grey matter in the
     5TT image

Additional standard options for Python scripts

  -nocleanup
     do not delete intermediate files during script execution, and do not delete
     scratch directory at script completion.

  -scratch /path/to/scratch/
     manually specify the path in which to generate the scratch directory.

  -continue <ScratchDir> <LastFile>
     continue the script from a previous execution; must provide the scratch
     directory path, and the name of the last successfully-generated file.

Standard options

  -info
     display information messages.

  -quiet
     do not display information messages or progress status. Alternatively, this
     can be achieved by setting the MRTRIX_QUIET environment variable to a non-
     empty string.

  -debug
     display debugging messages.

  -force
     force overwrite of output files.

  -nthreads number
     use this number of threads in multi-threaded applications (set to 0 to
     disable multi-threading).

  -config key value  (multiple uses permitted)
     temporarily set the value of an MRtrix config file entry.

  -help
     display this information page and exit.

  -version
     display version information and exit.

基本的な使い方は、以下の通り。5ttgenのアルゴリズムは、freesurfer, fsl, gif, hsvsがあるが、ここではfreesurferとfslのアルゴリズムについて使い方を解説する。

5ttgen [アルゴリズム] <入力画像> <出力画像>

3. 使用例

3.1. FSLアルゴリズムを用いる場合

FSLアルゴリズムを用いる場合、3D-T1WI(T1w.nii.gz)が必要となる。また、オプションとして3D-T2WIも入力することができる。

5ttgen fsl T1w.nii.gz 5tt.nii.gz

3.2. FreeSurferアルゴリズムを用いる場合

FreeSurferアルゴリズムを用いる場合、Freesurferの生成ファイルであるaparc+aseg.mgz(asegとついたファイル)が必要となる。

FreeSurferの使い方は、こちらの記事を参考にするとよい。

aparc+aseg.mgzが準備できたら、以下のコマンドを実行する。

5ttgen freesurfer aparc+aseg.mgz 5tt.nii.gz

4. 結果

5ttgenで生成された画像は、5ボリュームデータであり、各ボリュームと対応する組織は次の通り。

  1. Cortical grey matter
  2. Sub-cortical grey matter
  3. White matter
  4. CSF
  5. Pathological tissue

以下に、FSLとFreeSurferのアルゴリズムを用いて5ttgenした結果(緑)を示す。

【FSL】FSLを用いた構造MRIと拡散MRIの位置合わせ ~Boundary-Based Registration: BBR~


1. 目的
2. Boundary-Based Registration (BBR)とは
3. コマンド
4. 目的使用例
4.1. 目的前準備
4.2. 目的Boundary-Based Registration: BBB


1. 目的

2. Boundary-Based Registration (BBR)とは

Doug Greve氏によって開発されたEPI画像(拡散MRIや機能的MRI)用の位置合わせツールで、EPI画像と構造MRI画像(例:T1WI)との位置合わせで、灰白質・白質境界(Boundary)を頼りに位置合わせをする。以下のウェブサイトに、詳細な説明と分かりやすい図がある。

FLIRT_BBR

3. コマンド

Boundary-Based Registration (BBR) に基づいた構造MRIと拡散MRIの位置合わせをFSLで実装するには、epi_regを用いる。

epi_regのヘルプは、以下の通り。

クリックして展開
Usage: epi_reg [options] --epi=<EPI image> --t1=<wholehead T1 image> --t1brain=<brain extracted T1 image> --out=<output name>
 
Optional arguments
  --fmap=<image>         : fieldmap image (in rad/s)
  --fmapmag=<image>      : fieldmap magnitude image - wholehead extracted
  --fmapmagbrain=<image> : fieldmap magnitude image - brain extracted
  --gdc=<image>          : Gradient-distortion corection warpfield
  --wmseg=<image>        : white matter segmentation of T1 image
  --echospacing=<val>    : Effective EPI echo spacing (sometimes called dwell time) - in seconds
  --pedir=<dir>          : phase encoding direction, dir = x/y/z/-x/-y/-z
  --weight=<image>       : weighting image (in T1 space)
  --nofmapreg            : do not perform registration of fmap to T1 (use if fmap already registered) 
  --noclean              : do not clean up intermediate files
  -v                     : verbose output
  -h                     : display this help message
 
e.g.:  epi_reg --epi=example_func --t1=struct --t1brain=struct_brain --out=epi2struct --fmap=fmap_rads --fmapmag=fmap_mag --fmapmagbrain=fmap_mag_brain --echospacing=0.0005 --pedir=-y
 
Note that if parallel acceleration is used in the EPI acquisition then the *effective* echo spacing is the actual echo spacing between acquired lines in k-space divided by the acceleration factor.

基本的な使い方は、以下の通り。

epi_reg --epi=<b=0画像(spin-echo EPI)> --t1=<頭蓋除去前の3D-T1WI> --t1brain=<頭蓋除去後の3D-T1WI> --echospacing=<echo spacing時間(sec)> --pedir=<位相エンコード方向> --out=<出力画像>

4. 目的使用例

4.1 目的前準備

次のファイルを準備する。

.
├── CSF_GM_WM_seg.nii.gz:FASTで作成したCSF, GM, WMのセグメント
├── DWI.nii.gz:拡散MRI画像(b≠0)
├── DWI_b0.nii.gz:拡散MRIのb=0画像(spin-echo EPI)
├── T1_skull_stripped.nii.gz:頭蓋除去後の3D-T1WI
└── T1w.nii.gz:頭蓋除去前の3D-T1WI

頭蓋除去とFASTを用いたCSF, GM, WMのセグメントは、以下の記事を参考にするとよい。

また、拡散MRIからb値ごとに画像を抽出する方法は、以下の記事を参考にするとよい。

4.2. 目的Boundary-Based Registration: BBB

ここで、構造MRI(3D-T1WI)空間にあるCSF, GM, WMのセグメント(CSF_GM_WM_seg.nii.gz)を、拡散MRIの空間に移動させることを考える。

そのために、まずBBBを使って拡散MRIのb=0画像(spin-echo EPI)を、構造MRI(3D-T1WI)に位置合わせする。

この時、echo spacing時間( sec)--echospacingと位相エンコード方向--pedirを前もって調べておく必要がある。これらの情報は、dcm2niixを用いてDICOM形式からNIfTI形式に変換する際に出力されるJSONファイルに記載されている。dcm2niixの使い方は、以下の記事を参考にするとよい。

準備ができたら、以下のようにepi_regコマンドを実行して、拡散MRIから構造MRIへ位置合わせする変換行列を生成する。

epi_reg --epi=DWI_b0.nii.gz --t1=T1w.nii.gz --t1brain=T1_skull_stripped.nii.gz --echospacing=0.0380544 --pedir=-y --out=DWI2T1w

次に、先ほどの変換行列(拡散MRI空間→構造MRI空間)の逆変換行列(構造MRI空間→拡散MRI空間)を生成する。

convert_xfm -omat T1w2DWI.mat -inverse DWI2T1w.mat

逆変換行列(構造MRI空間→拡散MRI空間)を構造MRI空間にいるCSF, GM, WMのセグメント(CSF_GM_WM_seg.nii.gz)に適用することで、セグメントを拡散MRI空間に移動させる。このとき、-applyxfm-interp nearestneighbourとしていることに注意する。FLIRTの使い方の詳細はこちら

flirt -in CSF_GM_WM_seg.nii.gz -ref DWI_b0.nii.gz -out CSF_GM_WM_seg_DWIspace.nii.gz -init T1w2DWI.mat -applyxfm -interp nearestneighbour

処理前後のセグメントの様子をみてみる。

fsleyes DWI.nii.gz \
CSF_GM_WM_seg.nii.gz -cm random \
CSF_GM_WM_seg_DWIspace.nii.gz -cm random

軸位断で後頭葉付近を拡大してみる。

Ubuntu 20.04 / 18.04 環境で eddy_cuda10.2 (in FSL 6.0.5.x), PyTorch, Tensorflow 2 を使えるようにCUDA 10.2, 11.0, 11.5をセットアップする方法

注意(16 Apr 2023): FSL 6.0.6 から、CUDA 11以降でもeddy_cuda10.2が動くようになりました。したがって、以下の内容はもう古くなっています。新しい記事をご確認ください。

私のメインマシンは Lin4Neuro 18.04 ですが、そろそろ Lin4Neuro 20.04 への移行を考えています。

今、実験機には NVIDIA GeForce RTX 2070 が備え付けられています。
これを使って、FSL 6.0.5 の eddy をGPUが使えるように設定し、なおかつ、Tensorflow, Pytorch といった Deep Learning のフレームワークも使えるようにしたいと思います。

FSL 6.0.5 にはデフォルトで CUDA 10.2 に対応した eddy_cuda10.2 が配布されています。なので、CUDA 10.2を入れることにします。

なお、これは Ubuntu 18.04 でも全く問題なくできることがわかりましたので、タイトルを変更しました。

続きを読む

【FSL/MRtrix】4D画像から3D画像を抽出


1. 目的
2. FSLを用いる場合
2.1. コマンド
2.2. 使用例
3. MRtrixを用いる場合
3.1. コマンド
3.2. 使用例


1. 目的

  • 4D画像から3D画像を抽出

2. FSLを用いる場合

2.1. コマンド

FSLfslroiコマンドを用いる。

fslroiのヘルプは、次の通り。

クリックして展開
Usage: fslroi <input> <output> <xmin> <xsize> <ymin> <ysize> <zmin> <zsize>
       fslroi <input> <output> <tmin> <tsize>

       fslroi <input> <output> <xmin> <xsize> <ymin> <ysize> <zmin> <zsize> <tmin> <tsize>
Note: indexing (in both time and space) starts with 0 not 1! Inputting -1 for a size will set it to the full image extent for that dimension.

4D画像から3D画像を抽出する際の、基本的な使い方は以下の通り。

fslroi <入力画像> <出力画像> <Volume Index> <Volume Indexから残したいVolume数>

2.2. 使用例

例えば、5ttgen等で作成した以下のような5つの組織画像(5tt.nii.gz)が4D画像となっている場合。

Pathological tissue(Volume 4th)を取り除くには、次のようにコマンドを実行する。FSLではVolumeのIndexを0から数える。つまり、1番目のVolumeのIndexは0となる。以下のコードを翻訳すると、「Volume Index0番から数えて4 Volumesまでを残す」ということになる。

fslroi 5tt.nii.gz 4tt.nii.gz 0 4

fslhdコマンドを用いて、ボリューム数を確認すると、処理前で5 Volumesだったのが処理後に4 Volumesになっていることが分かる。使い方の詳細は、こちらの記事を参考に。

fslhd 5tt.nii.gz |grep ^dim4
fslhd 4tt.nii.gz |grep ^dim4
dim4        5  # 5tt.nii.gz
dim4        4  # 4tt.nii.gz

3. MRtrixを用いる場合

3.1. コマンド

MRtrixmrconvertコマンドを用いる。

mrconvertのヘルプは、次の通り。

クリックして展開
SYNOPSIS

     Perform conversion between different file types and optionally extract a
     subset of the input image

USAGE

     mrconvert [ options ] input output

        input        the input image.

        output       the output image.


DESCRIPTION

     If used correctly, this program can be a very useful workhorse. In
     addition to converting images between different formats, it can be used to
     extract specific studies from a data set, extract a specific region of
     interest, or flip the images. Some of the possible operations are
     described in more detail below.

     Note that for both the -coord and -axes options, indexing starts from 0
     rather than 1. E.g. -coord 3 <#> selects volumes (the fourth dimension)
     from the series; -axes 0,1,2 includes only the three spatial axes in the
     output image.

     Additionally, for the second input to the -coord option and the -axes
     option, you can use any valid number sequence in the selection, as well as
     the 'end' keyword (see the main documentation for details); this can be
     particularly useful to select multiple coordinates.

     The -vox option is used to change the size of the voxels in the output
     image as reported in the image header; note however that this does not
     re-sample the image based on a new voxel size (that is done using the
     mrresize command).

     By default, the intensity scaling parameters in the input image header are
     passed through to the output image header when writing to an integer
     image, and reset to 0,1 (i.e. no scaling) for floating-point and binary
     images. Note that the -scaling option will therefore have no effect for
     floating-point or binary output images.

     The -axes option specifies which axes from the input image will be used to
     form the output image. This allows the permutation, omission, or addition
     of axes into the output image. The axes should be supplied as a
     comma-separated list of axis indices. If an axis from the input image is
     to be omitted from the output image, it must either already have a size of
     1, or a single coordinate along that axis must be selected by the user by
     using the -coord option. Examples are provided further below.

     The -bvalue_scaling option controls an aspect of the import of diffusion
     gradient tables. When the input diffusion-weighting direction vectors have
     norms that differ substantially from unity, the b-values will be scaled by
     the square of their corresponding vector norm (this is how multi-shell
     acquisitions are frequently achieved on scanner platforms). However in
     some rare instances, the b-values may be correct, despite the vectors not
     being of unit norm (or conversely, the b-values may need to be rescaled
     even though the vectors are close to unit norm). This option allows the
     user to control this operation and override MRrtix3's automatic detection.

EXAMPLE USAGES

     Extract the first volume from a 4D image, and make the output a 3D image:
       $ mrconvert in.mif -coord 3 0 -axes 0,1,2 out.mif
     The -coord 3 0 option extracts, from axis number 3 (which is the fourth
     axis since counting begins from 0; this is the axis that steps across
     image volumes), only coordinate number 0 (i.e. the first volume). The
     -axes 0,1,2 ensures that only the first three axes (i.e. the spatial axes)
     are retained; if this option were not used in this example, then image
     out.mif would be a 4D image, but it would only consist of a single volume,
     and mrinfo would report its size along the fourth axis as 1.

     Extract slice number 24 along the AP direction:
       $ mrconvert volume.mif slice.mif -coord 1 24
     MRtrix3 uses a RAS (Right-Anterior-Superior) axis convention, and
     internally reorients images upon loading in order to conform to this as
     far as possible. So for non-exotic data, axis 1 should correspond
     (approximately) to the anterior-posterior direction.

     Extract only every other volume from a 4D image:
       $ mrconvert all.mif every_other.mif -coord 3 1:2:end
     This example demonstrates two features: Use of the colon syntax to
     conveniently specify a number sequence (in the format 'start:step:stop');
     and use of the 'end' keyword to generate this sequence up to the size of
     the input image along that axis (i.e. the number of volumes).

     Alter the image header to report a new isotropic voxel size:
       $ mrconvert in.mif isotropic.mif -vox 1.25
     By providing a single value to the -vox option only, the specified value
     is used to set the voxel size in mm for all three spatial axes in the
     output image.

     Alter the image header to report a new anisotropic voxel size:
       $ mrconvert in.mif anisotropic.mif -vox 1,,3.5
     This example will change the reported voxel size along the first and third
     axes (ideally left-right and inferior-superior) to 1.0mm and 3.5mm
     respectively, and leave the voxel size along the second axis (ideally
     anterior-posterior) unchanged.

     Turn a single-volume 4D image into a 3D image:
       $ mrconvert 4D.mif 3D.mif -axes 0,1,2
     Sometimes in the process of extracting or calculating a single 3D volume
     from a 4D image series, the size of the image reported by mrinfo will be
     "X x Y x Z x 1", indicating that the resulting image is in fact also 4D,
     it just happens to contain only one volume. This example demonstrates how
     to convert this into a genuine 3D image (i.e. mrinfo will report the size
     as "X x Y x Z".

     Insert an axis of size 1 into the image:
       $ mrconvert XYZD.mif XYZ1D.mif -axes 0,1,2,-1,3
     This example uses the value -1 as a flag to indicate to mrconvert where a
     new axis of unity size is to be inserted. In this particular example, the
     input image has four axes: the spatial axes X, Y and Z, and some form of
     data D is stored across the fourth axis (i.e. volumes). Due to insertion
     of a new axis, the output image is 5D: the three spatial axes (XYZ), a
     single volume (the size of the output image along the fourth axis will be
     1), and data D will be stored as volume groups along the fifth axis of the
     image.

     Manually reset the data scaling parameters stored within the image header
     to defaults:
       $ mrconvert with_scaling.mif without_scaling.mif -scaling 0.0,1.0
     This command-line option alters the parameters stored within the image
     header that provide a linear mapping from raw intensity values stored in
     the image data to some other scale. Where the raw data stored in a
     particular voxel is I, the value within that voxel is interpreted as:
     value = offset + (scale x I).  To adjust this scaling, the relevant
     parameters must be provided as a comma-separated 2-vector of
     floating-point values, in the format "offset,scale" (no quotation marks).
     This particular example sets the offset to zero and the scale to one,
     which equates to no rescaling of the raw intensity data.

Options for manipulating fundamental image properties

  -coord axis selection  (multiple uses permitted)
     retain data from the input image only at the coordinates specified in the
     selection along the specified axis. The selection argument expects a
     number sequence, which can also include the 'end' keyword.

  -vox sizes
     change the voxel dimensions reported in the output image header

  -axes axes
     specify the axes from the input image that will be used to form the output
     image

  -scaling values
     specify the data scaling parameters used to rescale the intensity values

Options for handling JSON (JavaScript Object Notation) files

  -json_import file
     import data from a JSON file into header key-value pairs

  -json_export file
     export data from an image header key-value pairs into a JSON file

Options to modify generic header entries

  -clear_property key  (multiple uses permitted)
     remove the specified key from the image header altogether.

  -set_property key value  (multiple uses permitted)
     set the value of the specified key in the image header.

  -append_property key value  (multiple uses permitted)
     append the given value to the specified key in the image header (this adds
     the value specified as a new line in the header value).

  -copy_properties source
     clear all generic properties and replace with the properties from the
     image / file specified.

Stride options

  -strides spec
     specify the strides of the output data in memory; either as a
     comma-separated list of (signed) integers, or as a template image from
     which the strides shall be extracted and used. The actual strides produced
     will depend on whether the output image format can support it.

Data type options

  -datatype spec
     specify output image data type. Valid choices are: float32, float32le,
     float32be, float64, float64le, float64be, int64, uint64, int64le,
     uint64le, int64be, uint64be, int32, uint32, int32le, uint32le, int32be,
     uint32be, int16, uint16, int16le, uint16le, int16be, uint16be, cfloat32,
     cfloat32le, cfloat32be, cfloat64, cfloat64le, cfloat64be, int8, uint8,
     bit.

DW gradient table import options

  -grad file
     Provide the diffusion-weighted gradient scheme used in the acquisition in
     a text file. This should be supplied as a 4xN text file with each line is
     in the format [ X Y Z b ], where [ X Y Z ] describe the direction of the
     applied gradient, and b gives the b-value in units of s/mm^2. If a
     diffusion gradient scheme is present in the input image header, the data
     provided with this option will be instead used.

  -fslgrad bvecs bvals
     Provide the diffusion-weighted gradient scheme used in the acquisition in
     FSL bvecs/bvals format files. If a diffusion gradient scheme is present in
     the input image header, the data provided with this option will be instead
     used.

  -bvalue_scaling mode
     enable or disable scaling of diffusion b-values by the square of the
     corresponding DW gradient norm (see Desciption). Valid choices are yes/no,
     true/false, 0/1 (default: automatic).

DW gradient table export options

  -export_grad_mrtrix path
     export the diffusion-weighted gradient table to file in MRtrix format

  -export_grad_fsl bvecs_path bvals_path
     export the diffusion-weighted gradient table to files in FSL (bvecs /
     bvals) format

Options for importing phase-encode tables

  -import_pe_table file
     import a phase-encoding table from file

  -import_pe_eddy config indices
     import phase-encoding information from an EDDY-style config / index file
     pair

Options for exporting phase-encode tables

  -export_pe_table file
     export phase-encoding table to file

  -export_pe_eddy config indices
     export phase-encoding information to an EDDY-style config / index file
     pair

Standard options

  -info
     display information messages.

  -quiet
     do not display information messages or progress status; alternatively,
     this can be achieved by setting the MRTRIX_QUIET environment variable to a
     non-empty string.

  -debug
     display debugging messages.

  -force
     force overwrite of output files (caution: using the same file as input and
     output might cause unexpected behaviour).

  -nthreads number
     use this number of threads in multi-threaded applications (set to 0 to
     disable multi-threading).

  -config key value  (multiple uses permitted)
     temporarily set the value of an MRtrix config file entry.

  -help
     display this information page and exit.

  -version
     display version information and exit.

4D画像から3D画像を抽出する際の、基本的な使い方は以下の通り。

mrconvert <入力画像> <出力画像> -coord <軸番号> <残したいボリューム数>

3.2. 使用例

例えば、5ttgen等で作成した以下のような5つの組織画像(5tt.nii.gz)が4D画像となっている場合。

Pathological tissue(Volume 4th)を取り除くには、次のようにコマンドを実行する。MRtrixでもFSLと同様に、VolumeのIndexを0から数える。つまり、1番目のVolumeのIndexは0となる。また軸番号は、x, y, z, tの順番に0, 1, 2, 3であり、Volume数を操作するには、t軸(-coord 3)を操作することになる。以下のコードを翻訳すると、「Volume Index0番からVolume Index3番までを残す」ということになる。

mrconvert 5tt.nii.gz 4tt.nii.gz -coord 3 0:3

mrinfoコマンドを用いて、ボリューム数を確認すると、処理前で5 Volumesだったのが処理後に4 Volumesになっていることが分かる。使い方の詳細は、こちらの記事を参考に。

mrinfo 5tt.nii.gz 4tt.nii.gz
************************************************
Image name:          "5tt.nii.gz"
************************************************
  Dimensions:        168 x 185 x 169 x 5
  Voxel size:        0.9 x 0.9375 x 0.9375 x ?
  Data strides:      [ 1 2 3 4 ]
  Format:            NIfTI-1.1 (GZip compressed)
  Data type:         32 bit float (little endian)
  Intensity scaling: offset = 0, multiplier = 1
  Transform:               0.9998     0.01794   0.0003439      -70.81
                         -0.01788      0.9946      0.1023       -88.1
                         0.001492     -0.1023      0.9948      -56.89
  comments:          6.0.3:b862cdd5
  mrtrix_version:    3.0.0-40-g3e1ed225
************************************************
Image name:          "4tt.nii.gz"
************************************************
  Dimensions:        168 x 185 x 169 x 4
  Voxel size:        0.9 x 0.9375 x 0.9375 x ?
  Data strides:      [ 1 2 3 4 ]
  Format:            NIfTI-1.1 (GZip compressed)
  Data type:         32 bit float (little endian)
  Intensity scaling: offset = 0, multiplier = 1
  Transform:               0.9998     0.01794   0.0003439      -70.81
                         -0.01788      0.9946      0.1023       -88.1
                         0.001492     -0.1023      0.9948      -56.89
  comments:          6.0.3:b862cdd5
  mrtrix_version:    3.0.0-40-g3e1ed225

【FSL/MRtrix】画像の切り取り・マスキング ~Masking~

目的

  • 画像の切り取り・マスキング ~Masking~

FSLを用いる場合

コマンド

FSLで画像の切り取り・マスキングをするには、fslmaths-masオプションを使用する。

fslmathsのヘルプは、次の通り。

クリックして展開
Usage: fslmaths [-dt <datatype>] <first_input> [operations and inputs] <output> [-odt <datatype>]

Datatype information:
 -dt sets the datatype used internally for calculations (default float for all except double images)
 -odt sets the output datatype ( default is float )
 Possible datatypes are: char short int float double input
 "input" will set the datatype to that of the original image

Binary operations:
  (some inputs can be either an image or a number)
 -add   : add following input to current image
 -sub   : subtract following input from current image
 -mul   : multiply current image by following input
 -div   : divide current image by following input
 -rem   : modulus remainder - divide current image by following input and take remainder
 -mas   : use (following image>0) to mask current image
 -thr   : use following number to threshold current image (zero anything below the number)
 -thrp  : use following percentage (0-100) of ROBUST RANGE to threshold current image (zero anything below the number)
 -thrP  : use following percentage (0-100) of ROBUST RANGE of non-zero voxels and threshold below
 -uthr  : use following number to upper-threshold current image (zero anything above the number)
 -uthrp : use following percentage (0-100) of ROBUST RANGE to upper-threshold current image (zero anything above the number)
 -uthrP : use following percentage (0-100) of ROBUST RANGE of non-zero voxels and threshold above
 -max   : take maximum of following input and current image
 -min   : take minimum of following input and current image
 -seed  : seed random number generator with following number
 -restart : replace the current image with input for future processing operations
 -save : save the current working image to the input filename

Basic unary operations:
 -exp   : exponential
 -log   : natural logarithm
 -sin   : sine function
 -cos   : cosine function
 -tan   : tangent function
 -asin  : arc sine function
 -acos  : arc cosine function
 -atan  : arc tangent function
 -sqr   : square
 -sqrt  : square root
 -recip : reciprocal (1/current image)
 -abs   : absolute value
 -bin   : use (current image>0) to binarise
 -binv  : binarise and invert (binarisation and logical inversion)
 -fillh : fill holes in a binary mask (holes are internal - i.e. do not touch the edge of the FOV)
 -fillh26 : fill holes using 26 connectivity
 -index : replace each nonzero voxel with a unique (subject to wrapping) index number
 -grid <value> <spacing> : add a 3D grid of intensity <value> with grid spacing <spacing>
 -edge  : edge strength
 -tfce <H> <E> <connectivity>: enhance with TFCE, e.g. -tfce 2 0.5 6 (maybe change 6 to 26 for skeletons)
 -tfceS <H> <E> <connectivity> <X> <Y> <Z> <tfce_thresh>: show support area for voxel (X,Y,Z)
 -nan   : replace NaNs (improper numbers) with 0
 -nanm  : make NaN (improper number) mask with 1 for NaN voxels, 0 otherwise
 -rand  : add uniform noise (range 0:1)
 -randn : add Gaussian noise (mean=0 sigma=1)
 -inm <mean> :  (-i i ip.c) intensity normalisation (per 3D volume mean)
 -ing <mean> :  (-I i ip.c) intensity normalisation, global 4D mean)
 -range : set the output calmin/max to full data range

Matrix operations:
 -tensor_decomp : convert a 4D (6-timepoint )tensor image into L1,2,3,FA,MD,MO,V1,2,3 (remaining image in pipeline is FA)

Kernel operations (set BEFORE filtering operation if desired):
 -kernel 3D : 3x3x3 box centered on target voxel (set as default kernel)
 -kernel 2D : 3x3x1 box centered on target voxel
 -kernel box    <size>     : all voxels in a cube of width <size> mm centered on target voxel
 -kernel boxv   <size>     : all voxels in a cube of width <size> voxels centered on target voxel, CAUTION: size should be an odd number
 -kernel boxv3  <X> <Y> <Z>: all voxels in a cuboid of dimensions X x Y x Z centered on target voxel, CAUTION: size should be an odd number
 -kernel gauss  <sigma>    : gaussian kernel (sigma in mm, not voxels)
 -kernel sphere <size>     : all voxels in a sphere of radius <size> mm centered on target voxel
 -kernel file   <filename> : use external file as kernel

Spatial Filtering operations: N.B. all options apart from -s use the default kernel or that _previously_ specified by -kernel
 -dilM    : Mean Dilation of non-zero voxels
 -dilD    : Modal Dilation of non-zero voxels
 -dilF    : Maximum filtering of all voxels
 -dilall  : Apply -dilM repeatedly until the entire FOV is covered
 -ero     : Erode by zeroing non-zero voxels when zero voxels found in kernel
 -eroF    : Minimum filtering of all voxels
 -fmedian : Median Filtering 
 -fmean   : Mean filtering, kernel weighted (conventionally used with gauss kernel)
 -fmeanu  : Mean filtering, kernel weighted, un-normalised (gives edge effects)
 -s <sigma> : create a gauss kernel of sigma mm and perform mean filtering
 -subsamp2  : downsamples image by a factor of 2 (keeping new voxels centred on old)
 -subsamp2offc  : downsamples image by a factor of 2 (non-centred)

Dimensionality reduction operations:
  (the "T" can be replaced by X, Y or Z to collapse across a different dimension)
 -Tmean   : mean across time
 -Tstd    : standard deviation across time
 -Tmax    : max across time
 -Tmaxn   : time index of max across time
 -Tmin    : min across time
 -Tmedian : median across time
 -Tperc <percentage> : nth percentile (0-100) of FULL RANGE across time
 -Tar1    : temporal AR(1) coefficient (use -odt float and probably demean first)

Basic statistical operations:
 -pval    : Nonparametric uncorrected P-value, assuming timepoints are the permutations; first timepoint is actual (unpermuted) stats image
 -pval0   : Same as -pval, but treat zeros as missing data
 -cpval   : Same as -pval, but gives FWE corrected P-values
 -ztop    : Convert Z-stat to (uncorrected) P
 -ptoz    : Convert (uncorrected) P to Z
 -rank    : Convert data to ranks (over T dim)
 -ranknorm: Transform to Normal dist via ranks

Multi-argument operations:
 -roi <xmin> <xsize> <ymin> <ysize> <zmin> <zsize> <tmin> <tsize> : zero outside roi (using voxel coordinates). Inputting -1 for a size will set it to the full image extent for that dimension.
 -bptf  <hp_sigma> <lp_sigma> : (-t in ip.c) Bandpass temporal filtering; nonlinear highpass and Gaussian linear lowpass (with sigmas in volumes, not seconds); set either sigma<0 to skip that filter
 -roc <AROC-thresh> <outfile> [4Dnoiseonly] <truth> : take (normally binary) truth and test current image in ROC analysis against truth. <AROC-thresh> is usually 0.05 and is limit of Area-under-ROC measure FP axis. <outfile> is a text file of the ROC curve (triplets of values: FP TP threshold). If the truth image contains negative voxels these get excluded from all calculations. If <AROC-thresh> is positive then the [4Dnoiseonly] option needs to be set, and the FP rate is determined from this noise-only data, and is set to be the fraction of timepoints where any FP (anywhere) is seen, as found in the noise-only 4d-dataset. This is then controlling the FWE rate. If <AROC-thresh> is negative the FP rate is calculated from the zero-value parts of the <truth> image, this time averaging voxelwise FP rate over all timepoints. In both cases the TP rate is the average fraction of truth=positive voxels correctly found.

Combining 4D and 3D images:
 If you apply a Binary operation (one that takes the current image and a new image together), when one is 3D and the other is 4D,
 the 3D image is cloned temporally to match the temporal dimensions of the 4D image.

e.g. fslmaths inputVolume -add inputVolume2 output_volume
     fslmaths inputVolume -add 2.5 output_volume
     fslmaths inputVolume -add 2.5 -mul inputVolume2 output_volume

     fslmaths 4D_inputVolume -Tmean -mul -1 -add 4D_inputVolume demeaned_4D_inputVolume

基本的な使い方は、以下の通り。

fslmaths <入力画像> -mas <マスク画像> <出力画像>

使用例

頭蓋除去されていないFA画像とマスク画像(緑)を、重ね合わせて表示した画像を以下に示す。

頭蓋除去されていないFA画像(FA.nii.gz)をマスク画像(mask.nii.gz)でマスキングするには、以下のコマンドを実行する。

fslmaths FA.nii.gz -mas mask.nii.gz FA_masked.nii.gz

マスキングして、頭蓋除去したFA画像は以下。

MRtrixを用いる場合

コマンド

MRtrixで画像の切り取り・マスキングをするには、mrcalc-multオプションを使用する。

mrcalcのヘルプは、次の通り。

クリックして展開
SYNOPSIS

     Apply generic voxel-wise mathematical operations to images

USAGE

     mrcalc [ options ] operand [ operand ... ]

        operand      an input image, intensity value, or the special keywords
                     'rand' (random number between 0 and 1) or 'randn' (random
                     number from unit std.dev. normal distribution) or the
                     mathematical constants 'e' and 'pi'.


DESCRIPTION

     This command will only compute per-voxel operations. Use 'mrmath' to
     compute summary statistics across images or along image axes.

     This command uses a stack-based syntax, with operators (specified using
     options) operating on the top-most entries (i.e. images or values) in the
     stack. Operands (values or images) are pushed onto the stack in the order
     they appear (as arguments) on the command-line, and operators (specified
     as options) operate on and consume the top-most entries in the stack, and
     push their output as a new entry on the stack.

     As an additional feature, this command will allow images with different
     dimensions to be processed, provided they satisfy the following
     conditions: for each axis, the dimensions match if they are the same size,
     or one of them has size one. In the latter case, the entire image will be
     replicated along that axis. This allows for example a 4D image of size [ X
     Y Z N ] to be added to a 3D image of size [ X Y Z ], as if it consisted of
     N copies of the 3D image along the 4th axis (the missing dimension is
     assumed to have size 1). Another example would a single-voxel 4D image of
     size [ 1 1 1 N ], multiplied by a 3D image of size [ X Y Z ], which would
     allow the creation of a 4D image where each volume consists of the 3D
     image scaled by the corresponding value for that volume in the
     single-voxel image.

EXAMPLE USAGES

     Double the value stored in every voxel:
       $ mrcalc a.mif 2 -mult r.mif
     This performs the operation: r = 2*a  for every voxel a,r in images a.mif
     and r.mif respectively.

     A more complex example:
       $ mrcalc a.mif -neg b.mif -div -exp 9.3 -mult r.mif
     This performs the operation: r = 9.3*exp(-a/b)

     Another complex example:
       $ mrcalc a.mif b.mif -add c.mif d.mif -mult 4.2 -add -div r.mif
     This performs: r = (a+b)/(c*d+4.2).

     Rescale the densities in a SH l=0 image:
       $ mrcalc ODF_CSF.mif 4 pi -mult -sqrt -div ODF_CSF_scaled.mif
     This applies the spherical harmonic basis scaling factor: 1.0/sqrt(4*pi),
     such that a single-tissue voxel containing the same intensities as the
     response function of that tissue should contain the value 1.0.

basic operations

  -abs  (multiple uses permitted)
     |%1| : return absolute value (magnitude) of real or complex number

  -neg  (multiple uses permitted)
     -%1 : negative value

  -add  (multiple uses permitted)
     (%1 + %2) : add values

  -subtract  (multiple uses permitted)
     (%1 - %2) : subtract nth operand from (n-1)th

  -multiply  (multiple uses permitted)
     (%1 * %2) : multiply values

  -divide  (multiple uses permitted)
     (%1 / %2) : divide (n-1)th operand by nth

  -min  (multiple uses permitted)
     min (%1, %2) : smallest of last two operands

  -max  (multiple uses permitted)
     max (%1, %2) : greatest of last two operands

comparison operators

  -lt  (multiple uses permitted)
     (%1 < %2) : less-than operator (true=1, false=0)

  -gt  (multiple uses permitted)
     (%1 > %2) : greater-than operator (true=1, false=0)

  -le  (multiple uses permitted)
     (%1 <= %2) : less-than-or-equal-to operator (true=1, false=0)

  -ge  (multiple uses permitted)
     (%1 >= %2) : greater-than-or-equal-to operator (true=1, false=0)

  -eq  (multiple uses permitted)
     (%1 == %2) : equal-to operator (true=1, false=0)

  -neq  (multiple uses permitted)
     (%1 != %2) : not-equal-to operator (true=1, false=0)

conditional operators

  -if  (multiple uses permitted)
     (%1 ? %2 : %3) : if first operand is true (non-zero), return second
     operand, otherwise return third operand

  -replace  (multiple uses permitted)
     (%1, %2 -> %3) : Wherever first operand is equal to the second operand,
     replace with third operand

power functions

  -sqrt  (multiple uses permitted)
     sqrt (%1) : square root

  -pow  (multiple uses permitted)
     %1^%2 : raise (n-1)th operand to nth power

nearest integer operations

  -round  (multiple uses permitted)
     round (%1) : round to nearest integer

  -ceil  (multiple uses permitted)
     ceil (%1) : round up to nearest integer

  -floor  (multiple uses permitted)
     floor (%1) : round down to nearest integer

logical operators

  -not  (multiple uses permitted)
     !%1 : NOT operator: true (1) if operand is false (i.e. zero)

  -and  (multiple uses permitted)
     (%1 && %2) : AND operator: true (1) if both operands are true (i.e.
     non-zero)

  -or  (multiple uses permitted)
     (%1 || %2) : OR operator: true (1) if either operand is true (i.e.
     non-zero)

  -xor  (multiple uses permitted)
     (%1 ^^ %2) : XOR operator: true (1) if only one of the operands is true
     (i.e. non-zero)

classification functions

  -isnan  (multiple uses permitted)
     isnan (%1) : true (1) if operand is not-a-number (NaN)

  -isinf  (multiple uses permitted)
     isinf (%1) : true (1) if operand is infinite (Inf)

  -finite  (multiple uses permitted)
     finite (%1) : true (1) if operand is finite (i.e. not NaN or Inf)

complex numbers

  -complex  (multiple uses permitted)
     (%1 + %2 i) : create complex number using the last two operands as
     real,imaginary components

  -polar  (multiple uses permitted)
     (%1 /_ %2) : create complex number using the last two operands as
     magnitude,phase components (phase in radians)

  -real  (multiple uses permitted)
     real (%1) : real part of complex number

  -imag  (multiple uses permitted)
     imag (%1) : imaginary part of complex number

  -phase  (multiple uses permitted)
     phase (%1) : phase of complex number (use -abs for magnitude)

  -conj  (multiple uses permitted)
     conj (%1) : complex conjugate

  -proj  (multiple uses permitted)
     proj (%1) : projection onto the Riemann sphere

exponential functions

  -exp  (multiple uses permitted)
     exp (%1) : exponential function

  -log  (multiple uses permitted)
     log (%1) : natural logarithm

  -log10  (multiple uses permitted)
     log10 (%1) : common logarithm

trigonometric functions

  -cos  (multiple uses permitted)
     cos (%1) : cosine

  -sin  (multiple uses permitted)
     sin (%1) : sine

  -tan  (multiple uses permitted)
     tan (%1) : tangent

  -acos  (multiple uses permitted)
     acos (%1) : inverse cosine

  -asin  (multiple uses permitted)
     asin (%1) : inverse sine

  -atan  (multiple uses permitted)
     atan (%1) : inverse tangent

hyperbolic functions

  -cosh  (multiple uses permitted)
     cosh (%1) : hyperbolic cosine

  -sinh  (multiple uses permitted)
     sinh (%1) : hyperbolic sine

  -tanh  (multiple uses permitted)
     tanh (%1) : hyperbolic tangent

  -acosh  (multiple uses permitted)
     acosh (%1) : inverse hyperbolic cosine

  -asinh  (multiple uses permitted)
     asinh (%1) : inverse hyperbolic sine

  -atanh  (multiple uses permitted)
     atanh (%1) : inverse hyperbolic tangent

Data type options

  -datatype spec
     specify output image data type. Valid choices are: float32, float32le,
     float32be, float64, float64le, float64be, int64, uint64, int64le,
     uint64le, int64be, uint64be, int32, uint32, int32le, uint32le, int32be,
     uint32be, int16, uint16, int16le, uint16le, int16be, uint16be, cfloat32,
     cfloat32le, cfloat32be, cfloat64, cfloat64le, cfloat64be, int8, uint8,
     bit.

Standard options

  -info
     display information messages.

  -quiet
     do not display information messages or progress status; alternatively,
     this can be achieved by setting the MRTRIX_QUIET environment variable to a
     non-empty string.

  -debug
     display debugging messages.

  -force
     force overwrite of output files (caution: using the same file as input and
     output might cause unexpected behaviour).

  -nthreads number
     use this number of threads in multi-threaded applications (set to 0 to
     disable multi-threading).

  -config key value  (multiple uses permitted)
     temporarily set the value of an MRtrix config file entry.

  -help
     display this information page and exit.

  -version
     display version information and exit.

基本的な使い方は、以下の通り。入力画像とバイナリーマスク画像(二値画像)を掛け算することで、マスキングをする。

mrcalc <入力画像> <バイナリーマスク画像> -mult <出力画像>

使用例

頭蓋除去されていないFA画像とマスク画像(緑)を、重ね合わせて表示した画像を以下に示す。

頭蓋除去されていないFA画像(FA.nii.gz)をマスク画像(mask.nii.gz)でマスキングするには、以下のコマンドを実行する。

mrcalc FA.nii.gz  mask.nii.gz -mult FA_masked.nii.gz

マスキングして、頭蓋除去したFA画像は以下。

【FSL/MRtrix】FSL/MRtrixを用いたしきい値処理とマスク画像の作成


1. 目的
2. FSLを用いる場合
2.1. コマンド
2.2. ノイズ除去(デノイズ)
2.3. 複数のラベルから1部のラベルを抽出
3. MRtrixを用いる場合
3.1. コマンド
3.2. ノイズ除去(デノイズ)
3.3. 複数のラベルから1部のラベルを抽出


1. 目的

  • FSL/MRtrixを用いたしきい値処理とマスク画像の作成

2. FSLを用いる場合

2.1. コマンド

FSLfslmathsを用いる。fslmathsは、画像の四則演算からしきい値処理、フィルタリングなど基本的な画像処理を実行することができるコマンドである。

fslmathsのヘルプは、次の通り。

クリックして展開
Usage: fslmaths [-dt <datatype>] <first_input> [operations and inputs] <output> [-odt <datatype>]

Datatype information:
 -dt sets the datatype used internally for calculations (default float for all except double images)
 -odt sets the output datatype ( default is float )
 Possible datatypes are: char short int float double input
 "input" will set the datatype to that of the original image

Binary operations:
  (some inputs can be either an image or a number)
 -add   : add following input to current image
 -sub   : subtract following input from current image
 -mul   : multiply current image by following input
 -div   : divide current image by following input
 -rem   : modulus remainder - divide current image by following input and take remainder
 -mas   : use (following image>0) to mask current image
 -thr   : use following number to threshold current image (zero anything below the number)
 -thrp  : use following percentage (0-100) of ROBUST RANGE to threshold current image (zero anything below the number)
 -thrP  : use following percentage (0-100) of ROBUST RANGE of non-zero voxels and threshold below
 -uthr  : use following number to upper-threshold current image (zero anything above the number)
 -uthrp : use following percentage (0-100) of ROBUST RANGE to upper-threshold current image (zero anything above the number)
 -uthrP : use following percentage (0-100) of ROBUST RANGE of non-zero voxels and threshold above
 -max   : take maximum of following input and current image
 -min   : take minimum of following input and current image
 -seed  : seed random number generator with following number
 -restart : replace the current image with input for future processing operations
 -save : save the current working image to the input filename

Basic unary operations:
 -exp   : exponential
 -log   : natural logarithm
 -sin   : sine function
 -cos   : cosine function
 -tan   : tangent function
 -asin  : arc sine function
 -acos  : arc cosine function
 -atan  : arc tangent function
 -sqr   : square
 -sqrt  : square root
 -recip : reciprocal (1/current image)
 -abs   : absolute value
 -bin   : use (current image>0) to binarise
 -binv  : binarise and invert (binarisation and logical inversion)
 -fillh : fill holes in a binary mask (holes are internal - i.e. do not touch the edge of the FOV)
 -fillh26 : fill holes using 26 connectivity
 -index : replace each nonzero voxel with a unique (subject to wrapping) index number
 -grid <value> <spacing> : add a 3D grid of intensity <value> with grid spacing <spacing>
 -edge  : edge strength
 -tfce <H> <E> <connectivity>: enhance with TFCE, e.g. -tfce 2 0.5 6 (maybe change 6 to 26 for skeletons)
 -tfceS <H> <E> <connectivity> <X> <Y> <Z> <tfce_thresh>: show support area for voxel (X,Y,Z)
 -nan   : replace NaNs (improper numbers) with 0
 -nanm  : make NaN (improper number) mask with 1 for NaN voxels, 0 otherwise
 -rand  : add uniform noise (range 0:1)
 -randn : add Gaussian noise (mean=0 sigma=1)
 -inm <mean> :  (-i i ip.c) intensity normalisation (per 3D volume mean)
 -ing <mean> :  (-I i ip.c) intensity normalisation, global 4D mean)
 -range : set the output calmin/max to full data range

Matrix operations:
 -tensor_decomp : convert a 4D (6-timepoint )tensor image into L1,2,3,FA,MD,MO,V1,2,3 (remaining image in pipeline is FA)

Kernel operations (set BEFORE filtering operation if desired):
 -kernel 3D : 3x3x3 box centered on target voxel (set as default kernel)
 -kernel 2D : 3x3x1 box centered on target voxel
 -kernel box    <size>     : all voxels in a cube of width <size> mm centered on target voxel
 -kernel boxv   <size>     : all voxels in a cube of width <size> voxels centered on target voxel, CAUTION: size should be an odd number
 -kernel boxv3  <X> <Y> <Z>: all voxels in a cuboid of dimensions X x Y x Z centered on target voxel, CAUTION: size should be an odd number
 -kernel gauss  <sigma>    : gaussian kernel (sigma in mm, not voxels)
 -kernel sphere <size>     : all voxels in a sphere of radius <size> mm centered on target voxel
 -kernel file   <filename> : use external file as kernel

Spatial Filtering operations: N.B. all options apart from -s use the default kernel or that _previously_ specified by -kernel
 -dilM    : Mean Dilation of non-zero voxels
 -dilD    : Modal Dilation of non-zero voxels
 -dilF    : Maximum filtering of all voxels
 -dilall  : Apply -dilM repeatedly until the entire FOV is covered
 -ero     : Erode by zeroing non-zero voxels when zero voxels found in kernel
 -eroF    : Minimum filtering of all voxels
 -fmedian : Median Filtering 
 -fmean   : Mean filtering, kernel weighted (conventionally used with gauss kernel)
 -fmeanu  : Mean filtering, kernel weighted, un-normalised (gives edge effects)
 -s <sigma> : create a gauss kernel of sigma mm and perform mean filtering
 -subsamp2  : downsamples image by a factor of 2 (keeping new voxels centred on old)
 -subsamp2offc  : downsamples image by a factor of 2 (non-centred)

Dimensionality reduction operations:
  (the "T" can be replaced by X, Y or Z to collapse across a different dimension)
 -Tmean   : mean across time
 -Tstd    : standard deviation across time
 -Tmax    : max across time
 -Tmaxn   : time index of max across time
 -Tmin    : min across time
 -Tmedian : median across time
 -Tperc <percentage> : nth percentile (0-100) of FULL RANGE across time
 -Tar1    : temporal AR(1) coefficient (use -odt float and probably demean first)

Basic statistical operations:
 -pval    : Nonparametric uncorrected P-value, assuming timepoints are the permutations; first timepoint is actual (unpermuted) stats image
 -pval0   : Same as -pval, but treat zeros as missing data
 -cpval   : Same as -pval, but gives FWE corrected P-values
 -ztop    : Convert Z-stat to (uncorrected) P
 -ptoz    : Convert (uncorrected) P to Z
 -rank    : Convert data to ranks (over T dim)
 -ranknorm: Transform to Normal dist via ranks

Multi-argument operations:
 -roi <xmin> <xsize> <ymin> <ysize> <zmin> <zsize> <tmin> <tsize> : zero outside roi (using voxel coordinates). Inputting -1 for a size will set it to the full image extent for that dimension.
 -bptf  <hp_sigma> <lp_sigma> : (-t in ip.c) Bandpass temporal filtering; nonlinear highpass and Gaussian linear lowpass (with sigmas in volumes, not seconds); set either sigma<0 to skip that filter
 -roc <AROC-thresh> <outfile> [4Dnoiseonly] <truth> : take (normally binary) truth and test current image in ROC analysis against truth. <AROC-thresh> is usually 0.05 and is limit of Area-under-ROC measure FP axis. <outfile> is a text file of the ROC curve (triplets of values: FP TP threshold). If the truth image contains negative voxels these get excluded from all calculations. If <AROC-thresh> is positive then the [4Dnoiseonly] option needs to be set, and the FP rate is determined from this noise-only data, and is set to be the fraction of timepoints where any FP (anywhere) is seen, as found in the noise-only 4d-dataset. This is then controlling the FWE rate. If <AROC-thresh> is negative the FP rate is calculated from the zero-value parts of the <truth> image, this time averaging voxelwise FP rate over all timepoints. In both cases the TP rate is the average fraction of truth=positive voxels correctly found.

Combining 4D and 3D images:
 If you apply a Binary operation (one that takes the current image and a new image together), when one is 3D and the other is 4D,
 the 3D image is cloned temporally to match the temporal dimensions of the 4D image.

e.g. fslmaths inputVolume -add inputVolume2 output_volume
     fslmaths inputVolume -add 2.5 output_volume
     fslmaths inputVolume -add 2.5 -mul inputVolume2 output_volume

     fslmaths 4D_inputVolume -Tmean -mul -1 -add 4D_inputVolume demeaned_4D_inputVolume

基本的な使い方は、以下の通り。

fslmaths  <入力画像1> [演算子あるいは入力画像] <出力画像> 

2.2. ノイズ除去(デノイズ)

ここでは、特にしきい値処理で用いる-thr-uthrオプション、さらにバイナリーマスク作成に必要な-binオプションを例にfslmathsコマンドの使い方を解説する。

例えば、拡散MRI(b=0, SE-EPI, DWI_b0.nii.gz)に対して、二値化処理し脳マスク画像を生成する場合、以下のようなコマンドになる。

fslmaths DWI_b0.nii.gz -bin DWI_b0_mask.nii.gz

生成した脳マスク画像(緑)と拡散MRI(b=0, SE-EPI, DWI_b0.nii.gz)を重ね合わせてみる。脳以外の領域に至るまでマスキングしていることが分かる。

脳周囲のノイズ信号値を確認すると、0~30程度であった。

そこで、信号値30以下をカットするようにしきい値処理をするために、-thrオプションを用いる。

fslmaths DWI_b0.nii.gz -thr 30 -bin DWI_b0_mask_thr30.nii.gz

しきい値処理をして生成した脳マスク画像(緑)と拡散MRI(b=0, SE-EPI, DWI_b0.nii.gz)を重ね合わせてみる。ノイズ部分のマスキングが解消されていることが分かる。

2.3. 複数のラベルから1部のラベルを抽出

以下のような、CSF/GM/WMのラベル(CSF: 1, GM: 2, WM: 3)があったとする。

この内、GMのみを抽出したい場合、下限値-thrおよび上限値-uthr共に信号値2になるように設定すればよい。

fslmaths CSF_GM_WM_seg.nii.gz -thr 2 -uthr 2 GM.nii.gz

CSF/GM/WMのラベルからGMのラベルのみが抽出される。

3. MRtrixを用いる場合

3.1. コマンド

MRtrixmrthresholdを用いる。mrthresholdは、画像のしきい値処理に用いるコマンドである。

mrthresholdのヘルプは、次の通り。

クリックして展開
USAGE

     mrthreshold [ options ] input [ output ]

        input        the input image to be thresholded

        output       the (optional) output binary image mask


DESCRIPTION

     The threshold value to be applied can be determined in one of a number of
     ways:

     - If no relevant command-line option is used, the command will
     automatically determine an optimal threshold;

     - The -abs option provides the threshold value explicitly;

     - The -percentile, -top and -bottom options enable more fine-grained
     control over how the threshold value is determined.

     The -mask option only influences those image values that contribute toward
     the determination of the threshold value; once the threshold is
     determined, it is applied to the entire image, irrespective of use of the
     -mask option. If you wish for the voxels outside of the specified mask to
     additionally be excluded from the output mask, this can be achieved by
     providing the -out_masked option.

     The four operators available through the "-comparison" option ("lt", "le",
     "ge" and "gt") correspond to "less-than" (<), "less-than-or-equal" (<=),
     "greater-than-or-equal" (>=) and "greater-than" (>). This offers
     fine-grained control over how the thresholding operation will behave in
     the presence of values equivalent to the threshold. By default, the
     command will select voxels with values greater than or equal to the
     determined threshold ("ge"); unless the -bottom option is used, in which
     case after a threshold is determined from the relevant lowest-valued image
     voxels, those voxels with values less than or equal to that threshold
     ("le") are selected. This provides more fine-grained control than the
     -invert option; the latter is provided for backwards compatibility, but is
     equivalent to selection of the opposite comparison within this selection.

     If no output image path is specified, the command will instead write to
     standard output the determined threshold value.

Threshold determination mechanisms

  -abs value
     specify threshold value as absolute intensity

  -percentile value
     determine threshold based on some percentile of the image intensity
     distribution

  -top count
     determine threshold that will result in selection of some number of
     top-valued voxels

  -bottom count
     determine & apply threshold resulting in selection of some number of
     bottom-valued voxels (note: implies threshold application operator of "le"
     unless otherwise specified)

Threshold determination modifiers

  -allvolumes
     compute a single threshold for all image volumes, rather than an
     individual threshold per volume

  -ignorezero
     ignore zero-valued input values during threshold determination

  -mask image
     compute the threshold based only on values within an input mask image

Threshold application modifiers

  -comparison choice
     comparison operator to use when applying the threshold; options are:
     lt,le,ge,gt (default = "le" for -bottom; "ge" otherwise)

  -invert
     invert the output binary mask (equivalent to flipping the operator;
     provided for backwards compatibility)

  -out_masked
     mask the output image based on the provided input mask image

  -nan
     set voxels that fail the threshold to NaN rather than zero (output image
     will be floating-point rather than binary)

Standard options

  -info
     display information messages.

  -quiet
     do not display information messages or progress status; alternatively,
     this can be achieved by setting the MRTRIX_QUIET environment variable to a
     non-empty string.

  -debug
     display debugging messages.

  -force
     force overwrite of output files (caution: using the same file as input and
     output might cause unexpected behaviour).

  -nthreads number
     use this number of threads in multi-threaded applications (set to 0 to
     disable multi-threading).

  -config key value  (multiple uses permitted)
     temporarily set the value of an MRtrix config file entry.

  -help
     display this information page and exit.

  -version
     display version information and exit.

基本的な使い方は、以下の通り。

mrthreshold [オプション]  <入力画像> <出力画像>

3.2. ノイズ除去(デノイズ)

例えば、拡散MRI(b=0, SE-EPI, DWI_b0.nii.gz)に対して、二値化処理し脳マスク画像を生成する場合、以下のようなコマンドになる。

ここで、-absはしきい値を設定するオプションであり、-comparisonはしきい値に対してどのような操作を実行するのかを指定するオプションである。例えば、-comparisonでは、の4種類(“lt”, “le”, “ge”, “gt”)の操作ができ、それぞれ“less-than” (<), “less-than-or-equal” (<=), “greater-than-or-equal” (>=), “greater-than” (>)を意味する。

mrthreshold -abs 0 -comparison gt DWI_b0.nii.gz DWI_b0_mask.nii.gz

生成した脳マスク画像(緑)と拡散MRI(b=0, SE-EPI, DWI_b0.nii.gz)を重ね合わせてみる。脳以外の領域に至るまでマスキングしていることが分かる。

脳周囲のノイズ信号値を確認すると、0~30程度であった。

そこで、信号値30以下をカットするようにしきい値処理をするために、-abs 30とする。

mrthreshold -abs 30 -comparison gt DWI_b0.nii.gz DWI_b0_mask_thr30.nii.gz

しきい値処理をして生成した脳マスク画像(緑)と拡散MRI(b=0, SE-EPI, DWI_b0.nii.gz)を重ね合わせてみる。ノイズ部分のマスキングが解消されていることが分かる。

3.3. 複数のラベルから1部のラベルを抽出

以下のような、CSF/GM/WMのラベル(CSF: 1, GM: 2, WM: 3)があったとする。

この内、WMのみを抽出したい場合、次のようにコマンドを実行する。

mrthreshold -abs 2 -comparison gt CSF_GM_WM_seg.nii.gz WM.nii.gz

CSF/GM/WMのラベルからWMのラベルのみが抽出される。

著者情報: 斎藤 勇哉

順天堂大学医学部 大学院医学研究科 放射線診断学講座所属
脳MRI 画像解析が専門であり、テーマは①神経変性疾患の機序解明、②医用人工知能の開発、③多施設データのハーモナイゼーション、④速読が脳に与える影響や学習効果、⑤SNS解析を用いたマーケティング戦略の改善
医療分野に関わらず、自然言語処理・スクレイピング・データ分析・Web アプリ開発を得意とし、企業や他大学の研究を支援。
主な使用言語は、Python、Shell Script、MATLAB、HTML、CSS

【FSL】 FSLを用いた定量値の計測 ~Sampling~


1. 目的
2. コマンド
3. 使用例
3.1. 最小値と最大値
3.2. ボクセル数および容積
3.3. 平均値と標準偏差
3.4. マスク画像を用いた計測


1. 目的

  • 定量値(容積や拡散定量値など)の算出

2. コマンド

FSLfslstatsコマンドを用いて、定量値を算出することが可能。

fslstatsのヘルプは次の通り。

Usage: fslstats [preoptions] <input> [options]

preoption -t will give a separate output line for each 3D volume of a 4D timeseries
preoption -K < indexMask > will generate seperate n submasks from indexMask, for indexvalues 1..n where n is the maximum index value in indexMask, and generate statistics for each submask
Note - options are applied in order, e.g. -M -l 10 -M will report the non-zero mean, apply a threshold and then report the new nonzero mean

-l <lthresh> : set lower threshold
-u <uthresh> : set upper threshold
-r           : output <robust min intensity> <robust max intensity>
-R           : output <min intensity> <max intensity>
-e           : output mean entropy ; mean(-i*ln(i))
-E           : output mean entropy (of nonzero voxels)
-v           : output <voxels> <volume>
-V           : output <voxels> <volume> (for nonzero voxels)
-m           : output mean
-M           : output mean (for nonzero voxels)
-s           : output standard deviation
-S           : output standard deviation (for nonzero voxels)
-w           : output smallest ROI <xmin> <xsize> <ymin> <ysize> <zmin> <zsize> <tmin> <tsize> containing nonzero voxels
-x           : output co-ordinates of maximum voxel
-X           : output co-ordinates of minimum voxel
-c           : output centre-of-gravity (cog) in mm coordinates
-C           : output centre-of-gravity (cog) in voxel coordinates
-p <n>       : output nth percentile (n between 0 and 100)
-P <n>       : output nth percentile (for nonzero voxels)
-a           : use absolute values of all image intensities
-n           : treat NaN or Inf as zero for subsequent stats
-k <mask>    : use the specified image (filename) for masking - overrides lower and upper thresholds
-d <image>   : take the difference between the base image and the image specified here
-h <nbins>   : output a histogram (for the thresholded/masked voxels only) with nbins
-H <nbins> <min> <max>   : output a histogram (for the thresholded/masked voxels only) with nbins and histogram limits of min and max

Note - thresholds are not inclusive ie lthresh<allowed<uthresh

基本的な使い方は、次の通り。

# 基本
fslstats  <入力画像> [オプション]

# マスクを適用する場合
fslstats  <入力画像> -mas <マスク画像> [オプション]

3. 使用例

fslstatsコマンドで、よくある使用例を紹介する。

3.1. 最小値と最大値

最小値と最大値は、オプション-Rを用いて計測する。

以下では、頭蓋除去済みの脳画像(T1_skull_stripped.nii.gz)における最小値と最大値を計測している。

fslstats T1_skull_stripped.nii.gz -R
0.000000 1307.000000 

3.2. ボクセル数および容積

ボクセル数および容積の計測は、オプション-Vを用いる。似ているオプションで-vがあるが、オプション-Vでは、信号値が0あるいはnanでない領域を対象に、計測する。他にも小文字・大文字で区別しているオプションがあるが、信号値がある領域のみを対象にしたい場合は、基本的に大文字オプション(例:-V, -M, -S)で計測するとよい。

以下では、灰白質(GM_seg.nii.gz)の容積を計測している。

fslstats GM_seg.nii.gz -V
882175 697814.250000  # 左からボクセル数、容積(mm^3)

3.3. 平均値と標準偏差

平均値を計測するにはオプション-Mを、標準偏差を計測するにはオプション-Sを用いる。

以下では、FA(FA.nii.gz)の平均値を算出している。

fslstats FA.nii.gz -M
0.276669

以下では、FA(FA.nii.gz)の標準偏差を算出している。

fslstats FA.nii.gz -S
0.186857

3.4. マスク画像を用いた計測

計測したい領域がある場合、オプション-kで領域(マスク画像)を指定して計測するとよい。

例えば、白質(WM_seg.nii.gz)領域における、FAの平均値を計測したい場合、次のようになる。

fslstats FA.nii.gz -k WM_seg.nii.gz -M
0.507313

計測したい領域が複数あり、それらの領域にインデックス(値)が割り振られている画像(例:CSF=1, GM=2, WM=3の画像)があるとき、オプション-Kを用いると便利である。

例えば、白質を48領域分割したアトラス(JHU-ICBM-labels-1mm_indiv.nii.gz)を用いて平均値を計測する場合、次のようになる。

fslstats -K JHU-ICBM-labels-1mm_indiv.nii.gz FA.nii.gz  -M
0.491841 
0.512530 
0.591286 
0.667444 
... [省略]
0.294148

【FSL】FDT pipelineを用いた標準空間(MNI空間)への位置合わせ


1. 目的
2. 必要なファイル
3. 実行
4. 実際に実行されているコマンド
5. 出力画像


1. 目的

  • FDT pipelineを用いて、個人のDiffusion画像と標準空間(MNI空間)の構造画像の位置合わせ

2. 必要なファイル

必要なファイルは次の通り。

BEDPOSTXの使い方はこちら

.
├── DTI.bedpostX  # BEDPOSTXの出力フォルダ
├── T1.nii.gz  # BET前のBrain 3D-T1WI (FNIRT用)
└── T1_brain.nii.gz  # BET後のBrain 3D-T1WI (FLIRT用)

これに加えて、b0画像から脳を抽出した画像、nodif_brain.nii.gz を DTI.bedpostX にコピーしておく必要がある。

3. 実行

ターミナル(端末)でfslと入力。

fsl

Windowが立ち上がったら、「FDT diffusion」を選択。

各項目ごとにファイルを選択。注意すべきことは次の通り。

  • 「Main structural image」に指定する画像はBET後のBrain 3D-T1WI
  • 「Non-betted structural」に指定する画像は、BET前のBrain 3D-T1WI
  • Normal searchを「Full search」に変更

以上の設定ができたら、「Go」を選択して位置合わせを実行する。

4. 実際に実行されているコマンド

上記の操作を実行すると、ターミナル上にFSLのコマンドが生成され位置合わせが実行される。その時のコマンドは次の通り。

flirt -in DTI.bedpostX/nodif_brain \
    -ref T1_brain.nii.gz \
    -omat DTI.bedpostX/xfms/diff2str.mat \
    -searchrx -180 180 -searchry -180 180 -searchrz -180 180 \
    -dof 6 -cost corratio

convert_xfm -omat DTI.bedpostX/xfms/str2diff.mat \
    -inverse DTI.bedpostX/xfms/diff2str.mat

flirt -in T1_brain.nii.gz \
    -ref /opt/fsl/data/standard/MNI152_T1_2mm_brain \
    -omat DTI.bedpostX/xfms/str2standard.mat \
    -searchrx -180 180 -searchry -180 180 -searchrz -180 180 \
    -dof 12 -cost corratio

convert_xfm -omat DTI.bedpostX/xfms/standard2str.mat \
    -inverse DTI.bedpostX/xfms/str2standard.mat

convert_xfm -omat DTI.bedpostX/xfms/diff2standard.mat \
    -concat DTI.bedpostX/xfms/str2standard.mat DTI.bedpostX/xfms/diff2str.mat

convert_xfm -omat DTI.bedpostX/xfms/standard2diff.mat \
    -inverse DTI.bedpostX/xfms/diff2standard.mat

fnirt --in=T1.nii.gz \
    --aff=DTI.bedpostX/xfms/str2standard.mat \
    --cout=DTI.bedpostX/xfms/str2standard_warp \
    --config=T1_2_MNI152_2mm

invwarp -w DTI.bedpostX/xfms/str2standard_warp \
    -o DTI.bedpostX/xfms/standard2str_warp \
    -r T1_brain.nii.gz

convertwarp -o DTI.bedpostX/xfms/diff2standard_warp \
    -r /opt/fsl/data/standard/MNI152_T1_2mm \
    -m DTI.bedpostX/xfms/diff2str.mat \
    -w DTI.bedpostX/xfms/str2standard_warp

convertwarp -o DTI.bedpostX/xfms/standard2diff_warp \
    -r DTI.bedpostX/nodif_brain_mask \
    -w DTI.bedpostX/xfms/standard2str_warp \
    --postmat=DTI.bedpostX/xfms/str2diff.mat

5. 出力画像

処理が終わると、BEDPOSTXの出力フォルダ(DTI.bedpostX)に位置合わせの出力ファイルが保存される。

DTI.bedpostX/xfms/
├── diff2standard.mat
├── diff2standard_warp.nii.gz
├── diff2str.mat
├── eye.mat
├── standard2diff.mat
├── standard2diff_warp.nii.gz
├── standard2str.mat
├── standard2str_warp.nii.gz
├── str2diff.mat
├── str2standard.mat
└── str2standard_warp.nii.gz

【FSL】BEDPOSTXの使い方


* 1. 目的
* 2. BEDPOSTX
* 3.


1. 目的

  • BEDPOSTXの利用方法の取得

2. BEDPOSTX

BEDPOSTXの実行には、次のようなファイルが必要。

さらに、ファイル名は次のようにしておく必要がある。

Sub001/
├── bvals  # DWIのGradient Table
├── bvecs  # DWIのGradient Table
├── data.nii.gz  # DWI
└── nodif_brain_mask.nii.gz  # b=0のマスク

BEDPOSTXは、次のコマンドで実行できる。

bedpostx Sub001
# Usage: bedpostx <subject directory> [options]

3.

次のように、データを用意する。

$ tree HC003/
HC003/
├── HC003.bval   # DWIのGradient Table
├── HC003.bvec  # DWIのGradient Table
├── drHC003.nii.gz  # DWI
└── maskdrHC003.nii.gz  # b=0のマスク

この時、BEDPOSTXを実行するために必要なファイルが揃っているかをbedpostx_datacheckで確認することができる。

$ bedpostx_datacheck HC003/
HC003//data does not exist
HC003//nodif_brain_mask does not exist
 num lines in HC003//bvals 
cat: HC003//bvals: No such file or directory
0
 num words in HC003//bvals 
cat: HC003//bvals: No such file or directory
0
 num lines in HC003//bvecs 
cat: HC003//bvecs: No such file or directory
0
 num words in HC003//bvecs 
cat: HC003//bvecs: No such file or directory
0

ファイル名を修正。

tree HC003
HC003/
├── bvals
├── bvecs
├── data.nii.gz
└── nodif_brain_mask.nii.gz

再度、bedpostx_datacheckを実行する。

$ bedpostx_datacheck HC003/
HC003//data
data_type	INT16
dim1		120
dim2		120
dim3		84
dim4		137
datatype	4
pixdim1		1.700000
pixdim2		1.700000
pixdim3		1.700000
pixdim4		0.000000
cal_max		0.000000
cal_min		0.000000
file_type	NIFTI-1+

HC003//nodif_brain_mask
data_type	INT16
dim1		120
dim2		120
dim3		84
dim4		1
datatype	4
pixdim1		1.700000
pixdim2		1.700000
pixdim3		1.700000
pixdim4		0.000000
cal_max		0.000000
cal_min		0.000000
file_type	NIFTI-1+

 num lines in HC003//bvals 
1
 num words in HC003//bvals 
137
 num lines in HC003//bvecs 
3
 num words in HC003//bvecs 
411

BEDPOSTXデータのチェックができたら、BEDPOSTXを実行する。

$ bedpostx HC003/
subjectdir is /home/neuro/Documents/Yuya_S/temp/bedpostx/bedpostx_dir/HC003
Making bedpostx directory structure
Queuing preprocessing stages
...

BEDPOSTXを実行すると、「.bedpostX」フォルダが生成されこれがBEDPOSTXの生成ファイルである。

$ ls
HC003  HC003.bedpostX

BEDPOSTXで出力されるファイルは次の通り。

  • merged_th<i>samples – 4D volume – Samples from the distribution on theta
  • merged_ph<i>samples – 4D volume – Samples from the distribution on phi
  • theta and phi together represent the principal diffusion direction in spherical polar co-ordinates
  • merged_f<i>samples – 4D volume – Samples from the distribution on anisotropic volume fraction (see technical report).
  • mean_th<i>samples – 3D Volume – Mean of distribution on theta
  • mean_ph<i>samples – 3D Volume – Mean of distribution on phi
  • mean_f<i>samples – 3D Volume – Mean of distribution on f anisotropy. Note that in each voxel, fibres are ordered according to a decreasing mean f-value
  • an_dsamples – 3D Volume – Mean of distribution on diffusivity d
  • mean_d_stdsamples – 3D Volume – Mean of distribution on diffusivity variance parameter d_std (not produced if –model=1)
  • mean_S0samples – 3D Volume – Mean of distribution on T2w baseline signal intensity S0
  • dyads<i> – Mean of PDD distribution in vector form. Note that this file can be loaded into FSLeyes for easy viewing of diffusion directions
  • dyads<i>_dispersion – 3D Volume – Uncertainty on the estimated fibre orientation. Characterizes how wide the orientation distribution is around the respective PDD.(how is this calculated?)
  • nodif_brain_mask – binary mask created from nodif_brain – copied from input directory

結果を確認するには、以下のコマンドを実行。

cd HC003.bedpostX
fsleyes mean_fsumsamples.nii.gz \
  dyads1.nii.gz         -ot linevector -xc 1 0 0 -yc 1 0 0 -zc 1 0 0 -lw 2 \
  dyads2_thr0.05.nii.gz -ot linevector -xc 0 1 0 -yc 0 1 0 -zc 0 1 0 -lw 2 \
  dyads3_thr0.05.nii.gz -ot linevector -xc 0 0 1 -yc 0 0 1 -zc 0 0 1 -lw 2

【MRtrix】MRtrixを用いたギブズのリンギングアーチファクト(Gibbs ringing)の除去


1. 目的
2. コマンド
3. 使用例
3.1. 構造MRI(3D-T1WI)への適用
3.2. 拡散MRIへの適用


### 1. 目的

  • MRtrixを用いたギブズのリンギングアーチファクト(Gibbs ringing)の除去

2. コマンド

ギブズのリンギングアーチファクト(Gibbs ringing)を除去するには、MRtrixmrdegibbsを用いる。

mrdegibbsのヘルプは、以下の通り。

クリックして展開
SYNOPSIS

     Remove Gibbs Ringing Artifacts

USAGE

     mrdegibbs [ options ] in out

        in           the input image.

        out          the output image.


DESCRIPTION

     This application attempts to remove Gibbs ringing artefacts from MRI
     images using the method of local subvoxel-shifts proposed by Kellner et
     al. (see reference below for details).

     This command is designed to run on data directly after it has been
     reconstructed by the scanner, before any interpolation of any kind has
     taken place. You should not run this command after any form of motion
     correction (e.g. not after dwifslpreproc). Similarly, if you intend
     running dwidenoise, you should run denoising before this command to not
     alter the noise structure, which would impact on dwidenoise's performance.

     Note that this method is designed to work on images acquired with full
     k-space coverage. Running this method on partial Fourier ('half-scan')
     data may lead to suboptimal and/or biased results, as noted in the
     original reference below. There is currently no means of dealing with
     this; users should exercise caution when using this method on partial
     Fourier data, and inspect its output for any obvious artefacts. 

OPTIONS

  -axes list
     select the slice axes (default: 0,1 - i.e. x-y).

  -nshifts value
     discretization of subpixel spacing (default: 20).

  -minW value
     left border of window used for TV computation (default: 1).

  -maxW value
     right border of window used for TV computation (default: 3).

Data type options

  -datatype spec
     specify output image data type. Valid choices are: float32, float32le,
     float32be, float64, float64le, float64be, int64, uint64, int64le,
     uint64le, int64be, uint64be, int32, uint32, int32le, uint32le, int32be,
     uint32be, int16, uint16, int16le, uint16le, int16be, uint16be, cfloat32,
     cfloat32le, cfloat32be, cfloat64, cfloat64le, cfloat64be, int8, uint8,
     bit.

Standard options

  -info
     display information messages.

  -quiet
     do not display information messages or progress status; alternatively,
     this can be achieved by setting the MRTRIX_QUIET environment variable to a
     non-empty string.

  -debug
     display debugging messages.

  -force
     force overwrite of output files (caution: using the same file as input and
     output might cause unexpected behaviour).

  -nthreads number
     use this number of threads in multi-threaded applications (set to 0 to
     disable multi-threading).

  -config key value  (multiple uses permitted)
     temporarily set the value of an MRtrix config file entry.

  -help
     display this information page and exit.

  -version
     display version information and exit.

基本的な使い方は、以下の通り。

mrdegibbs <入力画像> <出力画像> -axes 0,1  # Axial収集
mrdegibbs <入力画像> <出力画像> -axes 0,2  # Coronal収集
mrdegibbs <入力画像> <出力画像> -axes 1,2  # Sagittal収集

3. 使用例

3.1. 構造MRI(3D-T1WI)への適用

3D-T1WI(T1w.nii.gz)を入力としてmrdegibbsを実行する。

mrdegibbs T1w.nii.gz T1w_unringed.nii.gz -axes 0,1

実行した結果は、以下の通り。

3.2. 拡散MRIへの適用

mrdegibbsは、拡散MRIにも適用できる。ただし以下の条件がある。

  • dwidenoiseでノイズを除去した後に実行
  • dwifslpreprocのような歪み・頭の動き補正をする前に実行

dwidenoiseでノイズ除去された拡散強調像(DWI_denoised.nii.gz)を入力としてmrdegibbsを実行するには、以下のコマンドを実行する。

mrdegibbs DWI_denoised.nii.gz DWI_denoised_unringed.nii.gz -axes 0,1

実行した結果は、以下の通り。

【FSL】大脳基底核のセグメンテーション


1. 目的
2. コマンド
3. 使用例
3.1. 頭蓋除去をしていない場合
3.2. 頭蓋除去を既にしている場合
4. 結果
5. おまけ


1. 目的

  • 大脳基底核のセグメンテーション

2. コマンド

FSLrun_first_allを用いる。

run_first_allのヘルプは、以下。

Usage: run_first_all [options] -i <input_image> -o <output_image>

Optional arguments:
  -m <method>      : method must be one of auto, fast, none or a (numerical) threshold value
  -b               : input is already brain extracted
  -s <name>        : run only on one specified structure (e.g. L_Hipp) or a comma separated list (no spaces)
  -a <img2std.mat> : use affine matrix (do not re-run registration)
  -3               : use 3-stage affine registration (only currently for hippocampus)
  -d               : do not cleanup image output files (useful for debugging)
  -v               : verbose output
  -h               : display this help message

e.g.:  run_first_all -i im1 -o output_name 

基本的な使い方は、次の通り。

頭蓋除去をしていない3D-T1WIを入力する場合。

run_first_all -i <入力画像(3D-T1WI)> -o <出力画像(の接頭辞)>

頭蓋除去済みの3D-T1WIを入力する場合。

run_first_all -i <入力画像(3D-T1WI)> -o <出力画像(の接頭辞)> -b

3. 使用例

3.1. 頭蓋除去をしていない場合

頭蓋除去をしていない3D-T1WI(T1w.nii.gz)に対して、run_first_allをかけるには、次のようにコマンドを実行する。

ここでは、出力画像の接頭辞(オプション:-o)を「output」とした。

run_first_all -i T1w.nii.gz -o output

3.2. 頭蓋除去を既にしている場合

まず、頭蓋除去済みの3D-T1WI(T1_skull_stripped.nii.gz)を用意する。

頭蓋除去のやり方は、以下の記事を参考にするとよい。

頭蓋除去した画像(T1_skull_stripped.nii.gz)に対して、run_first_allコマンドを実行する。

ここでは、出力画像の接頭辞(オプション:-o)を「output」とし、頭蓋除去済みの脳を入力していることを示すオプション-bを付けている。

run_first_all -i T1_skull_stripped.nii.gz -o output -b

4. 結果

処理が完了すると、次のファイルが出力される。

  • output_name_all_fast_firstseg.nii.gz:大脳基底核がセグメンテーションされた画像(3D画像)
  • output_name_all_fast_origsegs.nii.gz:大脳基底核の各セグメンテーション画像(4D画像)
  • output_name_first.vtk:セグメンテーションをする際のメッシュ。FSLViewの3Dモードで見ることができる。
  • output_name_first.bvars:パラメータファイル。

大脳基底核のセグメント(output_all_fast_firstseg.nii.gz)と頭蓋除去した画像(T1_skull_stripped.nii.gz)を、重ね合わせてみる。

fsleyes T1_skull_stripped.nii.gz output_all_fast_firstseg.nii.gz -cm random

run_first_allでは、大脳基底核を次の領域にセグメント(区域分け)する。

Label Index 領域
10 Left-Thalamus-Proper
11 Left-Caudate
12 Left-Putamen
13 Left-Pallidum
16 Brain-Stem/ 4th Ventricle
17 Left-Hippocampus
18 Left-Amygdala
26 Left-Accumbens-area
49 Right-Thalamus-Proper
50 Right-Caudate
51 Right-Putamen
52 Right-Pallidum
53 Right-Hippocampus
54 Right-Amygdala
58 Right-Accumbens-area

5. おまけ

複数の被験者のセグメンテーション結果をQCしたい場合、first_roi_slicesdirコマンドを用いると便利である。

基本な使い方は、以下。

first_roi_slicesdir <入力画像(3D-T1WI)のリスト> <セグメンテーション画像のリスト>

例えば、次のような被験者Subj001, Subj002, Subj003がいた場合。

.
├── Subj001_T1_skull_stripped.nii.gz
├── Subj001_output_all_fast_firstseg.nii.gz
├── Subj002_T1_skull_stripped.nii.gz
├── Subj002_output_all_fast_firstseg.nii.gz
├── Subj003_T1_skull_stripped.nii.gz
└── Subj003_output_all_fast_firstseg.nii.gz

first_roi_slicesdirを、次のように実行する。

first_roi_slicesdir *_t1.nii.gz *_all_fast_firstseg.nii.gz

処理が完了すると、「slicesdir」フォルダが生成される。

slicesdir/
├── Subj001_T1_skull_stripped_t1grot1_to_Subj001_output_all_fast_firstseglbgrot1.png
├── Subj002_T1_skull_stripped_t1grot2_to_Subj002_output_all_fast_firstseglbgrot2.png
├── Subj003_T1_skull_stripped_t1grot3_to_Subj003_output_all_fast_firstseglbgrot3.png
├── grota.png
├── grotb.png
├── grotc.png
├── grotd.png
├── grote.png
├── grotf.png
├── grotg.png
├── groth.png
├── groti.png
└── index.html

slicesdirフォルダの「index.html」を開くと、結果が見れる。

【FSL】FSLを用いた頭蓋除去 ~Skull-stripping~


1. 目的
2. コマンド
3. 使用例
4. 結果


1. 目的

脳画像解析で、対象となる領域は脳実質でありその他の骨・筋・脂肪・眼球等の組織は、解析する上でノイズとなる。そのため、解析精度を高めるには頭蓋を除去することが重要である。

この記事では、FSLを用いて頭蓋を除去する方法を解説する。

  • FSLを用いた頭蓋除去

2. コマンド

ここでは、FSLの関数であるBETコマンドを用いて、頭蓋を除去する。

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)

主要なオプションの役割は、次の通り。

  • -o:脳表の輪郭画像を生成
  • -m:バイナリ―のマスク画像を生成
  • -s:骨画像を生成
  • -n:セグメントした画像を生成しない
  • -f :信号値に対するしきい値(0-1, 初期値:0.5). 小さいほど脳が大きく出力される.
  • -g :信号値しきい値における垂直方向の勾配. 大きくなるほど脳幹付近の脳が大きくなり、頭頂部の脳が小さくなる.
  • -t:セグメントされた脳とマスク画像にしきい値処理を適用
  • -R:堅牢性の高い脳の中心推定(BETを何回か繰り返す)
  • -S :眼球と視神経を除去
  • -B :バイアスフィールドの補正と首の除去
  • -Z:z方向(スライス方向)のFOVがかなり小さい場合にBETの精度を上げる(一時的にスライスをパディング)
    • -F:4DのfMRIデータに適用(”-f 0.3″として少し脳マスクを大きくする)

基本的な使い方は、次の通り。

bet <入力画像> <出力画像> [オプション]

オプションについては、出力画像の結果を見ながら調節するとよい。

3. 使用例

頭蓋除去前の3D-T1WI(T1w.nii.gz)に対して、betコマンドを実行する。

bet T1w.nii.gz T1_skull_stripped.nii.gz -f 0.3 -R -S -B

処理が完了すると、頭蓋除去された画像(T1_skull_stripped.nii.gz)とそのマスク画像(T1_skull_stripped_mask.nii.gz)が生成される。

ls  # カレントディレクトリのファイルを確認

Out:

    T1_skull_stripped.nii.gz  T1_skull_stripped_mask.nii.gz  T1w.nii.gz

4. 結果

処理前後の画像は次の通り。

【FSL】 FSLを用いたRF/B1バイアス(信号ムラ)補正とセグメンテーション


1. 目的
2. コマンド
3. 使用例
4. 結果
4.1. バイアス(信号ムラ)補正
4.2. ボクセルあたりの部分容積(存在割合)
4.3. 脳組織のセグメンテーション
4.4. 確率マップ


1. 目的

  • RF/B1バイアス(信号ムラ)補正
  • 脳組織のセグメンテーション(Segmentation)

2. コマンド

FSLfastコマンドを用いる。

fastコマンドヘルプは次の通り。

Usage: 
fast [options] file(s)

Optional arguments (You may optionally specify one or more of):
	-n,--class	number of tissue-type classes; default=3
	-I,--iter	number of main-loop iterations during bias-field removal; default=4
	-l,--lowpass	bias field smoothing extent (FWHM) in mm; default=20
	-t,--type	type of image 1=T1, 2=T2, 3=PD; default=T1
	-f,--fHard	initial segmentation spatial smoothness (during bias field estimation); default=0.02
	-g,--segments	outputs a separate binary image for each tissue type
	-a <standard2input.mat> initialise using priors; you must supply a FLIRT transform
	-A <prior1> <prior2> <prior3>    alternative prior images
	--nopve	turn off PVE (partial volume estimation)
	-b		output estimated bias field
	-B		output bias-corrected image
	-N,--nobias	do not remove bias field
	-S,--channels	number of input images (channels); default 1
	-o,--out	output basename
	-P,--Prior	use priors throughout; you must also set the -a option
	-W,--init	number of segmentation-initialisation iterations; default=15
	-R,--mixel	spatial smoothness for mixeltype; default=0.3
	-O,--fixed	number of main-loop iterations after bias-field removal; default=4
	-H,--Hyper	segmentation spatial smoothness; default=0.1
	-v,--verbose	switch on diagnostic messages
	-h,--help	display this message
	-s,--manualseg <filename> Filename containing intensities
	-p		outputs individual probability maps

基本的な使い方は、次の通り。

入力画像として、T1WI, T2WI, PDWIを用いることができる。

fast <入力画像> T1w.nii.gz

3. 使用例

まず前処理として、処理前の3D-T1WI(T1w.nii.gz)に対して、頭蓋除去(skull-stripping)をする。頭蓋除去のやり方は、以下を参考に。

頭蓋除去をすると次のようになる。

頭蓋除去した画像(T1_skull_stripped.nii.gz)に対して、fastコマンドを実行する。

fast -t 1 -g -B -b -p -o output T1_skull_stripped.nii.gz

ここで、使用したオプションは次の通り。

  • -t:入力画像の種類。ここでは、T1WIであるため「-t 1」と設定。
  • -g:セグメント後の画像をバイナリー画像として出力
  • -b:バイアスフィールドを出力
  • -B:バイアス補正後の画像を出力
  • -p:セグメントした各確率マップを出力
  • -o:出力画像の接頭辞を指定。ここでは「output」とした。

4. 結果

処理が完了すると、次のような画像が出力される。

4.1. バイアス(信号ムラ)補正

  • output_bias.nii.gz:バイアスフィールド画像
  • output_restore.nii.gz:バイアス補正後の画像

4.2. ボクセルあたりの部分容積(存在割合)

  • output_pve_0.nii.gz:脳脊髄液の部分容積画像
  • output_pve_1.nii.gz:灰白質の部分容積画像
  • output_pve_2.nii.gz:白質の部分容積画像

4.3. 脳組織のセグメンテーション

  • output_seg_0.nii.gz:脳脊髄液の2値(バイナリー)画像
  • output_seg_1.nii.gz:灰白質の2値画像
  • output_seg_2.nii.gz:白質の2値画像
  • output_seg.nii.gz:脳脊髄液(1)・灰白質(2)・白質(3)がセグメントされた画像

4.4. 確率マップ

  • output_prob_0.nii.gz:脳脊髄液の確率マップ
  • output_prob_1.nii.gz:灰白質の確率マップ
  • output_prob_2.nii.gz:白質の確率マップ

【FSL】FSLを用いた画像の位置合わせ ~Registration~


1. 目的
2. 位置合わせで使用する変換について
2.1. 拡大縮小・回転・平行移動・せん断を用いた変換
2.2. 非線形変換
3. コマンド
3.1. FLIRT
3.2. FNIRT
4. 使用例
4.1. 同一被験者における脳画像の位置合わせ(剛体変換)
4.2. 異なる被験者脳の位置合わせ(アフィン変換)
4.3. 異なる被験者脳の位置合わせ(アフィン変換+非線形変換)
4.4. 標準空間上にあるラベル(関心領域)を個人脳に位置合わせ(アフィン変換+非線形変換)


1. 目的

  • 位置合わせで使用する種々の変換の理解
  • 拡大縮小・回転・平行移動・せん断を用いた変換
  • 非線形変換

2. 位置合わせで使用する変換について

位置合わせで使用する変換として、拡大縮小・回転・平行移動・せん断を用いた変換と非線形変換がある。

2.1. 拡大縮小・回転・平行移動・せん断を用いた変換

平行移動および回転を組み合わせた変換を剛体変換(Rigid transform)、拡大縮小・回転・せん断のようにY=AXで表現できる変換を線形変換(1次変換, linear transform)という。また、線形変換に平行移動を組み合わせたY=AX+Bの変換を、アフィン変換(Affine transform)という。詳細は、こちらを参考にすると分かりやすい。

脳MRI画像のような、3次元データの位置合わせの場合、拡大縮小・回転・平行移動・せん断それぞれの自由度は3である。つまり、剛体変換の自由度は6線形変換の自由度は9アフィン変換の自由度は12となる。

2.2. 非線形変換

脳のしわや脳室等の形は個人差があるので、個人脳を標準脳に合わせる際に、拡大縮小・回転・平行移動・せん断を用いた変換では、十分に位置合わせができない。そこで、脳のしわや脳室等までも合わせるために、非線形変換を導入する。

非線形変換は、Y=AX+Bのような線形式で表現できない変換であり、アルゴリズムとしてB-spline法がよく用いられている。詳細は、こちらを参考にするとよい。

3. コマンド

FSLコマンドの、flirtで拡大縮小・回転・平行移動・せん断、fnirtで非線形変換を実行することができる。

3.1. FLIRT

flirtのヘルプは次の通り。

Usage: flirt [options] -in <inputvol> -ref <refvol> -out <outputvol>
       flirt [options] -in <inputvol> -ref <refvol> -omat <outputmatrix>
       flirt [options] -in <inputvol> -ref <refvol> -applyxfm -init <matrix> -out <outputvol>

  Available options are:
        -in  <inputvol>                    (no default)
        -ref <refvol>                      (no default)
        -init <matrix-filname>             (input 4x4 affine matrix)
        -omat <matrix-filename>            (output in 4x4 ascii format)
        -out, -o <outputvol>               (default is none)
        -datatype {char,short,int,float,double}                    (force output data type)
        -cost {mutualinfo,corratio,normcorr,normmi,leastsq,labeldiff,bbr}        (default is corratio)
        -searchcost {mutualinfo,corratio,normcorr,normmi,leastsq,labeldiff,bbr}  (default is corratio)
        -usesqform                         (initialise using appropriate sform or qform)
        -displayinit                       (display initial matrix)
        -anglerep {quaternion,euler}       (default is euler)
        -interp {trilinear,nearestneighbour,sinc,spline}  (final interpolation: def - trilinear)
        -sincwidth <full-width in voxels>  (default is 7)
        -sincwindow {rectangular,hanning,blackman}
        -bins <number of histogram bins>   (default is 256)
        -dof  <number of transform dofs>   (default is 12)
        -noresample                        (do not change input sampling)
        -forcescaling                      (force rescaling even for low-res images)
        -minsampling <vox_dim>             (set minimum voxel dimension for sampling (in mm))
        -applyxfm                          (applies transform (no optimisation) - requires -init)
        -applyisoxfm <scale>               (as applyxfm but forces isotropic resampling)
        -paddingsize <number of voxels>    (for applyxfm: interpolates outside image by size)
        -searchrx <min_angle> <max_angle>  (angles in degrees: default is -90 90)
        -searchry <min_angle> <max_angle>  (angles in degrees: default is -90 90)
        -searchrz <min_angle> <max_angle>  (angles in degrees: default is -90 90)
        -nosearch                          (sets all angular search ranges to 0 0)
        -coarsesearch <delta_angle>        (angle in degrees: default is 60)
        -finesearch <delta_angle>          (angle in degrees: default is 18)
        -schedule <schedule-file>          (replaces default schedule)
        -refweight <volume>                (use weights for reference volume)
        -inweight <volume>                 (use weights for input volume)
        -wmseg <volume>                    (white matter segmentation volume needed by BBR cost function)
        -wmcoords <text matrix>            (white matter boundary coordinates for BBR cost function)
        -wmnorms <text matrix>             (white matter boundary normals for BBR cost function)
        -fieldmap <volume>                 (fieldmap image in rads/s - must be already registered to the reference image)
        -fieldmapmask <volume>             (mask for fieldmap image)
        -pedir <index>                     (phase encode direction of EPI - 1/2/3=x/y/z & -1/-2/-3=-x/-y/-z)
        -echospacing <value>               (value of EPI echo spacing - units of seconds)
        -bbrtype <value>                   (type of bbr cost function: signed [default], global_abs, local_abs)
        -bbrslope <value>                  (value of bbr slope)
        -setbackground <value>             (use specified background value for points outside FOV)
        -noclamp                           (do not use intensity clamping)
        -noresampblur                      (do not use blurring on downsampling)
        -2D                                (use 2D rigid body mode - ignores dof)
        -verbose <num>                     (0 is least and default)
        -v                                 (same as -verbose 1)
        -i                                 (pauses at each stage: default is off)
        -version                           (prints version number)
        -help

基本的な使い方は、以下。

単純に、位置合わせを実行したい場合。

flirt -in <位置合わせしたい画像> -ref <位置合わせ先の画像> -dof <自由度> -out <出力画像>

一度、変換行列を生成して、次にそれを適応する場合。

# 変換行列を生成
flirt [options] -in <位置合わせしたい画像> -ref <位置合わせ先の画像> -dof <自由度> -omat <変換行列の出力ファイル>

# 変換行列を適用
flirt [options] -in <位置合わせしたい画像> -ref <位置合わせ先の画像> -applyxfm -init <適用したい変換行列> -out <出力画像>

3.2. FNIRT

fnirtのヘルプは次の通り。

Usage: 
fnirt --ref=<some template> --in=<some image>
fnirt --ref=<some template> --in=<some image> --infwhm=8,4,2 --subsamp=4,2,1 --warpres=8,8,8

Compulsory arguments (You MUST set one or more of):
	--ref		name of reference image
	--in		name of input image

Optional arguments (You may optionally specify one or more of):
	--aff		name of file containing affine transform
	--inwarp	name of file containing initial non-linear warps
	--intin		name of file/files containing initial intensity mapping
	--cout		name of output file with field coefficients
	--iout		name of output image
	--fout		name of output file with field
	--jout		name of file for writing out the Jacobian of the field (for diagnostic or VBM purposes)
	--refout	name of file for writing out intensity modulated --ref (for diagnostic purposes)
	--intout	name of files for writing information pertaining to intensity mapping
	--logout	Name of log-file
	--config	Name of config file specifying command line arguments
	--refmask	name of file with mask in reference space
	--inmask	name of file with mask in input image space
	--applyrefmask	Use specified refmask if set, default 1 (true)
	--applyinmask	Use specified inmask if set, default 1 (true)
	--imprefm	If =1, use implicit masking based on value in --ref image. Default =1
	--impinm	If =1, use implicit masking based on value in --in image, Default =1
	--imprefval	Value to mask out in --ref image. Default =0.0
	--impinval	Value to mask out in --in image. Default =0.0
	--minmet	non-linear minimisation method [lm | scg] (Levenberg-Marquardt or Scaled Conjugate Gradient)
	--miter		Max # of non-linear iterations, default 5,5,5,5
	--subsamp	sub-sampling scheme, default 4,2,1,1
	--warpres	(approximate) resolution (in mm) of warp basis in x-, y- and z-direction, default 10,10,10
	--splineorder	Order of spline, 2->Quadratic spline, 3->Cubic spline. Default=3
	--infwhm	FWHM (in mm) of gaussian smoothing kernel for input volume, default 6,4,2,2
	--reffwhm	FWHM (in mm) of gaussian smoothing kernel for ref volume, default 4,2,0,0
	--regmod	Model for regularisation of warp-field [membrane_energy bending_energy], default bending_energy
	--lambda	Weight of regularisation, default depending on --ssqlambda and --regmod switches. See user documentation.
	--ssqlambda	If set (=1), lambda is weighted by current ssq, default 1
	--jacrange	Allowed range of Jacobian determinants, default 0.01,100.0
	--refderiv	If =1, ref image is used to calculate derivatives. Default =0
	--intmod	Model for intensity-mapping [none global_linear global_non_linear local_linear global_non_linear_with_bias local_non_linear]
	--intorder	Order of polynomial for mapping intensities, default 5
	--biasres	Resolution (in mm) of bias-field modelling local intensities, default 50,50,50
	--biaslambda	Weight of regularisation for bias-field, default 10000
	--estint	Estimate intensity-mapping if set, default 1 (true)
	--numprec	Precision for representing Hessian, double or float. Default double
	--interp	Image interpolation model, linear or spline. Default linear
	-v,--verbose	Print diagnostic information while running
	-h,--help	display help info

基本的な使い方は、以下。

単純に、位置合わせしたい場合。

fnirt --ref=<位置合わせ先の画像> --in=<位置合わせしたい画像> --iout=<出力画像>

最初にflirtを実行し、次にfnirtを実行して、位置合わせする場合。

flirt [options] -in <位置合わせしたい画像> -ref <位置合わせ先の画像> -dof <自由度> -omat <flirt変換行列の出力ファイル>
fnirt --in=<位置合わせしたい画像> --aff=<適用したいflirt変換行列>  --cout=<fnirt変換行列の出力ファイル>

applywarp --in=<位置合わせしたい画像> --ref=<位置合わせ先の画像> --warp=<fnirt変換行列の出力ファイル> --out=<flirt/fnirt後の出力画像>

fnirtでは、様々なパラメータを設定することができるが、FSLでは種々のパラメータ値が記載された設定ファイル(.cnf)を提供している。設定ファイルは、${FSLDIR}/etc/flirtschで確認することができる。fnirtで設定ファイルを用いるには、-configオプションを用いて設定ファイルを指定する。

${FSLDIR}/etc/flirtsch
├── FA_2_FMRIB58_1mm.cnf  # 個人FAとFMRIB58_1mm(標準FA)の設定ファイル
├── GM_2_MNI152GM_2mm.cnf  # 個人灰白質(GM)とMNI152GM_2mm(標準GM)の設定ファイル
├── T1_2_MNI152_2mm.cnf  # 個人T1WIとMNI152_2mm.cnf(標準T1WI)の設定ファイル
├── b02b0.cnf  # 拡散強調画像のb=0画像の位置合わせで用いる設定ファイル
├── b02b0_1.cnf  # 拡散強調画像のb=0画像の位置合わせで用いる設定ファイル
├── b02b0_2.cnf  # 拡散強調画像のb=0画像の位置合わせで用いる設定ファイル
└── b02b0_4.cnf  # 拡散強調画像のb=0画像の位置合わせで用いる設定ファイル

4. 使用例

flirtおよびfnirtを用いた脳画像の位置合わせについて、使用例を用いて解説していく。

位置合わせの精度を高めるために、位置合わせの前に前処理として頭蓋除去をしておくとよい。やり方は、以下の記事を参考にするとよい。

頭蓋除去をすると次のようになる。

4.1. 同一被験者における脳画像の位置合わせ(剛体変換)

標準空間上にある個人脳(T1_skull_stripped_inMNI.nii.gz)を、個人空間上の個人脳(T1_skull_stripped.nii.gz)に位置合わせする。

二つの画像には、個人脳と標準脳のとの間には、この程度の位置ずれがある。

標準空間上にある個人脳(T1_skull_stripped_inMNI.nii.gz)を、個人空間上の個人脳(T1_skull_stripped.nii.gz)に位置合わせするには、次のコマンドを実行する。同一被験者脳の位置合わせであるため、自由度(DoF)は6としている。

flirt -in T1_skull_stripped_inMNI.nii.gz -ref T1_skull_stripped.nii.gz -dof 6 -out T1_skull_stripped_MNI2individual.nii.gz

標準空間から個人空間に位置合わせした個人脳と、個人空間にある個人脳を重ね合わせると、次のようになる。

4.2. 異なる被験者脳の位置合わせ(アフィン変換)

頭蓋除去済みのT1WI(T1_skull_stripped.nii.gz)を標準脳T1WI(MNI152_T1_1mm_brain.nii.gz)に位置合わせする。MNI152_T1_1mm_brain.nii.gzは、「${FSLDIR}/data/standard/MNI152_T1_1mm_brain.nii.gz」にある。

個人脳と標準脳のとの間には、この程度の位置ずれがある。

個人脳を標準脳に合わせるには、次のコマンドを実行する。この時、自由度は12としている。

flirt -in T1_skull_stripped.nii.gz -ref MNI152_T1_1mm_brain.nii.gz -dof 12 -out T1_skull_stripped_inMNI.nii.gz

標準脳に位置合わせした個人脳と標準脳を重ね合わせると、次のようになる。

4.3. 異なる被験者脳の位置合わせ(アフィン変換+非線形変換)

頭蓋除去済みのT1WI(T1_skull_stripped.nii.gz)を標準脳T1WI(MNI152_T1_1mm_brain.nii.gz)に位置合わせする場合、アフィン変換だけでは、脳のしわや脳室等における位置合わせ不十分である(下図)。

そこで、アフィン変換にあわせて非線形変換も組み合わせる。

アフィン変換および非線形変換を用いて、頭蓋除去済みのT1WI(T1_skull_stripped.nii.gz)を標準脳T1WI(MNI152_T1_1mm_brain.nii.gz)に位置合わせするには、以下のコマンドを実行する。

flirt -in T1_skull_stripped.nii.gz -ref MNI152_T1_1mm_brain.nii.gz -omat indiv2std.mat
fnirt --ref=MNI152_T1_1mm_brain.nii.gz --in=T1_skull_stripped.nii.gz --aff=indiv2std.mat --iout=T1_skull_stripped_inMNI.nii.gz

アフィン変換および非線形変換を用いた、位置合わせの結果は以下。

4.4. 標準空間上にあるラベル(関心領域)を個人脳に位置合わせ(アフィン変換+非線形変換)

何らかのアトラスで定義された関心領域(ROI)を用いて、個人脳の何らかの定量値を計測したい場合がある。その時には、アトラスを個人脳に位置合わせしなくてはならない。

標準脳のFAにあるアトラス(JHU-ICBM-labels-1mm.nii.gz)を、個人脳のFAに位置合わせする。JHU-ICBM-labels-1mm.nii.gzは、「${FSLDIR}/data/atlases/JHU/JHU-ICBM-labels-1mm.nii.gz 」にある。

手順は、次の通り。

  1. flirtを用いて個人脳FAを標準脳FAに位置合わせ
  2. 1の変換行列を初期値として、fnirtで個人脳FAを標準脳FAに位置合わせ
  3. 2で得られた変換行列(個人脳→標準脳)を反転させて、標準脳から個人脳へと変換する行列に
  4. 標準脳上にあるアトラスに、3の変換行列を適用して、アトラスを個人脳に位置合わせ
# 位置合わせ
flirt -in FA.nii.gz -ref FMRIB58_FA_1mm.nii.gz -dof 12 -omat indiv2std.mat
fnirt --in=FA.nii.gz --aff=indiv2std.mat --config=FA_2_FMRIB58_1mm.cnf --cout=warp_indiv2std.nii.gz

# 変換行列(個人脳→標準脳)を反転して、標準脳から個人脳へと変換する行列に
invwarp -w warp_indiv2std.nii.gz -o warp_std2indiv.nii.gz -r FA.nii.gz

# 変換行列を適用して、アトラスを個人脳に位置合わせ
applywarp --in=JHU-ICBM-labels-1mm.nii.gz --ref=FA.nii.gz --warp=warp_std2indiv.nii.gz --interp=nn --out=JHU-ICBM-labels-1mm_indiv.nii.gz

位置合わせの結果は、次の通り。

3次元fMRI データセットを4次元fMRIデータセットに変換する方法: SPMとFSLの比較

fMRIデータは3次元データで取り扱う場合と4次元データで取り扱う場合があります。

3次元データの場合、たとえば1つのセッションが240ボリュームで構成されているとすると、240のniftiファイルで構成されます。

4次元データの場合、1つのniftiファイルに240ボリュームがすべておさめられています。

個人的には、データ管理という点では、4次元データの方が取り扱いやすいと思っています。

そこで3次元データを4次元データに変換する方法をSPMの場合とFSLの場合でまとめたいと思います。

必要な情報としては、TRです。この情報がないといくつかのソフトはうまく動かなくなります。

続きを読む