Skip to content

Instantly share code, notes, and snippets.

@satra
Created December 11, 2011 10:04
Show Gist options
  • Save satra/1459725 to your computer and use it in GitHub Desktop.
Save satra/1459725 to your computer and use it in GitHub Desktop.
freesurfer gifti transformation to native space
#DOES NOT WORK: GIFTI READ/WRITE is broken
import nibabel as nb
import nibabel.gifti as gifti
# load combined file
# created with: mris_convert --combinesurfs lh.pial rh.pial ./pial.gii
surf = gifti.read('pial.gii')
#load orig affine transform
ao = nb.load('orig.nii').get_affine()
# load conformed affine
ac = nb.load('conformed.nii').get_affine()
# create freesurfer conformed volume to surface transform matrix
import numpy as np
M = np.array([[-1,0,0,128],
[0, 0, 1, -128],
[0, -1, 0, 128],
[0,0,0,1]],dtype=np.float32)
# create transform to go to native space
xfm = np.dot(ac, np.linalg.inv(M))
# transform the two data arrays storing left and right vertices
xfmda0 = np.dot(xfm, np.hstack((surf.darrays[0].data, np.ones((surf.darrays[0].data.shape[0],1)))).T)[:3,:].T
xfmda1 = np.dot(xfm, np.hstack((surf.darrays[1].data, np.ones((surf.darrays[1].data.shape[0],1)))).T)[:3,:].T
da = surf.darrays[0]
indtype = da.data.dtype
# set the data
surf.darrays[0] = da.from_array(xfmda0.astype(indtype), da.intent, da.datatype)
surf.darrays[1] = da.from_array(xfmda1.astype(indtype), da.intent, da.datatype)
# write to file
gifti.write(surf, 'xfmpial.gii')
import nibabel as nb
import nibabel.gifti as gifti
# load combined file
# created with: mris_convert --combinesurfs lh.pial rh.pial ./pial.gii
surf = gifti.read('pial.gii')
#load orig affine transform
ao = nb.load('orig.nii').get_affine()
# load conformed affine
ac = nb.load('conformed.nii').get_affine()
# create freesurfer conformed volume to surface transform matrix
import numpy as np
M = np.array([[-1,0,0,128],
[0, 0, 1, -128],
[0, -1, 0, 128],
[0,0,0,1]],dtype=np.float32)
# create transform to go to native space
xfm = np.dot(ac, np.linalg.inv(M))
# transform the two data arrays storing left and right vertices
xfmda0 = np.dot(xfm, np.hstack((surf.darrays[0].data, np.ones((surf.darrays[0].data.shape[0],1)))).T)[:3,:].T
# write directly to vtk
from tvtk.api import tvtk
mesh = tvtk.PolyData(points=xfmda0, polys=surf.darrays[1].data)
w = tvtk.XMLPolyDataWriter(input=mesh, file_name='polydata.vtp')
w.write()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment