usingNeuroAnalyzerimportCairoMakie# Quarto sets a default figure size (672 × 480 px), which overrides the sizes of# NeuroAnalyzer figures: remove itdelete!(CairoMakie.Makie.CURRENT_DEFAULT_THEME, :resolution)usingLinearAlgebra
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):
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].
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:
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 volumectr =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 coordinatesprintln("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 itfunctionorientation(affine) r = affine[1:3, 1:3] ori =""for i in1:3 a =argmax(abs.(r[:, i])) ori *= r[a, i] >0 ? "RAS"[a] :"LPI"[a]endreturn oriendprintln("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 indicesfunctionto_ras(mri) r = mri.affine[1:3, 1:3] perm =invperm([argmax(abs.(r[:, i])) for i in1:3]) flip = [r[d, perm[d]] <0 for d in1:3] v =permutedims(mri.data[:, :, :, 1], perm)for d in1:3 flip[d] && (v =reverse(v; dims = d))endreturn v, perm, flipend# 0-based voxel indices → 1-based indices of the RAS-oriented datafunctionras_index(ijk, v, perm, flip) p = [round(Int, ijk[perm[d]]) +1 for d in1:3]return [flip[d] ? size(v, d) +1- p[d] : p[d] for d in1:3]end
ras_index (generic function with 1 method)
Viewing slices
Three orthogonal slices through the origin of the coordinates:
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:
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.
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: