Magnetic Resonance Imaging

Initialize NeuroAnalyzer
using NeuroAnalyzer
import CairoMakie
# Quarto sets a default figure size (672 × 480 px), which overrides the sizes of
# NeuroAnalyzer figures: remove it
delete!(CairoMakie.Makie.CURRENT_DEFAULT_THEME, :resolution)
using LinearAlgebra

Magnetic Resonance Imaging (MRI) gives a three-dimensional image of the head. In EEG and MEG analysis, the anatomical (T1-weighted) MRI of the subject is used to:

  • build head models: surfaces of the scalp, skull and brain for source localization,
  • coregister electrode or sensor positions with the anatomy (fiducials, head shape),
  • show source estimates and electrode positions on the brain of the subject.

NeuroAnalyzer stores an MRI volume as an MRI object:

Field Description
data voxel values, x × y × z × volumes (Float32), in the orientation of the file
affine 4 × 4 matrix mapping voxel indices to coordinates in mm
frame coordinate frame of these coordinates: :ras, :tkr, :mni, :head, :unknown
header file name and fields of the original file header
history processing history

An anatomical image has one volume; functional (fMRI, BOLD) or diffusion images have many volumes (time points or gradient directions) along the fourth dimension.

Importing NIfTI files

NIfTI (.nii, gzip-compressed .nii.gz) is the most common file format of MRI volumes: it is used by FSL, SPM, AFNI, FreeSurfer, ANTs, MNE-Python and the BIDS standard. Both NIfTI-1 and NIfTI-2 files are imported with import_nifti().

The example volume is the T1-weighted MRI of the subject of the MNE-Python visual_92_categories dataset (written by FreeSurfer):

t1 = import_nifti("files/mri/T1.nii.gz")
NeuroAnalyzer MRI
  size: 256 × 256 × 176 voxels, 1 volume
  voxel size: 1.0 × 1.0 × 1.0 mm
  frame: ras
  file: files/mri/T1.nii.gz
println("size: ", size(t1.data))
println("voxel size (mm): ", round.(voxel_size(t1); digits = 3))
println("frame: ", t1.frame)
println("data type in the file: ", t1.header[:data_type])
println("description: ", t1.header[:description])
println("range: ", extrema(t1.data))
size: (256, 256, 176, 1)
voxel size (mm): [1.0, 1.0, 1.0]
frame: ras
data type in the file: Float32
description: FreeSurfer May 25 2011
range: (0.0f0, 1384.0f0)

Voxel values are scaled with the slope and intercept stored in the file header (scl_slope, scl_inter), so t1.data holds the actual intensities, whatever the data type of the file (e.g. 8-bit or 16-bit integers).

Voxels and coordinates

Each voxel has three indices \((i, j, k)\). The affine matrix \(A\) maps them to coordinates \((x, y, z)\) in mm:

\[ \begin{bmatrix} x \\ y \\ z \\ 1 \end{bmatrix} = A \begin{bmatrix} i \\ j \\ k \\ 1 \end{bmatrix} \]

The upper-left \(3 \times 3\) part of \(A\) holds the rotation and the voxel size, the last column holds the translation. As in the NIfTI standard, the voxel indices start at 0: the Julia index of voxel \((i, j, k)\) is data[i + 1, j + 1, k + 1, 1].

round.(t1.affine; digits = 3)
4×4 Matrix{Float64}:
  0.013  0.036   0.999   -91.751
 -0.999  0.034   0.012   149.515
  0.033  0.999  -0.036  -122.291
  0.0    0.0     0.0       1.0

NIfTI files may store two affines: the sform (any affine transformation, e.g. to a template space) and the qform (rotation and translation only, usually the scanner coordinates). import_nifti() uses the sform if it is present and the qform otherwise; both are kept in the header:

println("affine from: ", t1.header[:affine_source])
println("sform code: ", t1.header[:sform_code])
println("qform code: ", t1.header[:qform_code])
affine from: sform
sform code: 1
qform code: 1

The code tells the coordinate frame of the affine: 1 is the scanner coordinates (:ras), 4 is the MNI-152 template space (:mni).

RAS coordinates: the \(x\) axis points to the Right, \(y\) to the Anterior (front) and \(z\) to the Superior (top) of the head.

Converting between voxel indices and coordinates:

# voxel indices (0-based) → coordinates (mm)
vox2mm(mri, ijk) = (mri.affine * [ijk; 1])[1:3]
# coordinates (mm) → voxel indices (0-based, fractional)
mm2vox(mri, xyz) = (inv(mri.affine) * [xyz; 1])[1:3]

# the centre of the volume
ctr = collect((size(t1.data)[1:3] .- 1) ./ 2)
println("centre voxel: ", ctr)
println("centre (mm): ", round.(vox2mm(t1, ctr); digits = 1))
# the origin of the coordinates
println("origin voxel: ", round.(mm2vox(t1, [0, 0, 0]); digits = 1))
centre voxel: [127.5, 127.5, 87.5]
centre (mm): [2.0, 27.5, 6.1]
origin voxel: [154.7, 120.4, 85.4]

Orientation

The voxel axes do not have to be aligned with the RAS axes: the order in which the scanner acquires and stores the slices differs between scanners and software. The orientation of a volume is described by three letters: the anatomical direction in which each voxel axis (\(i\), \(j\), \(k\)) points.

# anatomical direction of each voxel axis: the RAS axis closest to it
function orientation(affine)
    r = affine[1:3, 1:3]
    ori = ""
    for i in 1:3
        a = argmax(abs.(r[:, i]))
        ori *= r[a, i] > 0 ? "RAS"[a] : "LPI"[a]
    end
    return ori
end
println("orientation: ", orientation(t1.affine))
orientation: PSR

In this volume, the index \(i\) increases towards the back of the head (Posterior), \(j\) towards the top (Superior) and \(k\) to the Right.

import_nifti() does not resample or reorient the voxels: data is in the orientation of the file and the affine gives the coordinates. To display slices, the voxel axes can be permuted and flipped to the closest RAS orientation (without interpolation):

# voxel data permuted and flipped to the closest RAS orientation and the
# permutation and flips needed to convert voxel indices
function to_ras(mri)
    r = mri.affine[1:3, 1:3]
    perm = invperm([argmax(abs.(r[:, i])) for i in 1:3])
    flip = [r[d, perm[d]] < 0 for d in 1:3]
    v = permutedims(mri.data[:, :, :, 1], perm)
    for d in 1:3
        flip[d] && (v = reverse(v; dims = d))
    end
    return v, perm, flip
end

# 0-based voxel indices → 1-based indices of the RAS-oriented data
function ras_index(ijk, v, perm, flip)
    p = [round(Int, ijk[perm[d]]) + 1 for d in 1:3]
    return [flip[d] ? size(v, d) + 1 - p[d] : p[d] for d in 1:3]
end
ras_index (generic function with 1 method)

Viewing slices

Three orthogonal slices through the origin of the coordinates:

function plot_slices(v, p; colormap = :grays)
    fig = CairoMakie.Figure(size = (900, 330))
    views = (("sagittal", "P → A", "I → S", v[p[1], :, :]),
             ("coronal", "L → R", "I → S", v[:, p[2], :]),
             ("axial", "L → R", "P → A", v[:, :, p[3]]))
    for (n, (title, xl, yl, s)) in enumerate(views)
        ax = CairoMakie.Axis(fig[1, n];
                             title = title,
                             xlabel = xl,
                             ylabel = yl,
                             aspect = CairoMakie.DataAspect())
        CairoMakie.heatmap!(ax, s; colormap = colormap)
    end
    return fig
end

v, perm, flip = to_ras(t1)
p = ras_index(mm2vox(t1, [0, 0, 0]), v, perm, flip)
println("origin in the RAS-oriented data: ", p)
origin in the RAS-oriented data: [86, 101, 121]
plot_slices(v, p)

Axes are in voxels of the reoriented data; the left hemisphere is on the left (neurological convention).

Importing DICOM series

DICOM is the format in which MRI scanners and hospital archives (PACS) store images. A classic DICOM MRI exam is a folder with one file per slice; slices of one acquisition form a series, an exam (study) has several series (localizer, T1, T2, FLAIR, …).

dicom_series() lists the series of a folder (searched recursively), of the folder of a DICOMDIR file or of a single file. The example is a T1-weighted MPRAGE (1 mm, Siemens Prisma 3 T) of the dcm_qa_mprage validation dataset of dcm2niix:

df = dicom_series("files/mri/dcm_qa_mprage")
df[:, [:number, :description, :modality, :files, :rows, :columns]]
1×6 DataFrame
Row number description modality files rows columns
Int64 String String Int64 Int64 Int64
1 6 T1_mprage_ns_sag_p2 MR 192 256 256

import_dicom() loads one series (series: series number or UID; not needed if the folder has one series):

t1d = import_dicom("files/mri/dcm_qa_mprage")
NeuroAnalyzer MRI
  size: 256 × 256 × 192 voxels, 1 volume
  voxel size: 1.0 × 1.0 × 1.0 mm
  frame: ras
  file: files/mri/dcm_qa_mprage
println("scanner: ", t1d.header[:manufacturer], " ", t1d.header[:model],
        " (", t1d.header[:field_strength], " T)")
println("series: ", t1d.header[:series_description])
println("TR (s): ", t1d.header[:tr])
println("TE (s): ", t1d.header[:te])
println("orientation: ", orientation(t1d.affine))
scanner: SIEMENS Prisma_fit (3.0 T)
series: T1_mprage_ns_sag_p2
TR (s): 2.25
TE (s): 0.00411
orientation: PIR

The slices are ordered by their position in space (not by the file names or the instance numbers) and the DICOM patient coordinates (LPS: x to the Left, y to the Posterior) are converted to RAS. Patient data (name, ID, birth date) are not copied to the header.

v, perm, flip = to_ras(t1d)
p = ras_index(mm2vox(t1d, [0, 0, 0]), v, perm, flip)
plot_slices(v, p)

import_dicom() reads uncompressed single-frame files (one image per file). Compressed files (JPEG, JPEG-LS, JPEG 2000, RLE), multi-frame (enhanced) files and Siemens mosaics (fMRI, DWI) can be converted to NIfTI with dcm2niix and loaded with import_nifti().

Template volumes

Volumes in a template space (e.g. MNI-152) share the same coordinates for all subjects. The inner skull mask of SPM is stored in the MNI space, but its sform code is 2 (“aligned to an anatomical image”), so the frame is unknown. The frame can be given when importing:

iskull = import_nifti("files/mri/mri-test-nifti.nii"; frame = :mni)
NeuroAnalyzer MRI
  size: 91 × 109 × 91 voxels, 1 volume
  voxel size: 2.0 × 2.0 × 2.0 mm
  frame: mni
  file: files/mri/mri-test-nifti.nii
println("orientation: ", orientation(iskull.affine))
println("sform code: ", iskull.header[:sform_code])
println("voxels inside the skull: ", count(>(0.5), iskull.data))
orientation: RAS
sform code: 2
voxels inside the skull: 255940
v, perm, flip = to_ras(iskull)
p = ras_index(mm2vox(iskull, [0, 0, 0]), v, perm, flip)
plot_slices(v, p)