1. 目的
2. データ準備
3. MIFフォーマットに変換
4. 渦電流および頭部の動き補正
5. 脳マスクの作成
6. 応答関数(Response function)の推定
7. 白質配向分布の推定
8. Tractographyの実行
9. Track Density Imaging (TDI)
1. 目的
2. コマンド
3. 使用例
3.1. 前準備
3.2. テンソルの推定(コマンド:dwi2tensor)
3.3. 拡散定量値の算出(コマンド:tensor2metric)
MRtrixを用いて、拡散テンソルイメージング(DTI)をするには、dwi2tensorとtensor2metricコマンドを用いる。
dwi2tensorは拡散MRI画像からテンソルを推定するコマンドで、tensor2metricは推定したテンソルから拡散定量値を算出するコマンドである。
dwi2tensorのヘルプは、次の通り。
SYNOPSIS
Diffusion (kurtosis) tensor estimation
USAGE
dwi2tensor [ options ] dwi dt
dwi the input dwi image.
dt the output dt image.
DESCRIPTION
By default, the diffusion tensor (and optionally its kurtosis) is fitted
to the log-signal in two steps: firstly, using weighted least-squares
(WLS) with weights based on the empirical signal intensities; secondly, by
further iterated weighted least-squares (IWLS) with weights determined by
the signal predictions from the previous iteration (by default, 2
iterations will be performed). This behaviour can be altered in two ways:
* The -ols option will cause the first fitting step to be performed using
ordinary least-squares (OLS); that is, all measurements contribute equally
to the fit, instead of the default behaviour of weighting based on the
empirical signal intensities.
* The -iter option controls the number of iterations of the IWLS
prodedure. If this is set to zero, then the output model parameters will
be those resulting from the first fitting step only: either WLS by
default, or OLS if the -ols option is used in conjunction with -iter 0.
The tensor coefficients are stored in the output image as follows:
volumes 0-5: D11, D22, D33, D12, D13, D23
If diffusion kurtosis is estimated using the -dkt option, these are stored
as follows:
volumes 0-2: W1111, W2222, W3333
volumes 3-8: W1112, W1113, W1222, W1333, W2223, W2333
volumes 9-11: W1122, W1133, W2233
volumes 12-14: W1123, W1223, W1233
OPTIONS
-ols
perform initial fit using an ordinary least-squares (OLS) fit (see
Description).
-mask image
only perform computation within the specified binary brain mask image.
-b0 image
the output b0 image.
-dkt image
the output dkt image.
-iter integer
number of iterative reweightings for IWLS algorithm (default: 2) (see
Description).
-predicted_signal image
the predicted dwi image.
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.
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.
tensor2metricのヘルプは、次の通り。
SYNOPSIS
Generate maps of tensor-derived parameters
USAGE
tensor2metric [ options ] tensor
tensor the input tensor image.
OPTIONS
-adc image
compute the mean apparent diffusion coefficient (ADC) of the diffusion
tensor. (sometimes also referred to as the mean diffusivity (MD))
-fa image
compute the fractional anisotropy (FA) of the diffusion tensor.
-ad image
compute the axial diffusivity (AD) of the diffusion tensor. (equivalent to
the principal eigenvalue)
-rd image
compute the radial diffusivity (RD) of the diffusion tensor. (equivalent
to the mean of the two non-principal eigenvalues)
-cl image
compute the linearity metric of the diffusion tensor. (one of the three
Westin shape metrics)
-cp image
compute the planarity metric of the diffusion tensor. (one of the three
Westin shape metrics)
-cs image
compute the sphericity metric of the diffusion tensor. (one of the three
Westin shape metrics)
-value image
compute the selected eigenvalue(s) of the diffusion tensor.
-vector image
compute the selected eigenvector(s) of the diffusion tensor.
-num sequence
specify the desired eigenvalue/eigenvector(s). Note that several
eigenvalues can be specified as a number sequence. For example, '1,3'
specifies the principal (1) and minor (3) eigenvalues/eigenvectors
(default = 1).
-modulate choice
specify how to modulate the magnitude of the eigenvectors. Valid choices
are: none, FA, eigval (default = FA).
-mask image
only perform computation within the specified binary brain mask image.
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.
DTI拡散定量値(FA, MD, AD, RD, カラーFA)を計算するための基本的な使い方は、以下の通り。
dwi2tensor <入力画像> <出力画像> tensor2metric -fa <出力画像> -adc <出力画像> -ad <出力画像> -rd <出力画像> -vec <出力画像> tensor.mif
まず、次のファイルを用意する。
. ├── DWI.nii.gz # 拡散MRI ├── DWI_mask.nii.gz ├── bvals # b-values ├── bvecs # b-vectors └── headers.json # ヘッダー情報の入ったJSONファイル
こちらの記事を参考に、拡散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
dwi2tensor)ファイルの用意ができたら、dwi2tensorを次のように実行する
dwi2tensor DWI.mif tensor.mif
mrinfoを使って「tensor.mif」の情報を確認すると、6 volumesのデータであることが分かる。
mrinfo tensor.mif
************************************************
Image name: "tensor.mif"
************************************************
Dimensions: 130 x 130 x 82 x 6
Voxel size: 1.76923 x 1.76923 x 1.8 x 1
Data strides: [ -1 2 3 4 ]
Format: MRtrix
Data type: 32 bit float (little endian)
Intensity scaling: offset = 0, multiplier = 1
Transform: 1 0 0 -109
-0 1 0 -103.7
-0 0 1 -58.57
それぞれのボリュームは、各方向の拡散係数に相当する。
The tensor coefficients are stored in the output image as follows:
volumes 0-5: D11, D22, D33, D12, D13, D23
tensor2metric)先程推定した、「tensor.mif」を使って拡散定量値を算出する。
tensor2metric -fa FA.mif -adc MD.mif -ad AD.mif -rd RD.mif -vec color_FA.mif tensor.mif
DTIの各拡散定量値画像は、以下。

1. 目的
2. コマンド
3. 使用例
3.1. 前準備
3.2. 歪み補正と頭の動き補正
MRtrixを用いて、拡散MRIの歪み・頭の動き・渦電流を補正するには、dwifslpreprocを用いる(古いMRtrixバージョンではdwipreproc)。
dwipreprocは、FSLのtopupとeddyを用いるので、前もってFSLをインストールしておく必要がある。
dwifslpreprocのヘルプは、次の通り。
SYNOPSIS
Perform diffusion image pre-processing using FSL's eddy tool; including
inhomogeneity distortion correction using FSL's topup tool if possible
USAGE
dwifslpreproc [ options ] input output
input The input DWI series to be corrected
output The output corrected image series
DESCRIPTION
This script is intended to provide convenience of use of the FSL software
tools topup and eddy for performing DWI pre-processing, by encapsulating
some of the surrounding image data and metadata processing steps. It is
intended to simply these processing steps for most commonly-used DWI
acquisition strategies, whilst also providing support for some more exotic
acquisitions. The "example usage" section demonstrates the ways in which
the script can be used based on the (compulsory) -rpe_* command-line
options.
The "-topup_options" and "-eddy_options" command-line options allow the
user to pass desired command-line options directly to the FSL commands
topup and eddy. The available options for those commands may vary between
versions of FSL; users can interrogate such by querying the help pages of
the installed software, and/or the FSL online documentation: (topup)
https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/topup/TopupUsersGuide ; (eddy)
https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/eddy/UsersGuide
The script will attempt to run the CUDA version of eddy; if this does not
succeed for any reason, or is not present on the system, the CPU version
will be attempted instead. By default, the CUDA eddy binary found that
indicates compilation against the most recent version of CUDA will be
attempted; this can be over-ridden by providing a soft-link "eddy_cuda"
within your path that links to the binary you wish to be executed.
Note that this script does not perform any explicit registration between
images provided to topup via the -se_epi option, and the DWI volumes
provided to eddy. In some instances (motion between acquisitions) this can
result in erroneous application of the inhomogeneity field during
distortion correction. Use of the -align_seepi option is advocated in this
scenario, which ensures that the first volume in the series provided to
eddy is also the first volume in the series provided to eddy, guaranteeing
alignment. But a prerequisite for this approach is that the image contrast
within the images provided to the -se_epi option must match the b=0 volumes
present within the input DWI series: this means equivalent TE, TR and flip
angle (note that differences in multi-band factors between two acquisitions
may lead to differences in TR).
EXAMPLE USAGES
A basic DWI acquisition, where all image volumes are acquired in a single
protocol with fixed phase encoding:
$ dwifslpreproc DWI_in.mif DWI_out.mif -rpe_none -pe_dir ap -readout_time 0.55
Due to use of a single fixed phase encoding, no EPI distortion correction
can be applied in this case.
DWIs all acquired with a single fixed phase encoding; but additionally a
pair of b=0 images with reversed phase encoding to estimate the
inhomogeneity field:
$ mrcat b0_ap.mif b0_pa.mif b0_pair.mif -axis 3; dwifslpreproc DWI_in.mif DWI_out.mif -rpe_pair -se_epi b0_pair.mif -pe_dir ap -readout_time 0.72 -align_seepi
Here the two individual b=0 volumes are concatenated into a single 4D image
series, and this is provided to the script via the -se_epi option. Note
that with the -rpe_pair option used here, which indicates that the SE-EPI
image series contains one or more pairs of b=0 images with reversed phase
encoding, the FIRST HALF of the volumes in the SE-EPI series must possess
the same phase encoding as the input DWI series, while the second half are
assumed to contain the opposite phase encoding direction but identical
total readout time. Use of the -align_seepi option is advocated as long as
its use is valid (more information in the Description section).
All DWI directions & b-values are acquired twice, with the phase encoding
direction of the second acquisition protocol being reversed with respect to
the first:
$ mrcat DWI_lr.mif DWI_rl.mif DWI_all.mif -axis 3; dwifslpreproc DWI_all.mif DWI_out.mif -rpe_all -pe_dir lr -readout_time 0.66
Here the two acquisition protocols are concatenated into a single DWI
series containing all acquired volumes. The direction indicated via the
-pe_dir option should be the direction of phase encoding used in
acquisition of the FIRST HALF of volumes in the input DWI series; ie. the
first of the two files that was provided to the mrcat command. In this
usage scenario, the output DWI series will contain the same number of image
volumes as ONE of the acquired DWI series (ie. half of the number in the
concatenated series); this is because the script will identify pairs of
volumes that possess the same diffusion sensitisation but reversed phase
encoding, and perform explicit recombination of those volume pairs in such
a way that image contrast in regions of inhomogeneity is determined from
the stretched rather than the compressed image.
Any acquisition scheme that does not fall into one of the example usages
above:
$ mrcat DWI_*.mif DWI_all.mif -axis 3; mrcat b0_*.mif b0_all.mif -axis 3; dwifslpreproc DWI_all.mif DWI_out.mif -rpe_header -se_epi b0_all.mif -align_seepi
With this usage, the relevant phase encoding information is determined
entirely based on the contents of the relevant image headers, and
dwifslpreproc prepares all metadata for the executed FSL commands
accordingly. This can therefore be used if the particular DWI acquisition
strategy used does not correspond to one of the simple examples as
described in the prior examples. This usage is predicated on the headers of
the input files containing appropriately-named key-value fields such that
MRtrix3 tools identify them as such. In some cases, conversion from DICOM
using MRtrix3 commands will automatically extract and embed this
information; however this is not true for all scanner vendors and/or
software versions. In the latter case it may be possible to manually
provide these metadata; either using the -json_import command-line option
of dwifslpreproc, or the -json_import or one of the -import_pe_* command-
line options of MRtrix3's mrconvert command (and saving in .mif format)
prior to running dwifslpreproc.
OPTIONS
-pe_dir PE
Manually specify the phase encoding direction of the input series; can be a
signed axis number (e.g. -0, 1, +2), an axis designator (e.g. RL, PA, IS),
or NIfTI axis codes (e.g. i-, j, k)
-readout_time time
Manually specify the total readout time of the input series (in seconds)
-se_epi image
Provide an additional image series consisting of spin-echo EPI images,
which is to be used exclusively by topup for estimating the inhomogeneity
field (i.e. it will not form part of the output image series)
-align_seepi
Achieve alignment between the SE-EPI images used for inhomogeneity field
estimation, and the DWIs (more information in Description section)
-json_import file
Import image header information from an associated JSON file (may be
necessary to determine phase encoding information)
-topup_options " TopupOptions"
Manually provide additional command-line options to the topup command
(provide a string within quotation marks that contains at least one space,
even if only passing a single command-line option to topup)
-eddy_options " EddyOptions"
Manually provide additional command-line options to the eddy command
(provide a string within quotation marks that contains at least one space,
even if only passing a single command-line option to eddy)
-eddy_mask image
Provide a processing mask to use for eddy, instead of having dwifslpreproc
generate one internally using dwi2mask
-eddy_slspec file
Provide a file containing slice groupings for eddy's slice-to-volume
registration
-eddyqc_text directory
Copy the various text-based statistical outputs generated by eddy, and the
output of eddy_qc (if installed), into an output directory
-eddyqc_all directory
Copy ALL outputs generated by eddy (including images), and the output of
eddy_qc (if installed), into an output directory
Options for specifying the acquisition phase-encoding design; note that one of the -rpe_* options MUST be provided
-rpe_none
Specify that no reversed phase-encoding image data is being provided; eddy
will perform eddy current and motion correction only
-rpe_pair
Specify that a set of images (typically b=0 volumes) will be provided for
use in inhomogeneity field estimation only (using the -se_epi option)
-rpe_all
Specify that ALL DWIs have been acquired with opposing phase-encoding
-rpe_header
Specify that the phase-encoding information can be found in the image
header(s), and that this is the information that the script should use
Options for importing the diffusion gradient table
-grad GRAD
Provide the diffusion gradient table in MRtrix format
-fslgrad bvecs bvals
Provide the diffusion gradient table in FSL bvecs/bvals format
Options for exporting the diffusion gradient table
-export_grad_mrtrix grad
Export the final gradient table in MRtrix format
-export_grad_fsl bvecs bvals
Export the final gradient table in FSL bvecs/bvals format
Additional standard options for Python scripts
-nocleanup
do not delete intermediate files during script execution, and do not delete
scratch directory at script completion.
-scratch /path/to/scratch/
manually specify the path in which to generate the scratch directory.
-continue <ScratchDir> <LastFile>
continue the script from a previous execution; must provide the scratch
directory path, and the name of the last successfully-generated file.
Standard options
-info
display information messages.
-quiet
do not display information messages or progress status. Alternatively, this
can be achieved by setting the MRTRIX_QUIET environment variable to a non-
empty string.
-debug
display debugging messages.
-force
force overwrite of output files.
-nthreads number
use this number of threads in multi-threaded applications (set to 0 to
disable multi-threading).
-config key value (multiple uses permitted)
temporarily set the value of an MRtrix config file entry.
-help
display this information page and exit.
-version
display version information and exit.
基本的な使い方は、以下の通り。
dwifslpreproc <入力画像> <出力画像> [オプション]
位相エンコード方向を、APとPAそれぞれで撮像したデータがあったとする。DICOM形式からNIfTI形式に変換する方法は、以下の記事を参考にするとよい。
. ├── DWI_AP.nii.gz # DW images (PE: AP) ├── DWI_PA.nii.gz # DW images (PE: PA) ├── bvals_AP # b-values (PE: AP) ├── bvals_PA # b-values (PE: PA) ├── bvecs_AP # b-vectors (PE: AP) ├── bvecs_PA # b-vectors (PE: PA) ├── headers_AP.json # DICOM headers (PE: AP) └── headers_PA.json # DICOM headers (PE: PA)
まず、こちらの記事を参考に、拡散MRI(DWI.nii.gz)とそのMPG軸情報(bvecs, bvals)とヘッダー情報(headers.json)をまとめて、MIF形式(DWI.mif)に変換する。
mrconvert -fslgrad bvecs_AP bvals_AP -json_import headers_AP.json DWI_AP.nii.gz DWI_AP.mif # PE: AP mrconvert -fslgrad bvecs_PA bvals_PA -json_import headers_PA.json DWI_PA.nii.gz DWI_PA.mif # PE: PA
次に、mrcatを使ってDWI_AP.mifとDWI_PA.mifをひとつの画像(DWI_all.mif)にまとめる。
オプションの-axis 3は、4次元目のt軸(Volume)方向にまとめるという意味である(MRtrixではAxisを0から数える [i.e., x: 0, y: 1, z: 2, t: 3])。mrcatの詳細は、こちら。
mrcat DWI_AP.mif DWI_PA.mif DWI_all.mif -axis 3
次に、dwiextractを用いて、b=0のみを抽出する。dwiextractの詳細は、こちら。
dwiextract -bzero DWI_all.mif DWI_b0.mif
歪み補正と頭の動き補正をするために、次のコマンドを実行する。
ここで使用した、各オプションは以下。
-rpe_header:位相エンコード情報を読み込む-se_epi:b=0(spin-echo EPI images)を指定-align_seepi:磁場の不均一性場の推定で用いられる、SE-EPI画像とDWIの間の位置合わせを実行dwifslpreproc DWI_all.mif DWI_preproc.mif -rpe_header -se_epi DWI_b0.mif -align_seepi
歪み補正後の画像は、以下。

頭の動き補正後の画像は、以下。


1. 目的
2. コマンド
3. 使用例
3.1. FSLアルゴリズムを用いる場合
3.2. FreeSurferアルゴリズムを用いる場合
4. 結果
MRtrixの5ttgenを用いて、次の5つの組織(five-tissue-type: 5TT)画像を生成する。
5ttgenのヘルプは、次の通り。
SYNOPSIS
Generate a 5TT image suitable for ACT
USAGE
5ttgen [ options ] algorithm ...
algorithm Select the algorithm to be used to complete the script operation;
additional details and options become available once an
algorithm is nominated. Options are: freesurfer, fsl, gif,
hsvs
DESCRIPTION
5ttgen acts as a 'master' script for generating a five-tissue-type (5TT)
segmented tissue image suitable for use in Anatomically-Constrained
Tractography (ACT). A range of different algorithms are available for
completing this task. When using this script, the name of the algorithm to
be used must appear as the first argument on the command-line after
'5ttgen'. The subsequent compulsory arguments and options available depend
on the particular algorithm being invoked.
Each algorithm available also has its own help page, including necessary
references; e.g. to see the help page of the 'fsl' algorithm, type '5ttgen
fsl'.
Options common to all 5ttgen algorithms
-nocrop
Do NOT crop the resulting 5TT image to reduce its size (keep the same
dimensions as the input image)
-sgm_amyg_hipp
Represent the amygdalae and hippocampi as sub-cortical grey matter in the
5TT image
Additional standard options for Python scripts
-nocleanup
do not delete intermediate files during script execution, and do not delete
scratch directory at script completion.
-scratch /path/to/scratch/
manually specify the path in which to generate the scratch directory.
-continue <ScratchDir> <LastFile>
continue the script from a previous execution; must provide the scratch
directory path, and the name of the last successfully-generated file.
Standard options
-info
display information messages.
-quiet
do not display information messages or progress status. Alternatively, this
can be achieved by setting the MRTRIX_QUIET environment variable to a non-
empty string.
-debug
display debugging messages.
-force
force overwrite of output files.
-nthreads number
use this number of threads in multi-threaded applications (set to 0 to
disable multi-threading).
-config key value (multiple uses permitted)
temporarily set the value of an MRtrix config file entry.
-help
display this information page and exit.
-version
display version information and exit.
基本的な使い方は、以下の通り。5ttgenのアルゴリズムは、freesurfer, fsl, gif, hsvsがあるが、ここではfreesurferとfslのアルゴリズムについて使い方を解説する。
5ttgen [アルゴリズム] <入力画像> <出力画像>
FSLアルゴリズムを用いる場合、3D-T1WI(T1w.nii.gz)が必要となる。また、オプションとして3D-T2WIも入力することができる。
5ttgen fsl T1w.nii.gz 5tt.nii.gz
FreeSurferアルゴリズムを用いる場合、Freesurferの生成ファイルであるaparc+aseg.mgz(asegとついたファイル)が必要となる。
FreeSurferの使い方は、こちらの記事を参考にするとよい。
aparc+aseg.mgzが準備できたら、以下のコマンドを実行する。
5ttgen freesurfer aparc+aseg.mgz 5tt.nii.gz
5ttgenで生成された画像は、5ボリュームデータであり、各ボリュームと対応する組織は次の通り。
以下に、FSLとFreeSurferのアルゴリズムを用いて5ttgenした結果(緑)を示す。

1. 目的
2. コマンド
3. 使用例
3.1. 前準備
3.2. 拡散MRIのバイアス(信号ムラ)補正
MRtrixを用いて拡散MRIのバイアス(信号ムラ)補正をするには、dwibiascorrectを使用する。
ここでは、ANTsのN4アルゴリズムを用いたバイアス補正を紹介する。ANTsアルゴリズムを使用する場合は、ANTsを前もってインストールしておく必要がある。
dwibiascorrectのヘルプは、次の通り。
SYNOPSIS
Perform B1 field inhomogeneity correction for a DWI volume series
USAGE
dwibiascorrect [ options ] algorithm ...
algorithm Select the algorithm to be used to complete the script operation;
additional details and options become available once an
algorithm is nominated. Options are: ants, fsl
Options for importing the diffusion gradient table
-grad GRAD
Provide the diffusion gradient table in MRtrix format
-fslgrad bvecs bvals
Provide the diffusion gradient table in FSL bvecs/bvals format
Options common to all dwibiascorrect algorithms
-mask image
Manually provide a mask image for bias field estimation
-bias image
Output the estimated bias field
Additional standard options for Python scripts
-nocleanup
do not delete intermediate files during script execution, and do not delete
scratch directory at script completion.
-scratch /path/to/scratch/
manually specify the path in which to generate the scratch directory.
-continue <ScratchDir> <LastFile>
continue the script from a previous execution; must provide the scratch
directory path, and the name of the last successfully-generated file.
Standard options
-info
display information messages.
-quiet
do not display information messages or progress status. Alternatively, this
can be achieved by setting the MRTRIX_QUIET environment variable to a non-
empty string.
-debug
display debugging messages.
-force
force overwrite of output files.
-nthreads number
use this number of threads in multi-threaded applications (set to 0 to
disable multi-threading).
-config key value (multiple uses permitted)
temporarily set the value of an MRtrix config file entry.
-help
display this information page and exit.
-version
display version information and exit.
基本的な使い方は、以下の通り。
dwibiascorrect ants <入力画像> <出力画像>
まず、こちらの記事を参考に、拡散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
以下のコマンドを実行する。-biasオプションを指定することで、バイアスフィールドを出力することができる。
dwibiascorrect ants DWI.mif DWI_unbiased.mif -bias bias.mif
補正後の画像は、以下。

拡散MRIのノイズ除去には、MRtrixのdwidenoiseを用いる。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 <入力画像> <出力画像>
前処理する前の拡散MRI(DWI.nii.gz)に、dwidenoiseを実行する。
dwidenoise DWI.nii.gz DWI_denoised.nii.gz
処理後の画像は、以下。

1. 目的
2. コマンド
3.使用例
3.1.前準備
3.2.b=0のみを抽出
3.3.b≠0を抽出
3.4.b値ごとに抽出
拡散MRIからb値ごとに画像を抽出するには、MRtrixのdwiextractを用いる。
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以外の拡散強調像を抽出
まず、こちらの記事を参考に、拡散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
オプション-bzeroを指定する。
dwiextract -bzero DWI.mif DWI_b0.mif
b=0の画像のみ抽出される。
mrinfo DWI_b0.mif |grep Dimensions
Dimensions: 130 x 130 x 82 x 1
オプション-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
オプション-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
1. 目的
2. コマンド
3. 使用例
3.1. 前準備
3.2. 拡散MRIのマスク画像の作成
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 <入力画像> <出力画像>
まず、こちらの記事を参考に、拡散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
以下のコマンドを実行する。
dwi2mask DWI.mif DWI_mask.mif
拡散MRIとマスク画像(緑)を重ね合わせてみる。

1. 目的
2. コマンド
3. 使用例
3.1. ボクセルサイズを指定(オプション:-voxel)
3.2. スケールを指定(オプション:-scale))
3.3. ボクセルサイズを指定(オプション:-voxel))
3.4. 目的の解像度を持つ画像を指定(オプション:-template))
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 <目的の解像度を持つ画像> <出力画像> # 目的の解像度を持つ画像を指定
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
-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
-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
-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
-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
1. 目的
2. FSLを用いる場合
2.1. コマンド
2.2. 使用例
3. MRtrixを用いる場合
3.1. コマンド
3.2. 使用例
FSLのfslroiコマンドを用いる。
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数>
例えば、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
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 <軸番号> <残したいボリューム数>
例えば、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で画像の切り取り・マスキングをするには、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で画像の切り取り・マスキングをするには、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画像は以下。

1. 目的
2. FSLを用いる場合
2.1. コマンド
2.2. ノイズ除去(デノイズ)
2.3. 複数のラベルから1部のラベルを抽出
3. MRtrixを用いる場合
3.1. コマンド
3.2. ノイズ除去(デノイズ)
3.3. 複数のラベルから1部のラベルを抽出
FSLのfslmathsを用いる。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> [演算子あるいは入力画像] <出力画像>
ここでは、特にしきい値処理で用いる-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)を重ね合わせてみる。ノイズ部分のマスキングが解消されていることが分かる。

以下のような、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のラベルのみが抽出される。

MRtrixのmrthresholdを用いる。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 [オプション] <入力画像> <出力画像>
例えば、拡散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)を重ね合わせてみる。ノイズ部分のマスキングが解消されていることが分かる。

以下のような、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のラベルのみが抽出される。

FSLにはeddyという拡散MRI画像の渦電流を補正するプログラムが搭載されています。
かつてはeddy_correctというシンプルなプログラムでしたが、
今のeddyは、計算量がとてつもなく大きな(=処理時間がかかる)プログラムとなっています。
Liux版のFSLには、eddy_openmp というCPU版と、eddy_cuda{8.0,9.1}というGPU版があります。
Ubuntu 18.04 が搭載されているLinuxで NVIDIA製のグラフィックボードが搭載されている場合、eddy_cudaを比較的簡単にセットアップできるので紹介します。
注意:NVIDIAのドライバを入れる時点で、ディスプレイの解像度が変になることがあります。現在の実働マシンに使う場合は相当注意しながら行ってください。個々人の環境があまりにも違うのでこの方法で不具合が起こっても責任は負いかねます。(すでに3台のマシンでセットアップを行い問題ないことを確認していますが…)