Writing FreeSurfer neuroimaging data with freesurferformats

In this document, we show how to write brain imaging data to FreeSurfer binary files.

Writing FreeSurfer neuroimaging data with freesurferformats

Writing 1D morphometry data or other per-vertex information (in MGH, MGZ or curv format)

Morphometry data, or vertex-wise measures, are data that usually describe a measure like cortical thickness or surface area over the cortex. There is one scalar value per vertex of the brain surface mesh. Of course, you could write whatever you want (p-values, effect sizes at the vertex, …), as long as the data is scalar.

The package provides the write.fs.morph function to write any scalar data that does not require metadata like MR acquisition parameters or transforms. With this function, the format gets determined automatically from the file name. In the following example, we load the area and thickness values for a subject and write the product of area and thickness (which is not cortical volume, by the way) to new files in MGH, MGZ and curv format.

Let’s first load the data:

Now we could write our derived data like this:

Writing MGH and MGZ format files with full control over the header

When writing 3D or 4D images, the voxels alone are sometimes not enough: depending on what you intend to do with the data later on, you may want to save metadata like MR acquisition parameters or vox2ras transformation matrices in the file header. This is possible with the write.fs.mgh function, that gives you full control over the MGH header. The two relevant pieces of header data are:

Here is an example that writes a file in MGH format including custom header data:

Note that if and only if you provide a ras2vox_matrix, the ras_good flag will be set to TRUE in the file header. If you do not provide mr_params, they default to all zero.

Writing ‘curv’ format files

You can use write.fs.curv to write arbitrary data in binary curv format. The result is identical to using write.fs.morph with any filename that does not end in mgh or mgz instead.)

It’s worth knowing the if your filename ends with .gz, the file will be written in gzip format.

Writing surface format files

You can use write.fs.surface to write triangular meshes in binary surface format (the format used for files like ‘surf/lh.white’ or ‘surf/rh.pial’). A mesh is defined by a list of vertices and a list of faces.

The vertex indices used to define the faces should be 1-based, as used in R. They will be written 0-based to the file.

Writing label files

Labels can be written with the write.fs.label function. A label is nothing but a list of vertex indices.

Writing color lookup table (LUT) files in ASCII format

The following example uses the write.fs.colortable function to write a colortable: