Skip to content

Instantly share code, notes, and snippets.

@haehn
Forked from satra/trackvis.py
Last active December 17, 2015 13:49
Show Gist options
  • Save haehn/5620382 to your computer and use it in GitHub Desktop.
Save haehn/5620382 to your computer and use it in GitHub Desktop.
import numpy as np
from nibabel import load
import nibabel.trackvis as nibtrk
# filename = "DeterministicTractography/QBALLRecon/hardiO10.trk"
trkfilename = "/software/data/STUT/DTI_TV/PWS04/dtk_35/dti_35.trk" #%hardiO10.trk_cross_streamline_id_20.trk"
trkfilename_out = "newtracks.trk"
bfilename = "/software/data/STUT/DTI_TV/PWS04/dt_recon/lowb.nii"
mrfilename = "/software/data/MIBR/data/PWS04/head.nii"
reg = np.genfromtxt('/software/data/STUT/DTI_TV/PWS04/dt_recon/register.dat',skiprows=4,comments='r')
bimg = load(bfilename)
mrimg = load(mrfilename)
M = np.array([[-1,0,0,128],
[0, 0, 1, -128],
[0, -1, 0, 128],
[0,0,0,1]],dtype=float)
M1 = np.array([[-2,0,0,128],
[0, 0, 2, -64],
[0, -2, 0, 128],
[0,0,0,1]],dtype=float)
s = nibtrk.read(trkfilename)
tracks = s[0]
hdr = s[1]
aff = bimg.get_affine()
#xfm = np.dot(np.dot(np.dot(img2.get_affine(),np.linalg.inv(M)),reg),aff)
xfm = np.dot(mrimg.get_affine(),np.dot(np.linalg.inv(M),np.dot(np.linalg.inv(reg),M1)))
print xfm
A = np.dot(aff[0:3,0:3],np.diag(1./hdr['voxel_size']))
b = aff[0:3,3]
for t in xrange( len( tracks ) ):
track = tracks[t]
xyz = track[0]
new_xyz = (np.dot(A, xyz.T) + b[:,None]).transpose()
newTrack = ( new_xyz, track[1], track[2] )
# replace the old track with the newTrack
tracks[t] = newTrack
# save the warped tracks
nibtrk.write( trkfilename_out, tracks, hdr, points_space='voxel' )
@haehn
Copy link
Author

haehn commented May 21, 2013

@satra I modified your code to use nibabel instead of streamlines.py but alas it does not give good results for me. the old version with streamlines.py did not work at all (I think due to the newer trackvis format - streamlines.py is very old).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment