【MRtrix】MRtrixを用いた拡散MRIのノイズ除去 ~Denoise~


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


1. 目的

  • MRtrixを用いた拡散MRIのノイズ除去(Denoise)

2. コマンド

拡散MRIのノイズ除去には、MRtrixdwidenoiseを用いる。dwidenoiseは、Marchenko-Pastur PCAを用いたデノイズである。

拡散MRIのノイズ除去は、前処理の一番最初に実行する必要がある。

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

クリックして展開
SYNOPSIS

     dMRI noise level estimation and denoising using Marchenko-Pastur PCA

USAGE

     dwidenoise [ options ] dwi out

        dwi          the input diffusion-weighted image.

        out          the output denoised DWI image.


DESCRIPTION

     DWI data denoising and noise map estimation by exploiting data redundancy
     in the PCA domain using the prior knowledge that the eigenspectrum of
     random covariance matrices is described by the universal Marchenko-Pastur
     (MP) distribution. Fitting the MP distribution to the spectrum of
     patch-wise signal matrices hence provides an estimator of the noise level
     'sigma', as was first shown in Veraart et al. (2016) and later improved in
     Cordero-Grande et al. (2019). This noise level estimate then determines
     the optimal cut-off for PCA denoising.

     Important note: image denoising must be performed as the first step of the
     image processing pipeline. The routine will fail if interpolation or
     smoothing has been applied to the data prior to denoising.

     Note that this function does not correct for non-Gaussian noise biases
     present in magnitude-reconstructed MRI images. If available, including the
     MRI phase data can reduce such non-Gaussian biases, and the command now
     supports complex input data.

OPTIONS

  -mask image
     Only process voxels within the specified binary brain mask image.

  -extent window
     Set the patch size of the denoising filter. By default, the command will
     select the smallest isotropic patch size that exceeds the number of DW
     images in the input data, e.g., 5x5x5 for data with <= 125 DWI volumes,
     7x7x7 for data with <= 343 DWI volumes, etc.

  -noise level
     The output noise map, i.e., the estimated noise level 'sigma' in the data.
     Note that on complex input data, this will be the total noise level across
     real and imaginary channels, so a scale factor sqrt(2) applies.

  -datatype float32/float64
     Datatype for the eigenvalue decomposition (single or double precision).
     For complex input data, this will select complex float32 or complex
     float64 datatypes.

  -estimator Exp1/Exp2
     Select the noise level estimator (default = Exp2), either: 
     * Exp1: the original estimator used in Veraart et al. (2016), or 
     * Exp2: the improved estimator introduced in Cordero-Grande et al. (2019).

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.

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

dwidenoise <入力画像> <出力画像>

2.1. 使用例

前処理する前の拡散MRI(DWI.nii.gz)に、dwidenoiseを実行する。

dwidenoise DWI.nii.gz DWI_denoised.nii.gz

処理後の画像は、以下。

【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

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

【MRtrix】拡散MRIからb値ごとに画像を抽出


1. 目的
2. コマンド
3.使用例
3.1.前準備
3.2.b=0のみを抽出
3.3.b≠0を抽出
3.4.b値ごとに抽出


1. 目的

  • 拡散MRIからb値ごとに画像を抽出

2. コマンド

拡散MRIからb値ごとに画像を抽出するには、MRtrixdwiextractを用いる。

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

クリックして展開
SYNOPSIS

     Extract diffusion-weighted volumes, b=0 volumes, or certain shells from a
     DWI dataset

USAGE

     dwiextract [ options ] input output

        input        the input DW image.

        output       the output image (diffusion-weighted volumes by default).


EXAMPLE USAGES

     Calculate the mean b=0 image from a 4D DWI series:
       $ dwiextract dwi.mif - -bzero | mrmath - mean mean_bzero.mif -axis 3
     The dwiextract command extracts all volumes for which the b-value is
     (approximately) zero; the resulting 4D image can then be provided to the
     mrmath command to calculate the mean intensity across volumes for each
     voxel.

OPTIONS

  -bzero
     Output b=0 volumes (instead of the diffusion weighted volumes, if
     -singleshell is not specified).

  -no_bzero
     Output only non b=0 volumes (default, if -singleshell is not specified).

  -singleshell
     Force a single-shell (single non b=0 shell) output. This will include b=0
     volumes, if present. Use with -bzero to enforce presence of b=0 volumes
     (error if not present) or with -no_bzero to exclude them.

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.

DW shell selection options

  -shells b-values
     specify one or more b-values to use during processing, as a
     comma-separated list of the desired approximate b-values (b-values are
     clustered to allow for small deviations). Note that some commands are
     incompatible with multiple b-values, and will report an error if more than
     one b-value is provided. 
     WARNING: note that, even though the b=0 volumes are never referred to as
     shells in the literature, they still have to be explicitly included in the
     list of b-values as provided to the -shell option! Several algorithms
     which include the b=0 volumes in their computations may otherwise return
     an undesired result.

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 selecting volumes based on phase-encoding

  -pe desc
     select volumes with a particular phase encoding; this can be three
     comma-separated values (for i,j,k components of vector direction) or four
     (direction & total readout time)

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.

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.

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

dwiextract -bzero <入力画像> <出力画像>  # b=0のみを抽出
dwiextract -no_bzero <入力画像> <出力画像>  # b=0以外の拡散強調像を抽出
dwiextract -singleshell <入力画像> <出力画像>  # b=0以外の拡散強調像を抽出

3. 使用例

3.1. 前準備

まず、こちらの記事を参考に、拡散MRI(DWI.nii.gz)とそのMPG軸情報(bvecs, bvals)とヘッダー情報(headers.json)をまとめて、MIF形式(DWI.mif)に変換する。

mrconvert -fslgrad bvecs bvals -json_import headers.json DWI.nii.gz DWI.mif

ここで使用する拡散MRI(DWI.mif)は、b=0が1枚、b=1000が64枚、b=2000が64枚で構成されている(全部で129 volumes)。

mrinfo DWI.mif  |grep Dimensions
Dimensions:        130 x 130 x 82 x 129

3.2. b=0のみを抽出

オプション-bzeroを指定する。

dwiextract -bzero DWI.mif DWI_b0.mif

b=0の画像のみ抽出される。

mrinfo DWI_b0.mif  |grep Dimensions
Dimensions:        130 x 130 x 82 x 1

3.3. b≠0を抽出

オプション-no_bzeroを指定する。

dwiextract -no_bzero DWI.mif DWI_nonb0.mif

b≠0の画像のみ抽出される。

mrinfo DWI_nonb0.mif  |grep Dimensions
Dimensions:        130 x 130 x 82 x 128

3.4. b値ごとに抽出

オプション-singleshellを指定する。

例えば、b=1000のみを抽出する場合、以下のようになる。

dwiextract -shells 1000 DWI.mif DWI_b1000.mif

b=1000の画像のみ抽出される。

mrinfo DWI_b1000.mif  |grep Dimensions
Dimensions:        130 x 130 x 82 x 64

【MRtrix】MRtrixを用いた拡散MRIのマスク画像の作成


1. 目的
2. コマンド
3. 使用例
3.1. 前準備
3.2. 拡散MRIのマスク画像の作成


1. 目的

  • MRtrixを用いた拡散MRIのマスク画像の作成

2. コマンド

MRtrixを用いて拡散MRIのマスク画像の作成するには、dwi2maskを使用する。

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

クリックして展開
SYNOPSIS

     Generates a whole brain mask from a DWI image

USAGE

     dwi2mask [ options ] input output

        input        the input DWI image containing volumes that are both
                     diffusion weighted and b=0

        output       the output whole-brain mask image


DESCRIPTION

     All diffusion weighted and b=0 volumes are used to obtain a mask that
     includes both brain tissue and CSF.

     In a second step peninsula-like extensions, where the peninsula itself is
     wider than the bridge connecting it to the mask, are removed. This may
     help removing artefacts and non-brain parts, e.g. eyes, from the mask.

OPTIONS

  -clean_scale value
     the maximum scale used to cut bridges. A certain maximum scale cuts
     bridges up to a width (in voxels) of 2x the provided scale. Setting this
     to 0 disables the mask cleaning step. (Default: 2)

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.

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

dwi2mask <入力画像> <出力画像>

3. 使用例

3.1. 前準備

まず、こちらの記事を参考に、拡散MRI(DWI.nii.gz)とそのMPG軸情報(bvecs, bvals)とヘッダー情報(headers.json)をまとめて、MIF形式(DWI.mif)に変換する。

mrconvert -fslgrad bvecs bvals -json_import headers.json DWI.nii.gz DWI.mif

3.2. 拡散MRIのマスク画像の作成

以下のコマンドを実行する。

dwi2mask DWI.mif DWI_mask.mif

拡散MRIとマスク画像(緑)を重ね合わせてみる。

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 でも全く問題なくできることがわかりましたので、タイトルを変更しました。

続きを読む

【MRtrix】MRtrixを用いた解像度の変更 ~Upsampling~


1. 目的
2. コマンド
3. 使用例
3.1. ボクセルサイズを指定(オプション:-voxel)
3.2. スケールを指定(オプション:-scale))
3.3. ボクセルサイズを指定(オプション:-voxel))
3.4. 目的の解像度を持つ画像を指定(オプション:-template))


1. 目的

  • MRtrixを用いたアップサンプリング(Upsampling)

2. コマンド

MRtrixのmrgridを用いる。

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

クリックして展開
SYNOPSIS

     Modify the grid of an image without interpolation (cropping or padding) or
     by regridding to an image grid with modified orientation, location and or
     resolution. The image content remains in place in real world coordinates.

USAGE

     mrgrid [ options ] input operation output

        input        input image to be regridded.

        operation    the operation to be performed, one of: regrid, crop, pad.

        output       the output image.


DESCRIPTION

     - regrid: This operation performs changes of the voxel grid that require
     interpolation of the image such as changing the resolution or location and
     orientation of the voxel grid. If the image is down-sampled, the
     appropriate smoothing is automatically applied using Gaussian smoothing
     unless nearest neighbour interpolation is selected or oversample is
     changed explicitly. The resolution can only be changed for spatial
     dimensions. 

     - crop: The image extent after cropping, can be specified either manually
     for each axis dimensions, or via a mask or reference image. The image can
     be cropped to the extent of a mask. This is useful for axially-acquired
     brain images, where the image size can be reduced by a factor of 2 by
     removing the empty space on either side of the brain. Note that cropping
     does not extend the image beyond the original FOV unless explicitly
     specified (via -crop_unbound or negative -axis extent).

     - pad: Analogously to cropping, padding increases the FOV of an image
     without image interpolation. Pad and crop can be performed simultaneously
     by specifying signed specifier argument values to the -axis option.

     This command encapsulates and extends the functionality of the superseded
     commands 'mrpad', 'mrcrop' and 'mrresize'. Note the difference in -axis
     convention used for 'mrcrop' and 'mrpad' (see -axis option description).

EXAMPLE USAGES

     Crop and pad the first axis:
       $ mrgrid in.mif crop -axis 0 10,-5 out.mif
     This removes 10 voxels on the lower and pads with 5 on the upper bound,
     which is equivalent to padding with the negated specifier (mrgrid in.mif
     pad -axis 0 -10,5 out.mif).

     Right-pad the image to the number of voxels of a reference image:
       $ mrgrid in.mif pad -as ref.mif -all_axes -axis 3 0,0 out.mif -fill nan
     This pads the image on the upper bound of all axes except for the volume
     dimension. The headers of in.mif and ref.mif are ignored and the output
     image uses NAN values to fill in voxels outside the original range of
     in.mif.

     Regrid and interpolate to match the voxel grid of a reference image:
       $ mrgrid in.mif regrid -template ref.mif -scale 1,1,0.5 out.mif -fill nan
     The -template instructs to regrid in.mif to match the voxel grid of
     ref.mif (voxel size, grid orientation and voxel centres). The -scale
     option overwrites the voxel scaling factor yielding voxel sizes in the
     third dimension that are twice as coarse as those of the template image.

Regridding options (involves image interpolation, applied to spatial axes only)

  -template image
     match the input image grid (voxel spacing, image size, header
     transformation) to that of a reference image. The image resolution
     relative to the template image can be changed with one of -size, -voxel,
     -scale.

  -size dims
     define the size (number of voxels) in each spatial dimension for the
     output image. This should be specified as a comma-separated list.

  -voxel size
     define the new voxel size for the output image. This can be specified
     either as a single value to be used for all spatial dimensions, or as a
     comma-separated list of the size for each voxel dimension.

  -scale factor
     scale the image resolution by the supplied factor. This can be specified
     either as a single value to be used for all dimensions, or as a
     comma-separated list of scale factors for each dimension.

  -interp method
     set the interpolation method to use when reslicing (choices: nearest,
     linear, cubic, sinc. Default: cubic).

  -oversample factor
     set the amount of over-sampling (in the target space) to perform when
     regridding. This is particularly relevant when downsamping a
     high-resolution image to a low-resolution image, to avoid aliasing
     artefacts. This can consist of a single integer, or a comma-separated list
     of 3 integers if different oversampling factors are desired along the
     different axes. Default is determined from ratio of voxel dimensions
     (disabled for nearest-neighbour interpolation).

Pad and crop options (no image interpolation is performed, header transformation is adjusted)

  -as reference image
     pad or crop the input image on the upper bound to match the specified
     reference image grid. This operation ignores differences in image
     transformation between input and reference image.

  -uniform number
     pad or crop the input image by a uniform number of voxels on all sides

  -mask image
     crop the input image according to the spatial extent of a mask image. The
     mask must share a common voxel grid with the input image but differences
     in image transformations are ignored. Note that even though only 3
     dimensions are cropped when using a mask, the bounds are computed by
     checking the extent for all dimensions. Note that by default a gap of 1
     voxel is left at all edges of the image to allow valid trilinear
     interpolation. This gap can be modified with the -uniform option but by
     default it does not extend beyond the FOV unless -crop_unbound is used.

  -crop_unbound
     Allow padding beyond the original FOV when cropping.

  -axis index spec  (multiple uses permitted)
     pad or crop the input image along the provided axis (defined by index).
     The specifier argument defines the number of voxels added or removed on
     the lower or upper end of the axis (-axis index delta_lower,delta_upper)
     or acts as a voxel selection range (-axis index start:stop). In both
     modes, values are relative to the input image (overriding all other
     extent-specifying options). Negative delta specifier values trigger the
     inverse operation (pad instead of crop and vice versa) and negative range
     specifier trigger padding. Note that the deprecated commands 'mrcrop' and
     'mrpad' used range-based and delta-based -axis indices, respectively.

  -all_axes
     Crop or pad all, not just spatial axes.

General options

  -fill number
     Use number as the out of bounds value. nan, inf and -inf are valid
     arguments. (Default: 0.0)

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.

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.

解像度の変更する場合の基本的な使い方は、以下の通り。

mrgrid <入力画像> regrid -voxel <値> <出力画像>  # ボクセルサイズを指定
mrgrid <入力画像> regrid -scale <値> <出力画像>  # スケールを指定
mrgrid <入力画像> regrid -template <目的の解像度を持つ画像> <出力画像>  # 目的の解像度を持つ画像を指定

3. 使用例

3D-T1WI(T1w.nii.gz)の解像度を変更する。

3D-T1WI(T1w.nii.gz)の解像度を確認してみる。

mrinfo T1w.nii.gz
************************************************
Image name:          "T1w.nii.gz"
************************************************
  Dimensions:        192 x 256 x 256
  Voxel size:        0.9 x 0.9375 x 0.9375
  Data strides:      [ -1 2 3 ]
  Format:            NIfTI-1.1 (GZip compressed)
  Data type:         signed 16 bit integer (little endian)
  Intensity scaling: offset = 0, multiplier = 1
  Transform:               0.9998     0.01794   0.0003439      -82.89
                         -0.01788      0.9946      0.1023      -113.6
                         0.001492     -0.1023      0.9948      -114.6
  comments:          6.0.3:b862cdd5

3.1. ボクセルサイズを指定(オプション:-voxel

-voxelオプションを用いて、以下のコマンドを実行。

ボクセルサイズを1mm isotropicにする。

mrgrid T1w.nii.gz regrid -voxel 1 T1w_1mm_iso.nii.gz

解像度を確認してみる。ボクセルサイズが1 x 1 x 1(1mm iso)になっている

mrinfo T1w_1mm_iso.nii.gz
************************************************
Image name:          "T1w_1mm_iso.nii.gz"
************************************************
  Dimensions:        173 x 240 x 240
  Voxel size:        1 x 1 x 1
  Data strides:      [ -1 2 3 ]
  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      -82.94
                         -0.01788      0.9946      0.1023      -113.6
                         0.001492     -0.1023      0.9948      -114.5
  comments:          6.0.3:b862cdd5
  mrtrix_version:    3.0.0-40-g3e1ed225

3.2. スケールを指定(オプション:-scale

-scaleオプションを用いて、以下のコマンドを実行。

スケールを2にして、解像度を2倍にする。

mrgrid T1w.nii.gz regrid -scale 2 T1w_scale2.nii.gz

解像度を確認してみる。解像度が173 x 240 x 240からになっている。

mrinfo T1w_scale2.nii.gz
************************************************
Image name:          "T1w_scale2.nii.gz"
************************************************
  Dimensions:        384 x 512 x 512
  Voxel size:        0.45 x 0.46875 x 0.46875
  Data strides:      [ -1 2 3 ]
  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      -83.12
                         -0.01788      0.9946      0.1023      -113.9
                         0.001492     -0.1023      0.9948      -114.8
  comments:          6.0.3:b862cdd5
  mrtrix_version:    3.0.0-40-g3e1ed225

3.3. ボクセルサイズを指定(オプション:-voxel

-voxelオプションを用いて、以下のコマンドを実行。

ボクセルサイズを1mm isotropicにする。

mrgrid T1w.nii.gz regrid -voxel 1 T1w_1mm_iso.nii.gz

解像度を確認してみる。ボクセルサイズが1 x 1 x 1(1mm iso)になっている。

mrinfo T1w_1mm_iso.nii.gz
************************************************
Image name:          "T1w_1mm_iso.nii.gz"
************************************************
  Dimensions:        173 x 240 x 240
  Voxel size:        1 x 1 x 1
  Data strides:      [ -1 2 3 ]
  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      -82.94
                         -0.01788      0.9946      0.1023      -113.6
                         0.001492     -0.1023      0.9948      -114.5
  comments:          6.0.3:b862cdd5
  mrtrix_version:    3.0.0-40-g3e1ed225

3.4. 目的の解像度を持つ画像を指定(オプション:-template

標準脳(MNI152)の3D-T1WI(MNI152_T1_2mm.nii.gz)と同じ解像度にする。標準脳(MNI152_T1_2mm.nii.gz)の解像度は以下。

mrinfo MNI152_T1_2mm.nii.gz
************************************************
Image name:          "MNI152_T1_2mm.nii.gz"
************************************************
  Dimensions:        91 x 109 x 91
  Voxel size:        2 x 2 x 2
  Data strides:      [ -1 2 3 ]
  Format:            NIfTI-1.1 (GZip compressed)
  Data type:         signed 16 bit integer (little endian)
  Intensity scaling: offset = 0, multiplier = 1
  Transform:                    1           0           0         -90
                               -0           1           0        -126
                               -0           0           1         -72
  comments:          FSL5.0

個人脳(T1w.nii.gz)を標準脳(MNI152_T1_2mm.nii.gz)の解像度に合わせるには、-templateオプションを用いて、以下のコマンドを実行。

mrgrid T1w.nii.gz regrid -template MNI152_T1_2mm.nii.gz T1w_MNIreso.nii.gz

解像度を確認してみる。解像度が標準脳(MNI152_T1_2mm.nii.gz)と同じになっている。

mrinfo T1w_MNIreso.nii.gz
************************************************
Image name:          "T1w_MNIreso.nii.gz"
************************************************
  Dimensions:        91 x 109 x 91
  Voxel size:        2 x 2 x 2
  Data strides:      [ -1 2 3 ]
  Format:            NIfTI-1.1 (GZip compressed)
  Data type:         32 bit float (little endian)
  Intensity scaling: offset = 0, multiplier = 1
  Transform:                    1           0           0         -90
                               -0           1           0        -126
                               -0           0           1         -72
  comments:          6.0.3:b862cdd5
  mrtrix_version:    3.0.0-40-g3e1ed225

【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

【MRIcron/MRIcroGL】MRIcron/MRIcroGLを用いたノイズ除去とマスク画像の作成


1. 目的
2. MRIcronを用いる場合
3. MRIcroGLを用いる場合


1. 目的

  • MRIcron/MRIcroGLを用いたバイナリーマスク画像の作成

ここでは、拡散MRI(b=0, SE-EPI)の脳周囲にあるノイズ除去するため、マスク画像を生成しノイズを除去する方法を解説する。

まず、画像を見てみる。拡散MRI(b=0, SE-EPI)を信号値0-10のスケールで表示すると、以下のような画像が表示される。この内、脳周囲の白い点々(ごま塩ノイズ)は本来観測すべきではない信号、つまりノイズである。これから、このノイズを除去していく。

2. MRIcronを用いる場合

MRIcronの基本操作は、以下の記事を参考にするとよい。

脳のマスク画像を作るには、ツールタブの「Draw/Intensity filter」を選択。あるいは、「Ctrl + I」を押す。

脳実質が欠けないようにThresholdを設定する。設定ができたら「Save highlighted as NIfTI or VOI」を選択。

保存先を指定して保存する。この時NIfTI形式として保存しておくと、他の脳画像解析ソフトで扱いやすい。

保存した画像を開くと、Intensity filterでしきい値処理された画像が表示される。この時、画像はまだ二値化されていない状態である。

ここで、スケールを最初と同じ0-10に設定して、脳周囲のノイズを確認してみる。脳周囲のノイズを除去されていることが分かる。

この画像を二値化してバイナリーマスク画像を作成したい場合、ツールタブの「Draw/Advanced/Brain mask」を選択し、ファイル名を指定して保存する。

二値化されたバイナリーマスク画像が生成される。

3. MRIcroGLを用いる場合

MRIcroGLの基本操作は、以下の記事を参考にするとよい。

脳のマスク画像を作るには、ツールタブの「Draw/Advanced/Intensity Filter」を選択。

「Action: Add to Drawing」となっている状態で、脳実質が欠けないようにしきい値を設定し「Apply」をクリック。

Intensity Filterのしきい値処理が適用されて残った領域が、関心領域として設定される。

関心領域が設定されている状態で、上タブの「Draw/Advanced/Mask Image」から、「Delete/Preserve regions with VOI」を選択。

ここで、スケールを最初と同じ0-10に設定して、脳周囲のノイズを確認してみる。脳周囲のノイズを除去されていることが分かる。

この画像を二値化してバイナリーマスク画像を作成したい場合、ツールタブの「Draw/Save VOI」を選択し、ファイル名を指定して保存する(ショートカットキー:CTRL+S)。

二値化されたバイナリーマスク画像が生成される。

【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

【FreeSurfer】FreeSurferを用いた脳構造解析


1. 目的
2. FreeSurferの概要
3. 準備するデータ
4. 実行
5. 結果
5.1. aparc.stats
5.2. wmparc.stats


1. 目的

  • 構造MRI (3D-T1WI)から、の脳構造を解析

2. FreeSurferの概要

準備中。。。

3. 準備するデータ

準備するデータは、3D-T1WIのみである。

.
└── Subj001.nii.gz

4. 実行

FreeSurferのrecon-allの基本的な使い方は、次の通り。Subjects DIR-sdは、被験者データが集められているフォルダを指定する。

recon-all -i <Input 3D-T1WI> -subjid <Subject ID> -all -sd .<Subject DIR>

例えば、次のようにコマンドを打ち込むことで、FreeSurferを実行できる。

recon-all -i Subj001.nii.gz -subjid Subj001 -all -sd .

5. 結果

FreeSurferの処理が完了すると、Subj001/mriフォルダに灰白質(aparc+aseg.mgz)と白質wmparc.mgzが各脳領域ごとに分割された画像が生成される。これを脳画像に重ねて表示するには、次のコマンドを実行する。

freeview -v Subj001/mri/brain.mgz \
	Subj001/mri/aparc+aseg.mgz:colormap:lut:opacity=0.2 \
	Subj001/mri/wmparc.mgz:colormap:lut:opacity=0.2

以下のような画像が表示される。

また、各脳領域の厚さ・面積・体積・脳回の曲率等の情報がSubj001/statsフォルダに保存される。

5.1. aparc.stats

aparc.statsには、皮質および深部灰白質の構造情報が記載されている。また、aparc.statsは、左半球 (lh) と右半球 (rh) ごとに保存される(例: lh.aparc.stats)。

lh.aparc.statsの中身は、次の通り。

# Table of FreeSurfer cortical parcellation anatomical statistics 
# 
# CreationTime 2020/12/09-20:01:37-GMT
# generating_program mris_anatomical_stats
# cvs_version $Id: mris_anatomical_stats.c,v 1.79 2016/03/14 15:15:34 greve Exp $
# mrisurf.c-cvs_version $Id: mrisurf.c,v 1.781.2.6 2016/12/27 16:47:14 zkaufman Exp $
# cmdline mris_anatomical_stats -th3 -mgz -cortex ../label/lh.cortex.label -f ../stats/lh.aparc.stats -b -a ../label/lh.aparc.annot -c ../label/aparc.annot.ctab Subj001 lh white 
# sysname  Linux
# hostname neuro
# machine  x86_64
# user     neuro
# 
# SUBJECTS_DIR /home/neuro/Documents/Yuya_S/FreeSurfer/2_ANALYZE
# anatomy_type surface
# subjectname Subj001
# hemi lh
# AnnotationFile ../label/lh.aparc.annot
# AnnotationFileTimeStamp 2020/12/10 04:34:33
# Measure Cortex, NumVert, Number of Vertices, 134464, unitless
# Measure Cortex, WhiteSurfArea, White Surface Total Area, 91536.6, mm^2
# Measure Cortex, MeanThickness, Mean Thickness, 2.5011, mm
# Measure BrainSeg, BrainSegVol, Brain Segmentation Volume, 1249289.000000, mm^3
# Measure BrainSegNotVent, BrainSegVolNotVent, Brain Segmentation Volume Without Ventricles, 1227719.000000, mm^3
# Measure BrainSegNotVentSurf, BrainSegVolNotVentSurf, Brain Segmentation Volume Without Ventricles from Surf, 1227368.805429, mm^3
# Measure Cortex, CortexVol Total cortical gray matter volume, 509668.845191, mm^3
# Measure SupraTentorial, SupraTentorialVol, Supratentorial volume, 1091814.805429, mm^3
# Measure SupraTentorialNotVent, SupraTentorialVolNotVent, Supratentorial volume, 1073466.805429, mm^3
# Measure EstimatedTotalIntraCranialVol, eTIV, Estimated Total Intracranial Volume, 1529098.631452, mm^3
# NTableCols 10
# TableCol  1 ColHeader StructName
# TableCol  1 FieldName Structure Name
# TableCol  1 Units     NA
# TableCol  2 ColHeader NumVert
# TableCol  2 FieldName Number of Vertices
# TableCol  2 Units     unitless
# TableCol  3 ColHeader SurfArea
# TableCol  3 FieldName Surface Area
# TableCol  3 Units     mm^2
# TableCol  4 ColHeader GrayVol
# TableCol  4 FieldName Gray Matter Volume
# TableCol  4 Units     mm^3
# TableCol  5 ColHeader ThickAvg 
# TableCol  5 FieldName Average Thickness
# TableCol  5 Units     mm
# TableCol  6 ColHeader ThickStd
# TableCol  6 FieldName Thickness StdDev
# TableCol  6 Units     mm 
# TableCol  7 ColHeader MeanCurv
# TableCol  7 FieldName Integrated Rectified Mean Curvature
# TableCol  7 Units     mm^-1
# TableCol  8 ColHeader GausCurv 
# TableCol  8 FieldName Integrated Rectified Gaussian Curvature
# TableCol  8 Units     mm^-2
# TableCol  9 ColHeader  FoldInd
# TableCol  9 FieldName  Folding Index 
# TableCol  9 Units      unitless 
# TableCol 10 ColHeader CurvInd
# TableCol 10 FieldName Intrinsic Curvature Index
# TableCol 10 Units     unitless
# ColHeaders StructName NumVert SurfArea GrayVol ThickAvg ThickStd MeanCurv GausCurv FoldInd CurvInd
bankssts                                 1706   1193   3135  2.764 0.427     0.112     0.019       15     1.3
caudalanteriorcingulate                  1136    745   1942  2.368 0.668     0.158     0.026       24     1.1
caudalmiddlefrontal                      3765   2557   6665  2.419 0.421     0.116     0.020       35     3.2
cuneus                                   2066   1395   2739  1.905 0.546     0.151     0.034       29     3.0
entorhinal                                637    497   2185  3.351 0.914     0.119     0.024        5     0.7
fusiform                                 4365   3016   9776  2.901 0.595     0.135     0.029       65     5.2
inferiorparietal                         6556   4462  12218  2.510 0.460     0.122     0.024       81     6.2
inferiortemporal                         5440   3693  12466  2.853 0.620     0.126     0.027       75     6.2
isthmuscingulate                         1738   1138   2947  2.372 0.814     0.127     0.030       24     2.0
lateraloccipital                         7720   5101  12698  2.301 0.458     0.137     0.028      103     8.8
lateralorbitofrontal                     3955   2697   7867  2.600 0.577     0.134     0.031       55     5.0
lingual                                  5496   3835   8069  2.020 0.578     0.144     0.035       77     7.4
medialorbitofrontal                      3388   2238   6023  2.430 0.704     0.120     0.032       47     4.0
middletemporal                           5073   3489  12496  2.881 0.655     0.130     0.026       75     5.4
parahippocampal                          1129    718   2446  2.897 0.776     0.090     0.021        8     0.8
paracentral                              2097   1424   3854  2.502 0.497     0.119     0.026       20     2.0
parsopercularis                          2432   1679   4984  2.566 0.543     0.115     0.021       28     2.1
parsorbitalis                             977    670   2470  2.621 0.598     0.152     0.037       19     1.7
parstriangularis                         1970   1406   4121  2.453 0.467     0.134     0.033       30     2.6
pericalcarine                            2208   1531   1980  1.593 0.432     0.154     0.037       31     3.3
postcentral                              7825   5228  12158  2.086 0.553     0.120     0.022       89     7.0
posteriorcingulate                       1949   1342   3783  2.631 0.793     0.152     0.037       35     2.5
precentral                               8007   5252  14452  2.557 0.498     0.109     0.021       69     6.6
precuneus                                6465   4325  11805  2.509 0.500     0.122     0.026       72     6.6
rostralanteriorcingulate                 1421    964   3191  2.943 0.740     0.130     0.032       27     2.0
rostralmiddlefrontal                     8606   6003  15441  2.212 0.553     0.140     0.034      140    12.7
superiorfrontal                          9981   7035  21086  2.588 0.559     0.133     0.029      118    11.8
superiorparietal                         8285   5587  13849  2.271 0.415     0.123     0.023       96     7.4
superiortemporal                         6222   4206  13988  2.956 0.616     0.115     0.024       78     6.3
supramarginal                            6623   4574  13160  2.579 0.520     0.130     0.028       92     7.8
frontalpole                               347    235   1010  2.809 0.788     0.178     0.056       11     0.8
temporalpole                              673    484   1882  3.001 0.960     0.165     0.071       18     1.8
transversetemporal                        692    435   1114  2.318 0.447     0.096     0.018        5     0.4
insula                                   3655   2496   7826  3.170 0.729     0.121     0.033       37     4.8

5.2. wmparc.stats

wmparc.statsには、白質の構造情報が記載されている。

# Title Segmentation Statistics 
# 
# generating_program mri_segstats
# cvs_version $Id: mri_segstats.c,v 1.121 2016/05/31 17:27:11 greve Exp $
# cmdline mri_segstats --seg mri/wmparc.mgz --sum stats/wmparc.stats --pv mri/norm.mgz --excludeid 0 --brainmask mri/brainmask.mgz --in mri/norm.mgz --in-intensity-name norm --in-intensity-units MR --subject Subj001 --surf-wm-vol --ctab /opt/freesurfer/WMParcStatsLUT.txt --etiv 
# sysname  Linux
# hostname neuro
# machine  x86_64
# user     neuro
# anatomy_type volume
# 
# SUBJECTS_DIR /home/neuro/Documents/Yuya_S/FreeSurfer/2_ANALYZE
# subjectname Subj001
# Measure VentricleChoroidVol, VentricleChoroidVol, Volume of ventricles and choroid plexus, 18348.000000, mm^3
# Measure lhCerebralWhiteMatter, lhCerebralWhiteMatterVol, Left hemisphere cerebral white matter volume, 247050.231251, mm^3
# Measure rhCerebralWhiteMatter, rhCerebralWhiteMatterVol, Right hemisphere cerebral white matter volume, 245715.728986, mm^3
# Measure CerebralWhiteMatter, CerebralWhiteMatterVol, Total cerebral white matter volume, 492765.960237, mm^3
# Measure Mask, MaskVol, Mask Volume, 1604897.000000, mm^3
# Measure EstimatedTotalIntraCranialVol, eTIV, Estimated Total Intracranial Volume, 1529098.631452, mm^3
# SegVolFile mri/wmparc.mgz 
# SegVolFileTimeStamp  2020/12/10 05:19:19 
# ColorTable /opt/freesurfer/WMParcStatsLUT.txt 
# ColorTableTimeStamp 2017/01/19 07:00:02 
# InVolFile  mri/norm.mgz 
# InVolFileTimeStamp  2020/12/09 23:13:15 
# InVolFrame 0 
# PVVolFile  mri/norm.mgz 
# PVVolFileTimeStamp  2020/12/09 23:13:15 
# ExcludeSegId 0 
# Only reporting non-empty segmentations
# VoxelVolume_mm3 1 
# TableCol  1 ColHeader Index 
# TableCol  1 FieldName Index 
# TableCol  1 Units     NA 
# TableCol  2 ColHeader SegId 
# TableCol  2 FieldName Segmentation Id
# TableCol  2 Units     NA
# TableCol  3 ColHeader NVoxels 
# TableCol  3 FieldName Number of Voxels
# TableCol  3 Units     unitless
# TableCol  4 ColHeader Volume_mm3
# TableCol  4 FieldName Volume
# TableCol  4 Units     mm^3
# TableCol  5 ColHeader StructName
# TableCol  5 FieldName Structure Name
# TableCol  5 Units     NA
# TableCol  6 ColHeader normMean 
# TableCol  6 FieldName Intensity normMean
# TableCol  6 Units     MR
# TableCol  7 ColHeader normStdDev
# TableCol  7 FieldName Itensity normStdDev
# TableCol  7 Units     MR
# TableCol  8 ColHeader normMin
# TableCol  8 FieldName Intensity normMin
# TableCol  8 Units     MR
# TableCol  9 ColHeader normMax
# TableCol  9 FieldName Intensity normMax
# TableCol  9 Units     MR
# TableCol 10 ColHeader normRange
# TableCol 10 FieldName Intensity normRange
# TableCol 10 Units     MR
# NRows 70 
# NTableCols 10 
# ColHeaders  Index SegId NVoxels Volume_mm3 StructName normMean normStdDev normMin normMax normRange  
  1 3001      3524     3508.1  wm-lh-bankssts                    98.6405     7.9080    71.0000   118.0000    47.0000 
  2 3002      3041     3012.8  wm-lh-caudalanteriorcingulate    106.1743     9.7316    71.0000   126.0000    55.0000 
  3 3003      6943     6929.7  wm-lh-caudalmiddlefrontal         95.6736     9.8735    63.0000   117.0000    54.0000 
  4 3005      2121     2119.2  wm-lh-cuneus                      91.1391    10.4037    66.0000   114.0000    48.0000 
  5 3006      1049     1088.4  wm-lh-entorhinal                  80.1049     8.8624    56.0000   112.0000    56.0000 
  6 3007      6820     6751.2  wm-lh-fusiform                    90.8783    10.4333    56.0000   114.0000    58.0000 
  7 3008      9829     9877.3  wm-lh-inferiorparietal            96.3825    10.2446    63.0000   120.0000    57.0000 
  8 3009      7034     7002.1  wm-lh-inferiortemporal            86.2688    12.7662    51.0000   113.0000    62.0000 
  9 3010      4036     4077.5  wm-lh-isthmuscingulate           105.1016     9.5987    37.0000   124.0000    87.0000 
 10 3011      9108     9298.5  wm-lh-lateraloccipital            90.5220     9.1699    63.0000   114.0000    51.0000 
 11 3012      6634     6595.1  wm-lh-lateralorbitofrontal        99.7825    11.2891    66.0000   126.0000    60.0000 
 12 3013      6526     6406.8  wm-lh-lingual                     89.2861    10.1055    51.0000   117.0000    66.0000 
 13 3014      4776     4756.7  wm-lh-medialorbitofrontal        100.5992    12.2001    24.0000   127.0000   103.0000 
 14 3015      5454     5569.1  wm-lh-middletemporal              85.9773     9.9489    57.0000   112.0000    55.0000 
 15 3016      1589     1661.2  wm-lh-parahippocampal             89.3222     8.3148    65.0000   112.0000    47.0000 
 16 3017      4042     4074.3  wm-lh-paracentral                 92.4000     8.4372    66.0000   115.0000    49.0000 
 17 3018      3752     3724.1  wm-lh-parsopercularis             95.7439    10.4939    68.0000   119.0000    51.0000 
 18 3019       934      925.5  wm-lh-parsorbitalis               84.3351    10.0562    61.0000   106.0000    45.0000 
 19 3020      2889     2864.7  wm-lh-parstriangularis            91.3375    11.1110    62.0000   117.0000    55.0000 
 20 3021      3880     3534.2  wm-lh-pericalcarine               90.3379    10.1190    62.0000   113.0000    51.0000 
 21 3022      9048     9133.1  wm-lh-postcentral                 90.5553    10.1126    63.0000   117.0000    54.0000 
 22 3023      4979     4930.6  wm-lh-posteriorcingulate         102.9735     9.9418    48.0000   122.0000    74.0000 
 23 3024     14565    14538.0  wm-lh-precentral                  93.4461     9.1777    63.0000   119.0000    56.0000 
 24 3025     10517    10495.6  wm-lh-precuneus                   99.6304     9.6149    36.0000   154.0000   118.0000 
 25 3026      2602     2514.4  wm-lh-rostralanteriorcingulate   101.8966    14.8008    35.0000   134.0000    99.0000 
 26 3027     12713    12821.3  wm-lh-rostralmiddlefrontal        98.1206    10.5230    65.0000   120.0000    55.0000 
 27 3028     17112    17150.4  wm-lh-superiorfrontal             94.3707    10.5009    61.0000   123.0000    62.0000 
 28 3029     12917    13041.8  wm-lh-superiorparietal            96.7138    10.0283    62.0000   117.0000    55.0000 
 29 3030      8258     8541.9  wm-lh-superiortemporal            93.0829    10.6918    63.0000   118.0000    55.0000 
 30 3031      9396     9420.8  wm-lh-supramarginal               96.7631    10.6806    63.0000   121.0000    58.0000 
 31 3032       214      221.1  wm-lh-frontalpole                 92.0561     9.4181    74.0000   116.0000    42.0000 
 32 3033       624      687.3  wm-lh-temporalpole                79.2388     7.5813    57.0000   110.0000    53.0000 
 33 3034       642      622.6  wm-lh-transversetemporal          94.6511     8.5727    75.0000   115.0000    40.0000 
 34 3035     10580    10410.0  wm-lh-insula                      96.7245    10.8609    58.0000   124.0000    66.0000 
 35 4001      2904     2910.9  wm-rh-bankssts                    95.7104     7.8693    67.0000   110.0000    43.0000 
 36 4002      2504     2512.0  wm-rh-caudalanteriorcingulate    105.3910     9.3044    69.0000   123.0000    54.0000 
 37 4003      7042     6997.0  wm-rh-caudalmiddlefrontal         96.0454     9.8148    65.0000   116.0000    51.0000 
 38 4005      2412     2543.3  wm-rh-cuneus                      88.8429     8.8231    63.0000   113.0000    50.0000 
 39 4006       692      766.1  wm-rh-entorhinal                  78.1604     8.9138    59.0000   113.0000    54.0000 
 40 4007      7157     7093.4  wm-rh-fusiform                    89.5639     9.5493    59.0000   111.0000    52.0000 
 41 4008     12012    12138.6  wm-rh-inferiorparietal            94.7903     9.8456    65.0000   115.0000    50.0000 
 42 4009      6736     6716.1  wm-rh-inferiortemporal            88.8744    10.5262    59.0000   110.0000    51.0000 
 43 4010      3673     3687.3  wm-rh-isthmuscingulate           103.4236    10.2888    26.0000   124.0000    98.0000 
 44 4011      9750     9938.5  wm-rh-lateraloccipital            89.0627     8.8456    53.0000   109.0000    56.0000 
 45 4012      6075     6100.6  wm-rh-lateralorbitofrontal        94.8914    10.2953    62.0000   118.0000    56.0000 
 46 4013      6756     6633.9  wm-rh-lingual                     86.4899    10.0740    11.0000   111.0000   100.0000 
 47 4014      3719     3732.0  wm-rh-medialorbitofrontal         94.9559    11.6434    30.0000   119.0000    89.0000 
 48 4015      5794     5999.5  wm-rh-middletemporal              88.0036     9.7096    59.0000   110.0000    51.0000 
 49 4016      1574     1625.5  wm-rh-parahippocampal             88.7154     8.8436    44.0000   112.0000    68.0000 
 50 4017      4166     4199.9  wm-rh-paracentral                 93.8337     8.2716    69.0000   116.0000    47.0000 
 51 4018      3510     3504.4  wm-rh-parsopercularis             96.5960    10.2199    66.0000   117.0000    51.0000 
 52 4019      1053     1065.9  wm-rh-parsorbitalis               86.1054     9.5682    62.0000   109.0000    47.0000 
 53 4020      3448     3427.2  wm-rh-parstriangularis            91.6995    10.0940    62.0000   114.0000    52.0000 
 54 4021      2888     2670.2  wm-rh-pericalcarine               86.4228     8.9538    26.0000   108.0000    82.0000 
 55 4022      7978     7981.5  wm-rh-postcentral                 90.6651    10.5013    63.0000   116.0000    53.0000 
 56 4023      4712     4661.9  wm-rh-posteriorcingulate         103.0671     8.9448    49.0000   124.0000    75.0000 
 57 4024     14926    14925.4  wm-rh-precentral                  94.0721     8.5665    67.0000   117.0000    50.0000 
 58 4025     10712    10698.6  wm-rh-precuneus                   99.2039     9.2602    54.0000   121.0000    67.0000 
 59 4026      1870     1846.9  wm-rh-rostralanteriorcingulate   103.8059    10.5876    70.0000   131.0000    61.0000 
 60 4027     11835    12171.9  wm-rh-rostralmiddlefrontal        96.1585     9.2493    66.0000   115.0000    49.0000 
 61 4028     17809    18126.3  wm-rh-superiorfrontal             94.0811     9.3702    63.0000   119.0000    56.0000 
 62 4029     13213    13320.4  wm-rh-superiorparietal            95.6500     9.6784    63.0000   116.0000    53.0000 
 63 4030      7743     7980.9  wm-rh-superiortemporal            93.0976     9.4358    65.0000   113.0000    48.0000 
 64 4031      9885     9909.1  wm-rh-supramarginal               96.7241    10.3698    63.0000   118.0000    55.0000 
 65 4032       240      265.8  wm-rh-frontalpole                 91.2417     7.4440    75.0000   107.0000    32.0000 
 66 4033       723      784.5  wm-rh-temporalpole                78.9391     8.1127    57.0000    98.0000    41.0000 
 67 4034       585      577.1  wm-rh-transversetemporal          96.0513     7.4146    73.0000   112.0000    39.0000 
 68 4035     11695    11518.1  wm-rh-insula                      94.4427    11.1743    41.0000   120.0000    79.0000 
 69 5001     37165    37072.8  Left-UnsegmentedWhiteMatter      103.1510     9.9691    27.0000   127.0000   100.0000 
 70 5002     35548    35459.7  Right-UnsegmentedWhiteMatter     102.0210     9.6094    23.0000   126.0000   103.0000 

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


1. 目的
2. 準備
2.1. DIPYのインストール
2.2. 使用データ
3. 拡散MRIのノイズ除去
3.1. 必要なパッケージをインポート
3.2. 画像およびMPG軸情報の読み込み
3.3. マスク画像の作成
3.4. ギブズのリンギングアーチファクト除去
3.5. NIfTI形式で保存
3.6. 結果


### 1. 目的

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

2. 準備

2.1. DIPYのインストール

pip3 install dipy

2.2. 使用データ

データを次のフォルダ構造で用意する。

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

3. 拡散MRIのノイズ除去

Pythonで以下のコマンドを実行。

3.1. 必要なパッケージをインポート

from dipy.denoise.gibbs import gibbs_removal
import matplotlib.pyplot as plt
import numpy as np
from dipy.segment.mask import median_otsu
from dipy.io.image import load_nifti, save_nifti
from dipy.io.gradients import read_bvals_bvecs
from dipy.core.gradients import gradient_table

3.2. 画像およびMPG軸情報の読み込み

DWI_FILE = 'DWI.nii.gz'
BVALS_FILE = 'bvals'
BVECS_FILE = 'bvecs'

# Import data
data, affine = load_nifti(DWI_FILE)
bvals, bvecs = read_bvals_bvecs(BVALS_FILE, BVECS_FILE)
gtab = gradient_table(bvals, bvecs)

3.3. マスク画像の作成

median_otsu関数を用いて、b=0画像からマスク画像を生成する。vol_idxには、b0 volumeのvolume indexを渡す。

maskdata, mask = median_otsu(
    data, vol_idx=np.where(bvals == 0)[0])

3.4. ギブズのリンギングアーチファクト除去

gibbs_removal関数を用いて、リンギングアーチファクトを除去する。

data_corrected = gibbs_removal(maskdata)

3.5. NIfTI形式で保存

save_nifti関数で、画像をNIfTI形式で保存する。

save_nifti('DWI_degibbs.nii.gz', data_corrected.astype(np.float32), affine)

3.6. 結果

補正前後の画像は、以下の通り。

【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」を開くと、結果が見れる。

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


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


1. 目的

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

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

  • FreeSurferを用いた頭蓋除去

2. コマンド

ここでは、FreeSurferの関数であるrecon-allコマンドを用いて、頭蓋を除去する。

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

# FreeSurfer作業ディレクトリを指定
export SUBJECTS_DIR=<PATH>

# Autorecon1を実行
recon-all -subjid <被験者ID (任意)> -i <入力画像 (3D-T1WI)> -autorecon1

Autorecon1では、以下の処理を実行している。

  1. 動き補正(同一被験者の3D-T1WIが二つある場合には、平均画像を生成)
  2. Talairach変換
  3. 信号ムラ(バイアス)の補正
  4. 信号値の正規化
  5. 頭蓋除去

3. 使用例

頭蓋除去前の3D-T1WI(T1w.nii.gz)に対して、recon-all -autorecon1コマンドを実行する。ここでは、被験者ID(-subjid)を「Subj001」にした。これは、自由に変えてもよい。

# FreeSurfer作業ディレクトリを指定
export SUBJECTS_DIR=$PWD

# Autorecon1を実行
recon-all -subjid Subj001 -i T1w.nii.gz -autorecon1

# Autorecon1で作成した頭蓋除去済みの脳マスク画像(brainmask)をNIfTIに変換
# ただし、元画像(T1w.nii.gz)と同じヘッダー情報を参考に(--likeオプション)
mri_convert Subj001/mri/brainmask.mgz brainmask.nii.gz --like T1w.nii.gz

# 元のT1WIにbrainmaskを適用
fslmaths T1w.nii.gz -mas brainmask.nii.gz T1_skull_stripped.nii.gz

recon-allでの処理が完了すると、被験者IDディレクトリ(Subj001)が生成され、このディレクトリ内に処理された結果が保存される。

Subj001/
├── label
├── mri
│   ├── T1.mgz
│   ├── brainmask.auto.mgz
│   ├── brainmask.mgz
│   ├── mri_nu_correct.mni.log
│   ├── mri_nu_correct.mni.log.bak
│   ├── nu.mgz
│   ├── orig
│   │   └── 001.mgz
│   ├── orig.mgz
│   ├── orig_nu.mgz
│   ├── rawavg.mgz
│   ├── talairach_with_skull.log
│   └── transforms
│       ├── bak
│       ├── talairach.auto.xfm
│       ├── talairach.auto.xfm.lta
│       ├── talairach.xfm
│       ├── talairach.xfm.lta
│       ├── talairach_avi.log
│       ├── talairach_avi_QA.log
│       ├── talairach_with_skull.lta
│       └── talsrcimg_to_711-2C_as_mni_average_305_t4_vox2vox.txt
├── scripts
│   ├── build-stamp.txt
│   ├── lastcall.build-stamp.txt
│   ├── patchdir.txt
│   ├── recon-all-status.log
│   ├── recon-all.cmd
│   ├── recon-all.done
│   ├── recon-all.env
│   ├── recon-all.local-copy
│   ├── recon-all.log
│   ├── recon-config.yaml
│   └── unknown-args.txt
├── stats
├── surf
├── tmp
├── touch
│   ├── conform.touch
│   ├── inorm1.touch
│   ├── nu.touch
│   ├── skull.lta.touch
│   ├── skull_strip.touch
│   └── talairach.touch
└── trash

頭蓋除去された画像は、「Subj001/mri/brainmask.mgz」にある。brainmask.mgz画像は、頭蓋除去済みの脳画像であるが、信号値の階調が0~225に圧縮(正規化)されてしまう。そこで、このbrainmask.mgzをマスク画像として扱い、元の3D-T1WIのマスク処理(マスキング)として適用する。

結果

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

【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. 結果

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

【FreeSurfer】FreeSurferを用いたRF/B1バイアス(信号ムラ)補正


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


1. 目的

  • RF/B1バイアス(信号ムラ)補正

2. コマンド

ここでは、FreeSurferの関数であるAntsN4BiasFieldCorrectionFsコマンドを用いて、信号ムラ補正をする。

AntsN4BiasFieldCorrectionFsは、ANTsの関数である”AntsN4BiasFieldCorrection”を基にしたものであり、補正アルゴリズムとしては、ANTs由来のものである。

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

				Help

NAME
	AntsN4BiasFieldCorrectionFs

SYNOPSIS
	AntsN4BiasFieldCorrectionFs [options] -i <invol> -o <outvol>

DESCRIPTION
	Runs N4 (nonparameteric, nonuniform normalization) retrospective bias 
	correction on an image. This programs wraps the 
	AntsN4BiasFieldCorrection utility available in the ANTs package (see 
	http://stnava.github.io/ANTs).

REQUIRED FLAGGED ARGUMENTS
	-i, --input invol
		input volume file

	-o, --output outvol
		corrected volume file

OPTIONAL FLAGGED ARGUMENTS
	--shrink
		resample factor to decrease computation time (default is 4)

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

AntsN4BiasFieldCorrectionFs -i <入力画像> -o <出力画像>

3. 使用例

補正前の3D-T1WI(T1w.nii.gz)に対して、信号ムラ補正をする。

AntsN4BiasFieldCorrectionFs -i T1w.nii.gz -o T1w_biascorrected.nii.gz

処理が完了すると、補正後の3D-T1WI(T1w_biascorrected.nii.gz)が出力される。

ls  # カレントディレクトリのファイルを確認
    T1w.nii.gz    T1w_biascorrected.nii.gz

4. 結果

補正前(上)と補正後(下)を比較すると次の通り。

補正前では頭頂部で比較的低信号、深部灰白質で比較的高信号だったのが、補正後に均一になっている。