Skip to content

Instantly share code, notes, and snippets.

@ofgulban
Created November 14, 2016 15:49
Show Gist options
  • Save ofgulban/26e8ec2988d3ee81c8bf9e3aea4aad6a to your computer and use it in GitHub Desktop.
Save ofgulban/26e8ec2988d3ee81c8bf9e3aea4aad6a to your computer and use it in GitHub Desktop.
Add Freesurfer labels from different subjects in the average mesh (fsaverage).
"""Add freesurfer labels similar to 'fslmaths -add'.
Use an .mgh file to read relevant information such as headers or number of
vertices.
Note: Freesurfer operations can be performed on .mgh format without
getting unrecognized data type error.
"""
import numpy as np
from nibabel import save
from nibabel import freesurfer as fs
# path of the output file
outfile = '/path/to/your/subject/label_operations/lh.file'
# mgh format is more useful, freesurfer operations can be on on this file
mgh = fs.mghformat.load(
'/path/to/your/subject/fsaverage/surf/lh.orig.avg.area.mgh')
# names of the rois
names = ['/path/to/your/subject_1/file_lh_roi.label',
'/path/to/your/subject_2/file_lh_roi.label',
'/path/to/your/subject_3/file_lh_roi.label',
'/path/to/your/subject_4/file_lh_roi.label']
# one example statistical surface file to get the number of vertices
surf_map = mgh.get_data()
surf_map = surf_map * 0 # start with all zeros
for i in range(len(names)):
temp = np.zeros(surf_map.size)
i_roi = fs.read_label(names[i])
temp[i_roi] = 1
surf_map[:, 0, 0] = surf_map[:, 0, 0] + temp
# save as mgh
out = fs.MGHImage(surf_map, mgh.affine, mgh.header)
save(out, outfile + '.mgh')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment