def show_tract(segmented_tract, color_positive, segmented_tract_negative, color_negative, out_path): """Visualization of the segmented tract. """ affine = utils.affine_for_trackvis(voxel_size=np.array([1.25, 1.25, 1.25])) bundle_native = transform_streamlines(segmented_tract, np.linalg.inv(affine)) bundle_nativeNeg = transform_streamlines(segmented_tract_negative, np.linalg.inv(affine)) renderer = window.Renderer() stream_actor2 = actor.line(bundle_native, colors=color_positive, linewidth=0.1) stream_actorNeg = actor.line(bundle_nativeNeg, colors=color_negative, opacity=0.01, linewidth=0.1) renderer.set_camera(position=(408.85, -26.23, 92.12), focal_point=(0.42, -14.03, 0.82), view_up=(-0.09, 0.85, 0.51)) bar = actor.scalar_bar() renderer.add(stream_actor2) renderer.add(stream_actorNeg) renderer.add(bar) window.show(renderer, size=(1920, 1039), reset_camera=False) renderer.camera_info() """Take a snapshot of the window and save it """ window.record(renderer, out_path=out_path, size=(1920, 1039))
def voxelCount(): tractography, header = trackvis.read(T_A_filename) tractography = [streamline[0] for streamline in tractography] affine = utils.affine_for_trackvis(voxel_size=np.array([2, 2, 2])) print("---Number of voxel---") print(len(streamline_mapping(T_A, affine=affine).keys())) tkinter.messagebox.showinfo( "Voxel", len(streamline_mapping(T_A, affine=affine).keys()))
def show_tract(segmented_tract, color): """Visualization of the segmented tract. """ affine=utils.affine_for_trackvis(voxel_size=np.array([1.25,1.25,1.25])) bundle_native = transform_streamlines(segmented_tract, np.linalg.inv(affine)) renderer = window.Renderer() stream_actor = actor.line(bundle_native, linewidth=0.1) bar = actor.scalar_bar() renderer.add(stream_actor) renderer.add(bar) window.show(renderer, size=(600, 600), reset_camera=False) """Take a snapshot of the window and save it """ window.record(renderer, out_path='bundle2.1.png', size=(600, 600))
def convert_fibs(inp, outp, parcellation): label_nii = nib.load(parcellation) label_data = label_nii.get_data() fiber_npz = np.load(inp) fibers = fiber_npz[fiber_npz.keys()[0]] voxel_size = label_nii.header.get_zooms() shape = label_data.shape affine = label_nii.affine trackvis_header = nib.trackvis.empty_header() trackvis_header['voxel_size'] = voxel_size trackvis_header['dim'] = shape trackvis_header['voxel_order'] = "RAS" trackvis_point_space = utils.affine_for_trackvis(voxel_size) trk = utils.move_streamlines(fibers, trackvis_point_space, input_space=np.eye(4)) trk = list(trk) for_save = [(sl, None, None) for sl in trk] nib.trackvis.write(outp, for_save, trackvis_header)
import nibabel as nib # Save density map dm_img = nib.Nifti1Image(dm.astype("int16"), hardi_img.affine) dm_img.to_filename("lr-superiorfrontal-dm.nii.gz") # Make a trackvis header so we can save streamlines voxel_size = labels_img.header.get_zooms() trackvis_header = nib.trackvis.empty_header() trackvis_header['voxel_size'] = voxel_size trackvis_header['dim'] = shape trackvis_header['voxel_order'] = "RAS" # Move streamlines to "trackvis space" trackvis_point_space = utils.affine_for_trackvis(voxel_size) lr_sf_trk = utils.move_streamlines(lr_superiorfrontal_track, trackvis_point_space, input_space=affine) lr_sf_trk = list(lr_sf_trk) # Save streamlines for_save = [(sl, None, None) for sl in lr_sf_trk] nib.trackvis.write("lr-superiorfrontal.trk", for_save, trackvis_header) """ Let's take a moment here to consider the representation of streamlines used in dipy. Streamlines are a path though the 3d space of an image represented by a set of points. For these points to have a meaningful interpretation, these points must be given in a known coordinate system. The ``affine`` attribute of the ``streamline_generator`` object specifies the coordinate system of the points with respect to the voxel indices of the input data.
T_A_filename = 'F:\Thesis\Resources\\alldata\\201111_uf.right.trk' threshold_short_streamlines = 0.0 color=colors.red T_A, hdr = loadtrkfile(T_A_filename, threshold_short_streamlines=threshold_short_streamlines) countstreamlines() showhistogram() tractography,header=trackvis.read(T_A_filename) tractography = [streamline[0] for streamline in tractography] affine=utils.affine_for_trackvis(voxel_size=np.array([2,2,2])) print ("---Number of voxel---") print (len(streamline_mapping(T_A,affine=affine).keys())) show_tract(T_A, color)
def test_affine_for_trackvis(): voxel_size = np.array([1., 2, 3.]) affine = affine_for_trackvis(voxel_size) origin = np.dot(affine, [0, 0, 0, 1]) assert_array_almost_equal(origin[:3], voxel_size / 2)
def label_streamlines_density(streamlines, labels, affine, f_name, img, label_img): """ .. figure:: connectivity.png :align: center **Connectivity of Corpus Callosum** .. include:: ../links_names.inc """ shape = labels.shape dm = utils.density_map(streamlines, shape, affine=affine) sum = 0 count = 0 for i in dm: for j in i: for k in j: if (k != 0): sum = sum + k count += 1 density = sum * 1.0 / count print density """ To do that, we will use tools available in [nibabel](http://nipy.org/nibabel) """ # Save density map dm_img = nib.Nifti1Image(dm.astype("int16"), img.get_affine()) dm_img.to_filename(f_name + "-dm.nii.gz") # Make a trackvis header so we can save streamlines voxel_size = label_img.get_header().get_zooms() trackvis_header = nib.trackvis.empty_header() trackvis_header['voxel_size'] = voxel_size trackvis_header['dim'] = shape trackvis_header['voxel_order'] = "RAS" # Move streamlines to "trackvis space" trackvis_point_space = utils.affine_for_trackvis(voxel_size) lr_sf_trk = utils.move_streamlines(streamlines, trackvis_point_space, input_space=affine) lr_sf_trk = list(lr_sf_trk) """ # Save streamlines for_save = [(sl, None, None) for sl in lr_sf_trk] nib.trackvis.write(f_name+"_label1.trk", for_save, trackvis_header) """ """ import tractconverter as tc density_file = f_name+"_label1.trk" input_format=tc.detect_format(density_file) input=input_format(density_file) output=tc.FORMATS['vtk'].create(density_file+".vtk",input.hdr) tc.convert(input,output) """ """ Let's take a moment here to consider the representation of streamlines used in dipy. Streamlines are a path though the 3d space of an image represented by a set of points. For these points to have a meaningful interpretation, these points must be given in a known coordinate system. The ``affine`` attribute of the ``streamline_generator`` object specifies the coordinate system of the points with respect to the voxel indices of the input data. ``trackvis_point_space`` specifies the trackvis coordinate system with respect to the same indices. The ``move_streamlines`` function returns a new set of streamlines from an existing set of streamlines in the target space. The target space and the input space must be specified as affine transformations with respect to the same reference [#]_. If no input space is given, the input space will be the same as the current representation of the streamlines, in other words the input space is assumed to be ``np.eye(4)``, the 4-by-4 identity matrix. All of the functions above that allow streamlines to interact with volumes take an affine argument. This argument allows these functions to work with streamlines regardless of their coordinate system. For example even though we moved our streamlines to "trackvis space", we can still compute the density map as long as we specify the right coordinate system. """ dm_trackvis = utils.density_map(lr_sf_trk, shape, affine=trackvis_point_space) assert np.all(dm == dm_trackvis) return dm, density """ This means that streamlines can interact with any image volume, for example a high resolution structural image, as long as one can register that image to the diffusion images and calculate the coordinate system with respect to that image. """ """
import nibabel as nib # Save density map dm_img = nib.Nifti1Image(dm.astype("int16"), hardi_img.get_affine()) dm_img.to_filename("lr-superiorfrontal-dm.nii.gz") # Make a trackvis header so we can save streamlines voxel_size = labels_img.get_header().get_zooms() trackvis_header = nib.trackvis.empty_header() trackvis_header['voxel_size'] = voxel_size trackvis_header['dim'] = shape trackvis_header['voxel_order'] = "RAS" # Move streamlines to "trackvis space" trackvis_point_space = utils.affine_for_trackvis(voxel_size) lr_sf_trk = utils.move_streamlines(lr_superiorfrontal_track, trackvis_point_space, input_space=affine) lr_sf_trk = list(lr_sf_trk) # Save streamlines for_save = [(sl, None, None) for sl in lr_sf_trk] nib.trackvis.write("lr-superiorfrontal.trk", for_save, trackvis_header) """ Let's take a moment here to consider the representation of streamlines used in dipy. Streamlines are a path though the 3d space of an image represented by a set of points. For these points to have a meaningful interpretation, these points must be given in a known coordinate system. The ``affine`` attribute of the ``streamline_generator`` object specifies the coordinate system of the points with respect to the voxel indices of the input data.
def compute_correlation(data, distance, prototype_policies, num_prototypes, iterations, verbose=False, size_limit=1000): global tracks_t,ids_l,data_original,tracks_s,id_t,tracks_n,a_ind, tracks_subsample print "Computing distance matrix and similarity matrix (original space):", data_original = data if data.shape[0] > size_limit: print print "Datset too big: subsampling to %s entries only!" % size_limit data = data[np.random.permutation(data.shape[0])[:size_limit], :] od = distance(data, data) print od.shape original_distances = squareform(od) #original_distances2 = squareform(od) """ my code """ affine=utils.affine_for_trackvis(voxel_size=np.array([2,2,2])) lengths = list(length(data_original)) lengths=np.array(lengths) temp=np.where(lengths>10)[0] l=np.argsort(lengths)[::-1][:len(temp)] data_original_temp=data_original[l] a= streamline_mapping_new_step(data_original_temp, affine=affine) tracks_subsample=data_original_temp[a] print len(tracks_subsample) """ my code """ rho = np.zeros((len(prototype_policies), len(num_prototypes),iterations)) for m, prototype_policy in enumerate(prototype_policies): print prototype_policy for j, num_proto in enumerate(num_prototypes): print "number of prototypes:", num_proto, " - ", for k in range(iterations): print k, stdout.flush() if verbose: print("Generating %s prototypes as" % num_proto), # Note that we use the original dataset here, not the subsampled one! if prototype_policy=='random': if verbose: print("random subset of the initial data.") prototype_idx = np.random.permutation(data_original.shape[0])[:num_proto] prototype = [data_original[i] for i in prototype_idx] elif prototype_policy=='sff': prototype_idx = subset_furthest_first(data_original, num_proto, distance) prototype = [data_original[i] for i in prototype_idx] elif prototype_policy=='fft': prototype_idx = furthest_first_traversal( tracks_subsample, num_proto, distance) prototype = [ tracks_subsample[i] for i in prototype_idx] else: raise Exception if verbose: print("Computing dissimilarity matrix.") data_dissimilarity = distance(data, prototype) if verbose: print("Computing distance matrix (dissimilarity space).") dissimilarity_distances = pdist(data_dissimilarity, metric='euclidean') rho[m,j,k] = correlation(original_distances, dissimilarity_distances)[0] print return rho
def compute_correlation(data, distance, prototype_policies, num_prototypes, iterations, verbose=False, size_limit=1000): global tracks_t, ids_l, data_original, tracks_s, id_t, tracks_n, a_ind, tracks_subsample print "Computing distance matrix and similarity matrix (original space):", data_original = data if data.shape[0] > size_limit: print print "Datset too big: subsampling to %s entries only!" % size_limit data = data[np.random.permutation(data.shape[0])[:size_limit], :] od = distance(data, data) print od.shape original_distances = squareform(od) #original_distances2 = squareform(od) """ my code """ affine = utils.affine_for_trackvis(voxel_size=np.array([2, 2, 2])) lengths = list(length(data_original)) lengths = np.array(lengths) temp = np.where(lengths > 10)[0] l = np.argsort(lengths)[::-1][:len(temp)] data_original_temp = data_original[l] a = streamline_mapping_new_step(data_original_temp, affine=affine) tracks_subsample = data_original_temp[a] print len(tracks_subsample) """ my code """ rho = np.zeros((len(prototype_policies), len(num_prototypes), iterations)) for m, prototype_policy in enumerate(prototype_policies): print prototype_policy for j, num_proto in enumerate(num_prototypes): print "number of prototypes:", num_proto, " - ", for k in range(iterations): print k, stdout.flush() if verbose: print("Generating %s prototypes as" % num_proto), # Note that we use the original dataset here, not the subsampled one! if prototype_policy == 'random': if verbose: print("random subset of the initial data.") prototype_idx = np.random.permutation( data_original.shape[0])[:num_proto] prototype = [data_original[i] for i in prototype_idx] elif prototype_policy == 'sff': prototype_idx = subset_furthest_first( data_original, num_proto, distance) prototype = [data_original[i] for i in prototype_idx] elif prototype_policy == 'fft': prototype_idx = furthest_first_traversal( tracks_subsample, num_proto, distance) prototype = [tracks_subsample[i] for i in prototype_idx] else: raise Exception if verbose: print("Computing dissimilarity matrix.") data_dissimilarity = distance(data, prototype) if verbose: print("Computing distance matrix (dissimilarity space).") dissimilarity_distances = pdist(data_dissimilarity, metric='euclidean') rho[m, j, k] = correlation(original_distances, dissimilarity_distances)[0] print return rho
import numpy as np import nibabel as nib from dipy.tracking import utils from dipy.tracking.utils import length from mapping_test import * """ Reading the track """ streams1,hdr1=nib.trackvis.read('/home/nusrat/dataset_trackvis/101.trk') tracks = np.array([s[0] for s in streams1], dtype=np.object) """ affine for converting the streamline cordinate with the voxel cordinate """ affine=utils.affine_for_trackvis(voxel_size=np.array([2,2,2])) """ length function from the dipy https://github.com/nipy/dipy/blob/master/dipy/tracking/_utils.py """ lengths = list(length(tracks)) """ fiter the whole tractography--like we are not interested the track less than 10. """ lengths=np.array(lengths) l=np.where(lengths>10)[0] """ rearrange the tracktography """
def label_streamlines_density(streamlines,labels,affine,f_name,img,label_img): """ .. figure:: connectivity.png :align: center **Connectivity of Corpus Callosum** .. include:: ../links_names.inc """ shape = labels.shape dm = utils.density_map(streamlines, shape, affine=affine) sum=0 ;count=0 for i in dm: for j in i: for k in j: if (k != 0): sum=sum+k count += 1 density = sum*1.0/count print density """ To do that, we will use tools available in [nibabel](http://nipy.org/nibabel) """ # Save density map dm_img = nib.Nifti1Image(dm.astype("int16"), img.get_affine()) dm_img.to_filename(f_name+"-dm.nii.gz") # Make a trackvis header so we can save streamlines voxel_size = label_img.get_header().get_zooms() trackvis_header = nib.trackvis.empty_header() trackvis_header['voxel_size'] = voxel_size trackvis_header['dim'] = shape trackvis_header['voxel_order'] = "RAS" # Move streamlines to "trackvis space" trackvis_point_space = utils.affine_for_trackvis(voxel_size) lr_sf_trk = utils.move_streamlines(streamlines, trackvis_point_space, input_space=affine) lr_sf_trk = list(lr_sf_trk) """ # Save streamlines for_save = [(sl, None, None) for sl in lr_sf_trk] nib.trackvis.write(f_name+"_label1.trk", for_save, trackvis_header) """ """ import tractconverter as tc density_file = f_name+"_label1.trk" input_format=tc.detect_format(density_file) input=input_format(density_file) output=tc.FORMATS['vtk'].create(density_file+".vtk",input.hdr) tc.convert(input,output) """ """ Let's take a moment here to consider the representation of streamlines used in dipy. Streamlines are a path though the 3d space of an image represented by a set of points. For these points to have a meaningful interpretation, these points must be given in a known coordinate system. The ``affine`` attribute of the ``streamline_generator`` object specifies the coordinate system of the points with respect to the voxel indices of the input data. ``trackvis_point_space`` specifies the trackvis coordinate system with respect to the same indices. The ``move_streamlines`` function returns a new set of streamlines from an existing set of streamlines in the target space. The target space and the input space must be specified as affine transformations with respect to the same reference [#]_. If no input space is given, the input space will be the same as the current representation of the streamlines, in other words the input space is assumed to be ``np.eye(4)``, the 4-by-4 identity matrix. All of the functions above that allow streamlines to interact with volumes take an affine argument. This argument allows these functions to work with streamlines regardless of their coordinate system. For example even though we moved our streamlines to "trackvis space", we can still compute the density map as long as we specify the right coordinate system. """ dm_trackvis = utils.density_map(lr_sf_trk, shape, affine=trackvis_point_space) assert np.all(dm == dm_trackvis) return dm,density """ This means that streamlines can interact with any image volume, for example a high resolution structural image, as long as one can register that image to the diffusion images and calculate the coordinate system with respect to that image. """ """