def visualize(streamlines_A, streamlines_B, mappingAB, line='line', shift=np.array([0.0, 0.0, 200.0]), color_A=fvtk.colors.white, color_B=fvtk.colors.green, color_line=fvtk.colors.yellow): assert(len(mappingAB) == len(streamlines_A)) assert(mappingAB.max() <= len(streamlines_B)) if line == 'line': line = fvtk.line linewidth = 2.0 linekwargs = {'linewidth':linewidth} elif line == 'tube': line = fvtk.streamtube linewidth = 1.0 linekwargs = {'linewidth':linewidth, 'lod':False} else: raise Exception if color_A == 'auto': color_A = line_colors(streamlines_A) if color_B == 'auto': color_B = line_colors(streamlines_B) streamlines_B_shifted = np.array([s + shift for s in streamlines_B]) midpointA = [s[int(s.shape[0] / 2)] for s in streamlines_A] midpointB = [s[int(s.shape[0] / 2)] for s in streamlines_B_shifted] ren = fvtk.ren() fvtk.add(ren, line(streamlines_A.tolist(), colors=color_A, **linekwargs)) fvtk.add(ren, line(streamlines_B_shifted.tolist(), colors=color_B, **linekwargs)) fvtk.add(ren, fvtk.line(zip(midpointA, midpointB), colors=color_line, opacity=0.5, linewidth=0.5)) fvtk.show(ren)
def label_streamlines(streamlines,labels,labels_Value,affine,hdr,f_name,data_path): cc_slice=labels==labels_Value cc_streamlines = utils.target(streamlines, labels, affine=affine) cc_streamlines = list(cc_streamlines) other_streamlines = utils.target(streamlines, cc_slice, affine=affine, include=False) other_streamlines = list(other_streamlines) assert len(other_streamlines) + len(cc_streamlines) == len(streamlines) print ("num of roi steamlines is %d",len(cc_streamlines)) # Make display objects color = line_colors(cc_streamlines) cc_streamlines_actor = fvtk.line(cc_streamlines, line_colors(cc_streamlines)) cc_ROI_actor = fvtk.contour(cc_slice, levels=[1], colors=[(1., 1., 0.)], opacities=[1.]) # Add display objects to canvas r = fvtk.ren() fvtk.add(r, cc_streamlines_actor) fvtk.add(r, cc_ROI_actor) # Save figures fvtk.record(r, n_frames=1, out_path=f_name+'_roi.png', size=(800, 800)) fvtk.camera(r, [-1, 0, 0], [0, 0, 0], viewup=[0, 0, 1]) fvtk.record(r, n_frames=1, out_path=f_name+'_roi.png', size=(800, 800)) """""" csd_streamlines_trk = ((sl, None, None) for sl in cc_streamlines) csd_sl_fname = f_name+'_roi_streamline.trk' nib.trackvis.write(csd_sl_fname, csd_streamlines_trk, hdr, points_space='voxel') #nib.save(nib.Nifti1Image(FA, img.get_affine()), 'FA_map2.nii.gz') print('Saving "_roi_streamline.trk" sucessful.') import tractconverter as tc input_format=tc.detect_format(csd_sl_fname) input=input_format(csd_sl_fname) output=tc.FORMATS['vtk'].create(csd_sl_fname+".vtk",input.hdr) tc.convert(input,output) return cc_streamlines
def show_streamlines(streamlines, cmap='orient', opacity=1., r=None): if r is None: ren = fvtk.ren() else: ren = r if cmap == 'orient': colors = line_colors(streamlines) line_actor = fvtk.line(streamlines, colors, opacity=opacity) fvtk.add(ren, line_actor) if r is None: fvtk.show(ren) else: return ren
def createVtkPng(source, anatomical, roi): import vtk from dipy.viz.colormap import line_colors from dipy.viz import fvtk target = source.replace(".trk",".png") roiImage= nibabel.load(roi) anatomicalImage = nibabel.load(anatomical) sourceImage = [s[0] for s in nibabel.trackvis.read(source, points_space='voxel')[0]] try: sourceActor = fvtk.streamtube(sourceImage, line_colors(sourceImage)) roiActor = fvtk.contour(roiImage.get_data(), levels=[1], colors=[(1., 1., 0.)], opacities=[1.]) anatomicalActor = fvtk.slicer(anatomicalImage.get_data(), voxsz=(1.0, 1.0, 1.0), plane_i=None, plane_j=None, plane_k=[65], outline=False) except ValueError: return False sourceActor.RotateX(-70) sourceActor.RotateY(2.5) sourceActor.RotateZ(185) roiActor.RotateX(-70) roiActor.RotateY(2.5) roiActor.RotateZ(185) anatomicalActor.RotateX(-70) anatomicalActor.RotateY(2.5) anatomicalActor.RotateZ(185) ren = fvtk.ren() fvtk.add(ren, sourceActor) fvtk.add(ren, roiActor) fvtk.add(ren, anatomicalActor) fvtk.record(ren, out_path=target, size=(1200, 1200), n_frames=1, verbose=True, cam_pos=(90.03, 118.33, 700.59)) return target
def show_gt_streamlines(streamlines, radii, cmap='orient', r=None): if cmap is None: np.random.seed(42) colors = np.random.rand(len(streamlines), 3) if cmap == 'orient': colors = line_colors(streamlines) if r is None: ren = fvtk.ren() else: ren = r for i in range(len(streamlines)): line_actor = fvtk.line(streamlines[i], colors[i], linewidth=(radii[i, 1] ** 2) / 2.) fvtk.add(ren, line_actor) label_actor = fvtk.label(ren, text=str(np.round(radii[i, 1], 2)), pos=(streamlines[i][0]), scale=(.8, .8, .8), color=(colors[i])) fvtk.add(ren, label_actor) label_actor_id = fvtk.label(ren, text='[' + str(i) + ']', pos=(streamlines[i][-1]), scale=(.8, .8, .8), color=(colors[i])) fvtk.add(ren, label_actor_id) if r is None: fvtk.show(ren) else: return ren
def runStream(csd_peaks, roi_file, roi_label=1, output_file="tracts.dpy", ang_thr=45., a_low=0.2, step_size=0.1, seeds_per_voxel=30): img = nib.load(roi_file) roidata = img.get_data() p = np.asarray(np.where(roidata == roi_label)) p = p.transpose() seed_points = None for i in p: points = np.random.uniform(size=[seeds_per_voxel,3]) + (i-0.5) if seed_points is None: seed_points = points else: seed_points = np.concatenate([seed_points, points], axis=0) sphere = get_sphere('symmetric724') print "seed eudx tractography" eu = EuDX(csd_peaks.peak_values, csd_peaks.peak_indices, odf_vertices=sphere.vertices, step_sz=step_size, seeds=seed_points, ang_thr=ang_thr, a_low=a_low) csa_streamlines_mult_peaks = [streamline for streamline in eu] ren = fvtk.ren() fvtk.add(ren, fvtk.line(csa_streamlines_mult_peaks, line_colors(csa_streamlines_mult_peaks))) fvtk.show(ren) dpw = Dpy(output_file, 'w') dpw.write_tracks(csa_streamlines_mult_peaks) return csa_streamlines_mult_peaks
# Enables/disables interactive visualization interactive = False # Initialization of LocalTracking. The computation happens in the next step. streamlines_generator = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=.5) # Generate streamlines object streamlines = Streamlines(streamlines_generator) # Prepare the display objects. color = line_colors(streamlines) if window.have_vtk: streamlines_actor = actor.line(streamlines, line_colors(streamlines)) # Create the 3D display. r = window.Renderer() r.add(streamlines_actor) # Save still images for this static example. Or for interactivity use window.record(r, n_frames=1, out_path='deterministic.png', size=(800, 800)) if interactive: window.show(r) """ .. figure:: deterministic.png :align: center
streamliness' (or a 'candidate connectome'): """ """ Let's visualize the initial candidate group of streamlines in 3D, relative to the anatomical structure of this brain: """ from dipy.viz.colormap import line_colors from dipy.viz import fvtk candidate_streamlines_actor = fvtk.streamtube(candidate_sl, line_colors(candidate_sl)) cc_ROI_actor = fvtk.contour(cc_slice, levels=[1], colors=[(1., 1., 0.)], opacities=[1.]) vol_actor = fvtk.slicer(t1_data, voxsz=(1.0, 1.0, 1.0), plane_i=[40], plane_j=None, plane_k=[35], outline=False) # Add display objects to canvas ren = fvtk.ren() fvtk.add(ren, candidate_streamlines_actor) fvtk.add(ren, cc_ROI_actor) fvtk.add(ren, vol_actor) fvtk.record(ren, n_frames=1, out_path='life_candidates.png', size=(800, 800)) """ .. figure:: life_candidates.png
csa_streamlines_trk = ((sl, None, None) for sl in csa_streamlines) csa_sl_fname = 'csa_streamline.trk' nib.trackvis.write(csa_sl_fname, csa_streamlines_trk, hdr, points_space='voxel') """ Visualize the streamlines with fvtk (python vtk is required). """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors r = fvtk.ren() fvtk.add(r, fvtk.line(csa_streamlines, line_colors(csa_streamlines))) print('Saving illustration as tensor_tracks.png') fvtk.record(r, n_frames=1, out_path='csa_tracking.png', size=(600, 600)) """ .. figure:: csa_tracking.png :align: center **Deterministic streamlines with EuDX on ODF peaks field modulated by GFA**. It is also possible to use EuDX with multiple ODF peaks. Which is very helpful when tracking in crossing areas. """
""" ren = window.Renderer() """ Every streamline will be coloured according to its orientation """ from dipy.viz.colormap import line_colors """ `actor.line` creates a streamline actor for streamline visualization and `ren.add` adds this actor to the scene """ ren.add(actor.streamtube(tensor_streamlines, line_colors(tensor_streamlines))) print('Saving illustration as tensor_tracks.png') ren.SetBackground(1, 1, 1) window.record(ren, out_path='tensor_tracks.png', size=(600, 600)) # Enables/disables interactive visualization interactive = False if interactive: window.show(ren) """ .. figure:: tensor_tracks.png :align: center Deterministic streamlines with EuDX on a Tensor Field.
def test_contour_from_roi(): # Render volume renderer = window.renderer() data = np.zeros((50, 50, 50)) data[20:30, 25, 25] = 1. data[25, 20:30, 25] = 1. affine = np.eye(4) surface = actor.contour_from_roi(data, affine, color=np.array([1, 0, 1]), opacity=.5) renderer.add(surface) renderer.reset_camera() renderer.reset_clipping_range() # window.show(renderer) # Test binarization renderer2 = window.renderer() data2 = np.zeros((50, 50, 50)) data2[20:30, 25, 25] = 1. data2[35:40, 25, 25] = 1. affine = np.eye(4) surface2 = actor.contour_from_roi(data2, affine, color=np.array([0, 1, 1]), opacity=.5) renderer2.add(surface2) renderer2.reset_camera() renderer2.reset_clipping_range() # window.show(renderer2) arr = window.snapshot(renderer, 'test_surface.png', offscreen=True) arr2 = window.snapshot(renderer2, 'test_surface2.png', offscreen=True) report = window.analyze_snapshot(arr, find_objects=True) report2 = window.analyze_snapshot(arr2, find_objects=True) npt.assert_equal(report.objects, 1) npt.assert_equal(report2.objects, 2) # test on real streamlines using tracking example from dipy.data import read_stanford_labels from dipy.reconst.shm import CsaOdfModel from dipy.data import default_sphere from dipy.direction import peaks_from_model from dipy.tracking.local import ThresholdTissueClassifier from dipy.tracking import utils from dipy.tracking.local import LocalTracking from dipy.viz.colormap import line_colors hardi_img, gtab, labels_img = read_stanford_labels() data = hardi_img.get_data() labels = labels_img.get_data() affine = hardi_img.get_affine() white_matter = (labels == 1) | (labels == 2) csa_model = CsaOdfModel(gtab, sh_order=6) csa_peaks = peaks_from_model(csa_model, data, default_sphere, relative_peak_threshold=.8, min_separation_angle=45, mask=white_matter) classifier = ThresholdTissueClassifier(csa_peaks.gfa, .25) seed_mask = labels == 2 seeds = utils.seeds_from_mask(seed_mask, density=[1, 1, 1], affine=affine) # Initialization of LocalTracking. # The computation happens in the next step. streamlines = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=2) # Compute streamlines and store as a list. streamlines = list(streamlines) # Prepare the display objects. streamlines_actor = actor.line(streamlines, line_colors(streamlines)) seedroi_actor = actor.contour_from_roi(seed_mask, affine, [0, 1, 1], 0.5) # Create the 3d display. r = window.ren() r2 = window.ren() r.add(streamlines_actor) arr3 = window.snapshot(r, 'test_surface3.png', offscreen=True) report3 = window.analyze_snapshot(arr3, find_objects=True) r2.add(streamlines_actor) r2.add(seedroi_actor) arr4 = window.snapshot(r2, 'test_surface4.png', offscreen=True) report4 = window.analyze_snapshot(arr4, find_objects=True) # assert that the seed ROI rendering is not far # away from the streamlines (affine error) npt.assert_equal(report3.objects, report4.objects)
Finally, we can bring it all together using ``LocalTracking``. We will then display the resulting streamlines using the fvtk module. """ from dipy.tracking.local import LocalTracking from dipy.viz import fvtk from dipy.viz.colormap import line_colors # Initialization of LocalTracking. The computation happens in the next step. streamlines = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=.5) # Compute streamlines and store as a list. streamlines = list(streamlines) # Prepare the display objects. color = line_colors(streamlines) if fvtk.have_vtk: streamlines_actor = fvtk.line(streamlines, line_colors(streamlines)) # Create the 3d display. r = fvtk.ren() fvtk.add(r, streamlines_actor) # Save still images for this static example. Or for interactivity use # fvtk.show fvtk.record(r, n_frames=1, out_path='deterministic.png', size=(800, 800)) """ .. figure:: deterministic.png
""" Let's visualize the initial candidate group of streamlines in 3D, relative to the anatomical structure of this brain: """ from dipy.viz.colormap import line_colors from dipy.viz import window, actor # Enables/disables interactive visualization interactive = False candidate_streamlines_actor = actor.streamtube(candidate_sl, line_colors(candidate_sl)) cc_ROI_actor = actor.contour_from_roi(cc_slice, color=(1., 1., 0.), opacity=0.5) vol_actor = actor.slicer(t1_data) vol_actor.display(x=40) vol_actor2 = vol_actor.copy() vol_actor2.display(z=35) # Add display objects to canvas ren = window.Renderer() ren.add(candidate_streamlines_actor) ren.add(cc_ROI_actor) ren.add(vol_actor) ren.add(vol_actor2)
Save the streamlines. """ csa_streamlines_trk = ((sl, None, None) for sl in csa_streamlines) csa_sl_fname = 'csa_prob_streamline.trk' nib.trackvis.write(csa_sl_fname, csa_streamlines_trk, hdr) """ Visualize the streamlines with fvtk (python vtk is required). """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors r = fvtk.ren() fvtk.add(r, fvtk.line(csa_streamlines, line_colors(csa_streamlines))) print('Saving illustration as csa_prob_tracks.png') fvtk.record(r, n_frames=1, out_path='csa_prob_tracks.png', size=(600, 600)) """ .. figure:: csa_prob_tracks.png :align: center **Probabilistic streamlines applied on an ODF field modulated by GFA**. """
def dwi_deterministic_tracing(image, bvecs, bvals, wm, seeds, fibers, prune_length=3, plot=False, verbose=False): # Pipeline transcribed from: # http://nipy.org/dipy/examples_built/introduction_to_basic_tracking.html # Load Images dwi_loaded = nib.load(image) dwi_data = dwi_loaded.get_data() wm_loaded = nib.load(wm) wm_data = wm_loaded.get_data() seeds_loaded = nib.load(seeds) seeds_data = seeds_loaded.get_data() # Load B-values & B-vectors # NB. Use aligned b-vecs if providing eddy-aligned data bvals, bvecs = read_bvals_bvecs(bvals, bvecs) gtab = gradient_table(bvals, bvecs) # Establish ODF model csa_model = CsaOdfModel(gtab, sh_order=6) csa_peaks = peaks_from_model(csa_model, dwi_data, default_sphere, relative_peak_threshold=0.8, min_separation_angle=45, mask=wm_data) # Classify tissue for high FA and create seeds # (Putting this inside a looped try-block to handle fuzzy failures) classifier = ThresholdTissueClassifier(csa_peaks.gfa, 0.25) seeds = wrap_fuzzy_failures(utils.seeds_from_mask, args=[seeds_data], kwargs={"density": [2, 2, 2], "affine": np.eye(4)}, errortype=ValueError, failure_threshold=5, verbose=verbose) # Perform deterministic tracing # (Putting this inside a looped try-block to handle fuzzy failures) streamlines_generator = wrap_fuzzy_failures(LocalTracking, args=[csa_peaks, classifier, seeds], kwargs={"affine": np.eye(4), "step_size": 0.5}, errortype=ValueError, failure_threshold=5, verbose=verbose) streamlines = wrap_fuzzy_failures(Streamlines, args=[streamlines_generator], kwargs={}, errortype=IndexError, failure_threshold=5, verbose=verbose) # Prune streamlines streamlines = ArraySequence([strline for strline in streamlines if len(strline) > prune_length]) # Save streamlines save_trk(fibers + ".trk", streamlines, dwi_loaded.affine, shape=wm_data.shape, vox_size=wm_loaded.header.get_zooms()) # Visualize fibers if plot and have_fury: from dipy.viz import window, actor, colormap as cmap color = cmap.line_colors(streamlines) streamlines_actor = actor.line(streamlines, color) # Create the 3D display. r = window.Renderer() r.add(streamlines_actor) # Save still image. window.record(r, n_frames=1, out_path=fibers + ".png", size=(800, 800))
""" Let's visualize the initial candidate group of streamlines in 3D, relative to the anatomical structure of this brain: """ from dipy.viz import window, actor, colormap as cmap # Enables/disables interactive visualization interactive = False candidate_streamlines_actor = actor.streamtube(candidate_sl, cmap.line_colors(candidate_sl)) cc_ROI_actor = actor.contour_from_roi(cc_slice, color=(1., 1., 0.), opacity=0.5) vol_actor = actor.slicer(t1_data) vol_actor.display(x=40) vol_actor2 = vol_actor.copy() vol_actor2.display(z=35) # Add display objects to canvas ren = window.Renderer() ren.add(candidate_streamlines_actor) ren.add(cc_ROI_actor) ren.add(vol_actor) ren.add(vol_actor2)
def life(dwifile, bvecsfile, bvalsfile, tractogramfile, outdir, display_tracks=False, verbose=0): """ Linear fascicle evaluation (LiFE) Evaluating the results of tractography algorithms is one of the biggest challenges for diffusion MRI. One proposal for evaluation of tractography results is to use a forward model that predicts the signal from each of a set of streamlines, and then fit a linear model to these simultaneous prediction. Parameters ---------- dwifile: str the path to the diffusion dataset. bvecsfile: str the path to the diffusion b-vectors. bvalsfile: str the path to the diffusion b-values. tractogramfile: str the path to the tractogram. outdir: str the destination folder. display_tracks: bool, default False if True render the tracks. verbose: int, default 0 the verbosity level. Returns ------- life_weights_file: str a file containing the fiber track weights. life_weights_snap: str a snap with the distrubution of weights. spatial_error_file: str the model root mean square error. tracks_snap: str a snap with the tracks. """ # Load diffusion data and tractogram bvecs = numpy.loadtxt(bvecsfile) bvals = numpy.loadtxt(bvalsfile) gtab = gradient_table(bvals, bvecs) im = nibabel.load(dwifile) data = im.get_data() trk = nibabel.streamlines.load(tractogramfile) if verbose > 0: print("[info] Diffusion shape: {0}".format(data.shape)) print("[info] Number of tracks: {0}".format(len(trk.streamlines))) # Express the tractogram in voxel coordiantes inv_affine = numpy.linalg.inv(trk.affine) trk = [ numpy.dot( numpy.concatenate( ( streamline, numpy.ones( (len(streamline), 1) ) ), axis=1 ), inv_affine) for streamline in trk.streamlines] trk = [track[..., :3] for track in trk] # Create a viewer tracks_snap = None if display_tracks: nb_tracks = len(trk) if nb_tracks < 5000: downsampling = 1 else: downsampling = nb_tracks // 5000 tracks_snap = os.path.join(outdir, "tracks.png") streamlines_actor = fvtk.line(trk[::downsampling], line_colors(trk[::downsampling])) vol_actor = fvtk.slicer(data[..., 0]) vol_actor.display(data.shape[0] // 2, None, None) ren = fvtk.ren() fvtk.add(ren, streamlines_actor) fvtk.add(ren, vol_actor) fvtk.record(ren, n_frames=1, out_path=tracks_snap, size=(800, 800)) if verbose > 1: fvtk.show(ren) # Fit the Life model and save the associated weights fiber_model = dpilife.FiberModel(gtab) fiber_fit = fiber_model.fit(data, trk, affine=numpy.eye(4)) life_weights = fiber_fit.beta life_weights_file = os.path.join(outdir, "life_weights.txt") numpy.savetxt(life_weights_file, life_weights) life_weights_snap = os.path.join(outdir, "life_weights.png") fig, ax = plt.subplots(1) ax.hist(life_weights, bins=100, histtype="step") ax.set_xlabel("Fiber weights") ax.set_ylabel("# Fibers") fig.savefig(life_weights_snap) # Invert the model and predict back either the data that was used to fit # the model: compute the prediction error of the diffusion-weighted data # and calculate the root of the mean squared error. model_predict = fiber_fit.predict() model_error = model_predict - fiber_fit.data model_rmse = numpy.sqrt(numpy.mean(model_error[:, 10:] ** 2, -1)) data_rmse = numpy.ones(data.shape[:3]) * numpy.nan data_rmse[fiber_fit.vox_coords[:, 0], fiber_fit.vox_coords[:, 1], fiber_fit.vox_coords[:, 2]] = model_rmse model_error_file = os.path.join(outdir, "model_rmse.nii.gz") error_im = nibabel.Nifti1Image(data_rmse, im.affine) nibabel.save(error_im, model_error_file) # As a baseline against which we can compare, we assume that the weight # for each streamline is equal to zero. This produces the naive prediction # of the mean of the signal in each voxel. life_weights_baseline = numpy.zeros(life_weights.shape[0]) pred_weighted = numpy.reshape( opt.spdot(fiber_fit.life_matrix, life_weights_baseline), (fiber_fit.vox_coords.shape[0], numpy.sum(~gtab.b0s_mask))) mean_pred = numpy.empty( (fiber_fit.vox_coords.shape[0], gtab.bvals.shape[0])) S0 = fiber_fit.b0_signal # Since the fitting is done in the demeaned S/S0 domain, we need to add # back the mean and then multiply by S0 in every voxels. mean_pred[..., gtab.b0s_mask] = S0[:, None] mean_pred[..., ~gtab.b0s_mask] = ( (pred_weighted + fiber_fit.mean_signal[:, None]) * S0[:, None]) mean_error = mean_pred - fiber_fit.data mean_rmse = numpy.sqrt(numpy.mean(mean_error ** 2, -1)) data_rmse = numpy.ones(data.shape[:3]) * numpy.nan data_rmse[fiber_fit.vox_coords[:, 0], fiber_fit.vox_coords[:, 1], fiber_fit.vox_coords[:, 2]] = mean_rmse mean_error_file = os.path.join(outdir, "mean_rmse.nii.gz") error_im = nibabel.Nifti1Image(data_rmse, im.affine) nibabel.save(error_im, mean_error_file) # Compute the improvment array data_rmse = numpy.ones(data.shape[:3]) * numpy.nan data_rmse[fiber_fit.vox_coords[:, 0], fiber_fit.vox_coords[:, 1], fiber_fit.vox_coords[:, 2]] = mean_rmse - model_rmse improvment_error_file = os.path.join(outdir, "improvment_rmse.nii.gz") error_im = nibabel.Nifti1Image(data_rmse, im.affine) nibabel.save(error_im, improvment_error_file) return (life_weights_file, life_weights_snap, model_error_file, mean_error_file, improvment_error_file, tracks_snap)
all_streamlines_threshold_classifier = LocalTracking(dg, threshold_classifier, seeds, affine, step_size=.5, return_all=True) save_trk("deterministic_threshold_classifier_all.trk", all_streamlines_threshold_classifier, affine, labels.shape) streamlines = Streamlines(all_streamlines_threshold_classifier) if have_fury: window.clear(ren) ren.add(actor.line(streamlines, cmap.line_colors(streamlines))) window.record(ren, out_path='all_streamlines_threshold_classifier.png', size=(600, 600)) if interactive: window.show(ren) """ .. figure:: all_streamlines_threshold_classifier.png :align: center **Deterministic tractography using a thresholded fractional anisotropy.** """ """ Binary Tissue Classifier ------------------------ A binary mask can be used to define where the tracking stops. The binary
csa_sl_fname = 'csa_streamline.trk' nib.trackvis.write(csa_sl_fname, csa_streamlines_trk, hdr, points_space='voxel') """ Visualize the streamlines with fvtk (python vtk is required). """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors r = fvtk.ren() fvtk.add(r, fvtk.line(csa_streamlines, line_colors(csa_streamlines))) print('Saving illustration as tensor_tracks.png') fvtk.record(r, n_frames=1, out_path='csa_tracking.png', size=(600, 600)) """ .. figure:: csa_tracking.png :align: center **Deterministic streamlines with EuDX on ODF peaks field modulated by GFA**. It is also possible to use EuDX with multiple ODF peaks, which is very helpful when tracking in crossing areas. """ eu = EuDX(csapeaks.peak_values,
seeds, affine, max_cross=1, step_size=step_size, maxlen=1000, pft_back_tracking_dist=2, pft_front_tracking_dist=1, particle_count=15, return_all=False) streamlines = Streamlines(pft_streamline_generator) sft = StatefulTractogram(streamlines, hardi_img, Space.RASMM) save_trk(sft, "tractogram_pft.trk") if has_fury: r = window.Renderer() r.add(actor.line(streamlines, colormap.line_colors(streamlines))) window.record(r, out_path='tractogram_pft.png', size=(800, 800)) if interactive: window.show(r) """ .. figure:: tractogram_pft.png :align: center **Corpus Callosum using particle filtering tractography** """ # Local Probabilistic Tractography prob_streamline_generator = LocalTracking(dg, cmc_criterion,
lesion mask, or electrode mask). """ # Make a corpus callosum seed mask for tracking seed_mask = labels == 2 seeds = utils.seeds_from_mask(seed_mask, density=[1, 1, 1], affine=affine) # Make a streamline bundle model of the corpus callosum ROI connectivity streamlines = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=2) streamlines = Streamlines(streamlines) # Visualize the streamlines and the Path Length Map base ROI # (in this case also the seed ROI) streamlines_actor = actor.line(streamlines, cmap.line_colors(streamlines)) surface_opacity = 0.5 surface_color = [0, 1, 1] seedroi_actor = actor.contour_from_roi(seed_mask, affine, surface_color, surface_opacity) ren = window.Renderer() ren.add(streamlines_actor) ren.add(seedroi_actor) """ If you set interactive to True (below), the rendering will pop up in an interactive window. """ interactive = False if interactive:
cc_slice = labels == 2 cc_streamlines = utils.target(streamlines, affine, cc_slice) cc_streamlines = Streamlines(cc_streamlines) other_streamlines = utils.target(streamlines, affine, cc_slice, include=False) other_streamlines = Streamlines(other_streamlines) assert len(other_streamlines) + len(cc_streamlines) == len(streamlines) from dipy.viz import window, actor, colormap as cmap # Enables/disables interactive visualization interactive = False # Make display objects color = cmap.line_colors(cc_streamlines) cc_streamlines_actor = actor.line(cc_streamlines, cmap.line_colors(cc_streamlines)) cc_ROI_actor = actor.contour_from_roi(cc_slice, color=(1., 1., 0.), opacity=0.5) vol_actor = actor.slicer(t1_data) vol_actor.display(x=40) vol_actor2 = vol_actor.copy() vol_actor2.display(z=35) # Add display objects to canvas r = window.Renderer() r.add(vol_actor) r.add(vol_actor2)
other_streamlines = utils.target(streamlines, cc_slice, affine=affine, include=False) other_streamlines = list(other_streamlines) assert len(other_streamlines) + len(cc_streamlines) == len(streamlines) """ We can use some of dipy's visualization tools to display the ROI we targeted above and all the streamlines that pass though that ROI. The ROI is the yellow region near the center of the axial image. """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors # Make display objects color = line_colors(cc_streamlines) cc_streamlines_actor = fvtk.line(cc_streamlines, line_colors(cc_streamlines)) cc_ROI_actor = fvtk.contour(cc_slice, levels=[1], colors=[(1., 1., 0.)], opacities=[1.]) # Add display objects to canvas r = fvtk.ren() fvtk.add(r, cc_streamlines_actor) fvtk.add(r, cc_ROI_actor) # Save figures fvtk.record(r, n_frames=1, out_path='corpuscallosum_axial.png', size=(800, 800)) fvtk.camera(r, [-1, 0, 0], [0, 0, 0], viewup=[0, 0, 1]) fvtk.record(r, n_frames=1, out_path='corpuscallosum_sagittal.png', size=(800, 800))
streamlines = list(streamline_generator) # to include only longer streamlines, so we visualize lesser amount of tract, for hardware reasons # part for changing including streamlines only longer than particular length, here 50 from dipy.tracking.metrics import length longer_streamlines = [] for tract in streamlines: if length(tract)>50.0: longer_streamlines.append(tract) # Streamlines visualization from dipy.viz import fvtk from dipy.viz.colormap import line_colors # Make display objects streamlines_actor = fvtk.line(longer_streamlines, line_colors(longer_streamlines)) # Add display objects to canvas r = fvtk.ren() fvtk.add(r, streamlines_actor) # Save figure fvtk.camera(r, [-1, 0, 0], [0, 0, 0], viewup=[0, 0, 1]) fvtk.record(r, n_frames=1, out_path='streamlines_saggital.png',size=(800, 800))
vox_size=np.array([2., 2., 2.]), shape=csapeaks.gfa.shape[:3]) """ Visualize the streamlines with `dipy.viz` module (python vtk is required). """ from dipy.viz import window, actor from dipy.viz.colormap import line_colors # Enables/disables interactive visualization interactive = False ren = window.Renderer() ren.add(actor.line(csa_streamlines, line_colors(csa_streamlines))) print('Saving illustration as tensor_tracks.png') window.record(ren, out_path='csa_tracking.png', size=(600, 600)) if interactive: window.show(ren) """ .. figure:: csa_tracking.png :align: center Deterministic streamlines with EuDX on ODF peaks field modulated by GFA. It is also possible to use EuDX with multiple ODF peaks, which is very helpful when tracking in crossing areas.
from dipy.viz import colormap from dipy.viz import actor, window subsamp_sls = Streamlines() for i in range(np.shape(data_new)[0]): tmp = data_new[i] tmp = zero_remove(tmp) #tmp = tmp[~np.all(tmp == 0, axis=-1)] #tmp = np.around(tmp, decimals=0) subsamp_sls.append(tmp) color = colormap.line_colors(subsamp_sls) streamlines_actor = actor.line(subsamp_sls, colormap.line_colors(subsamp_sls)) # Create the 3D display. scene = window.Scene() scene.add(streamlines_actor) window.show(scene) #%%
""" ren = fvtk.ren() """ Every streamline will be coloured according to its orientation """ from dipy.viz.colormap import line_colors """ fvtk.line adds a streamline actor for streamline visualization and fvtk.add adds this actor in the scene """ fvtk.add(ren, fvtk.streamtube(tensor_streamlines, line_colors(tensor_streamlines))) print('Saving illustration as tensor_tracks.png') ren.SetBackground(1, 1, 1) fvtk.record(ren, n_frames=1, out_path='tensor_tracks.png', size=(600, 600)) """ .. figure:: tensor_tracks.png :align: center **Deterministic streamlines with EuDX on a Tensor Field**. .. include:: ../links_names.inc """
def tracking(image, bvecs, bvals, wm, seeds, fibers, prune_length=3, rseed=42, plot=False, proba=False, verbose=False): # Pipelines transcribed from: # https://dipy.org/documentation/1.1.1./examples_built/tracking_introduction_eudx/#example-tracking-introduction-eudx # https://dipy.org/documentation/1.1.1./examples_built/tracking_probabilistic/ # Load Images dwi_loaded = nib.load(image) dwi_data = dwi_loaded.get_fdata() wm_loaded = nib.load(wm) wm_data = wm_loaded.get_fdata() seeds_loaded = nib.load(seeds) seeds_data = seeds_loaded.get_fdata() seeds = utils.seeds_from_mask(seeds_data, dwi_loaded.affine, density=2) # Load B-values & B-vectors # NB. Use aligned b-vecs if providing eddy-aligned data bvals, bvecs = read_bvals_bvecs(bvals, bvecs) gtab = gradient_table(bvals, bvecs) csa_model = CsaOdfModel(gtab, sh_order=6) # Set stopping criterion gfa = csa_model.fit(dwi_data, mask=wm_data).gfa stop_criterion = ThresholdStoppingCriterion(gfa, .25) if proba: # Establish ODF model response, ratio = auto_response(gtab, dwi_data, roi_radius=10, fa_thr=0.7) csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6) csd_fit = csd_model.fit(dwi_data, mask=wm_data) # Create Probabilisitic direction getter fod = csd_fit.odf(default_sphere) pmf = fod.clip(min=0) prob_dg = ProbabilisticDirectionGetter.from_pmf(pmf, max_angle=30., sphere=default_sphere) # Use the probabilisitic direction getter as the dg dg = prob_dg else: # Establish ODF model csa_peaks = peaks_from_model(csa_model, dwi_data, default_sphere, relative_peak_threshold=0.8, min_separation_angle=45, mask=wm_data) # Use the CSA peaks as the dg dg = csa_peaks # Create generator and perform tracing s_generator = LocalTracking(dg, stop_criterion, seeds, dwi_loaded.affine, 0.5, random_seed=rseed) streamlines = Streamlines(s_generator) # Prune streamlines streamlines = ArraySequence( [strline for strline in streamlines if len(strline) > prune_length]) sft = StatefulTractogram(streamlines, dwi_loaded, Space.RASMM) # Save streamlines save_trk(sft, fibers + ".trk") # Visualize fibers if plot and has_fury: from dipy.viz import window, actor, colormap as cmap # Create the 3D display. r = window.Renderer() r.add(actor.line(streamlines, cmap.line_colors(streamlines))) window.record(r, out_path=fibers + '.png', size=(800, 800))
""" Next, we will create a visualization of these streamlines, relative to this subject's T1-weighted anatomy: """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors from dipy.data import read_stanford_t1 from dipy.tracking.utils import move_streamlines from numpy.linalg import inv t1 = read_stanford_t1() t1_data = t1.get_data() t1_aff = t1.get_affine() color = line_colors(streamlines) """ To speed up visualization, we will select a random sub-set of streamlines to display. This is particularly important, if you track from seeds throughout the entire white matter, generating many streamlines. In this case, for demonstration purposes, we subselect 900 streamlines. """ from dipy.tracking.streamline import select_random_set_of_streamlines plot_streamlines = select_random_set_of_streamlines(streamlines, 900) streamlines_actor = fvtk.streamtube(list(move_streamlines(plot_streamlines, inv(t1_aff))), line_colors(streamlines)) vol_actor = fvtk.slicer(t1_data, voxsz=(1.0, 1.0, 1.0), plane_i=[40], plane_j=None, plane_k=[35], outline=False)
""" """ Let's visualize the initial candidate group of streamlines in 3D, relative to the anatomical structure of this brain: """ from dipy.viz.colormap import line_colors from dipy.viz import window, actor # Enables/disables interactive visualization interactive = False candidate_streamlines_actor = actor.streamtube(candidate_sl, line_colors(candidate_sl)) cc_ROI_actor = actor.contour_from_roi(cc_slice, color=(1., 1., 0.), opacity=0.5) vol_actor = actor.slicer(t1_data) vol_actor.display(x=40) vol_actor2 = vol_actor.copy() vol_actor2.display(z=35) # Add display objects to canvas ren = window.Renderer() ren.add(candidate_streamlines_actor) ren.add(cc_ROI_actor) ren.add(vol_actor)
""" Create a scene. """ ren = window.Renderer() """ Every streamline will be coloured according to its orientation """ from dipy.viz.colormap import line_colors """ `actor.line` creates a streamline actor for streamline visualization and `ren.add` adds this actor to the scene """ ren.add(actor.streamtube(tensor_streamlines, line_colors(tensor_streamlines))) print('Saving illustration as tensor_tracks.png') ren.SetBackground(1, 1, 1) window.record(ren, out_path='tensor_tracks.png', size=(600, 600)) # Enables/disables interactive visualization interactive = False if interactive: window.show(ren) """ .. figure:: tensor_tracks.png :align: center Deterministic streamlines with EuDX on a Tensor Field.
# Above we see the total number of streamlines contained within this tractogram. Typically we would want a million or more in order to adequately cover the entire white matter of the brain. Here though, we are working with a smaller number as it is easier to use in a notebook. # # Lets plot two of these streamlines so we can get a sense of what streamlines look like when visualized # In[2]: from dipy.viz import window, actor, colormap as cmap # Enables/disables interactive visualization interactive = True firstTwoStreamline = streamsObjIN.tractogram.streamlines[1:2] # Make display objects color = cmap.line_colors(firstTwoStreamline) cc_streamlines_actor = actor.line(firstTwoStreamline, cmap.line_colors(firstTwoStreamline)) vol_actor = actor.slicer(t1_data) vol_actor.display(x=40) vol_actor2 = vol_actor.copy() vol_actor2.display(z=35) # Add display objects to canvas r = window.Renderer() r.add(vol_actor) r.add(vol_actor2) r.add(cc_streamlines_actor) r.add(cc_ROI_actor)
cc_slice, affine=affine, include=False) other_streamlines = list(other_streamlines) assert len(other_streamlines) + len(cc_streamlines) == len(streamlines) """ We can use some of dipy's visualization tools to display the ROI we targeted above and all the streamlines that pass though that ROI. The ROI is the yellow region near the center of the axial image. """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors # Make display objects color = line_colors(cc_streamlines) cc_streamlines_actor = fvtk.line(cc_streamlines, line_colors(cc_streamlines)) cc_ROI_actor = fvtk.contour(cc_slice, levels=[1], colors=[(1., 1., 0.)], opacities=[1.]) vol_actor = fvtk.slicer(t1_data, voxsz=(1.0, 1.0, 1.0), plane_i=[40], plane_j=None, plane_k=[35], outline=False) # Add display objects to canvas r = fvtk.ren()
#fig.tight_layout() #fig.savefig('threshold_fa_3_0.5.png') all_streamlines_threshold_classifier = LocalTracking(dg, threshold_classifier, seeds, affine, step_size=0.4, return_all=True) save_trk("deterministic_threshold_classifier_all.trk", all_streamlines_threshold_classifier, affine, labels.shape) streamlines = Streamlines(all_streamlines_threshold_classifier) ren = window.Renderer() if window.have_vtk: window.clear(ren) ren.add(actor.line(streamlines, line_colors(streamlines))) window.record( ren, out_path= '/home/nrajamani/Downloads/HNU1/scripts/density_vs_exec/all_streamlines_threshold_classifier_4.png', size=(600, 600)) if interactive: window.show(ren) print("----%s seconds -----" % (time.time() - start_time)) ## [2,2,2] = execution time 849.603137016 seconds ## ## [3,3,3] = execution time 2183.9916029 seconds seconds## ## [4,4,4] = execution time ### 5 = execution time 32 ### 6 = 28.07976 seconds ### 7 = 27.07548
streamline_generator = EuDX(stopping_values, csd_peaks.peak_indices, seeds=10**4, odf_vertices=sphere.vertices, a_low=0.1) streamlines = [streamline for streamline in streamline_generator] """ We can visualize the streamlines using ``fvtk.line`` or ``fvtk.streamtube``. """ fvtk.clear(ren) fvtk.add(ren, fvtk.line(streamlines, line_colors(streamlines))) print('Saving illustration as csd_streamlines_eudx.png') fvtk.record(ren, out_path='csd_streamlines_eudx.png', size=(900, 900)) """ .. figure:: csd_streamlines_eudx.png :align: center **CSD-based streamlines using EuDX** We used above ``fvtk.record`` because we want to create a figure for the tutorial but you can visualize the same objects in 3D using ``fvtk.show(ren)``. To learn more about this process you could start playing with the number of
The streamlines that are entered into the model are termed 'candidate streamliness' (or a 'candidate connectome'): """ """ Let's visualize the initial candidate group of streamlines in 3D, relative to the anatomical structure of this brain: """ from dipy.viz.colormap import line_colors from dipy.viz import fvtk candidate_streamlines_actor = fvtk.streamtube(candidate_sl, line_colors(candidate_sl)) cc_ROI_actor = fvtk.contour(cc_slice, levels=[1], colors=[(1., 1., 0.)], opacities=[1.]) vol_actor = fvtk.slicer(t1_data) vol_actor.display(40, None, None) vol_actor2 = vol_actor.copy() vol_actor2.display(None, None, 35) # Add display objects to canvas ren = fvtk.ren() fvtk.add(ren, candidate_streamlines_actor) fvtk.add(ren, cc_ROI_actor)
stopping_criterion, seeds, affine=affine, step_size=.5) # Generate streamlines object streamlines = Streamlines(streamlines_generator) """ We will then display the resulting streamlines using the ``fury`` python package. """ from dipy.viz import colormap if has_fury: # Prepare the display objects. color = colormap.line_colors(streamlines) streamlines_actor = actor.line(streamlines, colormap.line_colors(streamlines)) # Create the 3D display. scene = window.Scene() scene.add(streamlines_actor) # Save still images for this static example. Or for interactivity use window.record(scene, out_path='tractogram_EuDX.png', size=(800, 800)) if interactive: window.show(scene) """ .. figure:: tractogram_EuDX.png :align: center
# part for changing including streamlines only longer than particular length, here 50 from dipy.tracking.metrics import length longer_streamlines = [] for tract in streamlines: if length(tract) > 50.0: longer_streamlines.append(tract) # Streamlines visualization from dipy.viz import fvtk from dipy.viz.colormap import line_colors # Make display objects streamlines_actor = fvtk.line(longer_streamlines, line_colors(longer_streamlines)) # Add display objects to canvas r = fvtk.ren() fvtk.add(r, streamlines_actor) # Save figure fvtk.camera(r, [-1, 0, 0], [0, 0, 0], viewup=[0, 0, 1]) fvtk.record(r, n_frames=1, out_path='streamlines_saggital.png', size=(800, 800))
""" """ Let's visualize the initial candidate group of streamlines in 3D, relative to the anatomical structure of this brain: """ # Enables/disables interactive visualization interactive = False candidate_streamlines_actor = actor.streamtube(candidate_sl, cmap.line_colors(candidate_sl)) cc_ROI_actor = actor.contour_from_roi(cc_slice, color=(1., 1., 0.), opacity=0.5) vol_actor = actor.slicer(t1_data) vol_actor.display(x=40) vol_actor2 = vol_actor.copy() vol_actor2.display(z=35) # Add display objects to canvas scene = window.Scene() scene.add(candidate_streamlines_actor) scene.add(cc_ROI_actor) scene.add(vol_actor) scene.add(vol_actor2)
other_streamlines = Streamlines(other_streamlines) assert len(other_streamlines) + len(cc_streamlines) == len(streamlines) """ We can use some of DIPY_'s visualization tools to display the ROI we targeted above and all the streamlines that pass though that ROI. The ROI is the yellow region near the center of the axial image. """ from dipy.viz import window, actor, colormap as cmap # Enables/disables interactive visualization interactive = False # Make display objects color = cmap.line_colors(cc_streamlines) cc_streamlines_actor = actor.line(cc_streamlines, cmap.line_colors(cc_streamlines)) cc_ROI_actor = actor.contour_from_roi(cc_slice, color=(1., 1., 0.), opacity=0.5) vol_actor = actor.slicer(t1_data) vol_actor.display(x=40) vol_actor2 = vol_actor.copy() vol_actor2.display(z=35) # Add display objects to canvas r = window.Renderer() r.add(vol_actor) r.add(vol_actor2)
hardi_img, gtab, labels_img = read_stanford_labels() labels = labels_img.get_data() cc_slice = labels == 2 t1 = read_stanford_t1() t1_data = t1.get_data() data = hardi_img.get_data() # Read the candidates from file in voxel space: candidate_sl = [ s[0] for s in nib.trackvis.read(args.input_trackvis, points_space='voxel')[0] ] # Visualize the initial candidate group of streamlines # in 3D, relative to the anatomical structure of this brain. candidate_streamlines_actor = fvtk.streamtube(candidate_sl, line_colors(candidate_sl)) cc_ROI_actor = fvtk.contour(cc_slice, levels=[1], colors=[(1., 1., 0.)], opacities=[1.]) vol_actor = fvtk.slicer(t1_data) vol_actor.display(40, None, None) vol_actor2 = vol_actor.copy() vol_actor2.display(None, None, 35) # Add display objects to canvas. ren = fvtk.ren() fvtk.add(ren, candidate_streamlines_actor) fvtk.add(ren, cc_ROI_actor) fvtk.add(ren, vol_actor) fvtk.add(ren, vol_actor2) fvtk.record(ren, n_frames=1, out_path="life_candidates.png", size=(800, 800))
def visualize_bundles(trk, affine_or_mapping=None, bundle=None, ren=None, color=None, inline=True, interact=False): """ Visualize bundles in 3D using VTK """ if isinstance(trk, str): trk = nib.streamlines.load(trk) tg = trk.tractogram else: # Assume these are streamlines (as list or Streamlines object): tg = nib.streamlines.Tractogram(trk) if affine_or_mapping is not None: tg = tg.apply_affine(np.linalg.inv(affine_or_mapping)) streamlines = tg.streamlines if ren is None: ren = window.Renderer() # There are no bundles in here: if list(tg.data_per_streamline.keys()) == []: streamlines = list(streamlines) sl_actor = actor.line(streamlines, line_colors(streamlines)) ren.add(sl_actor) sl_actor.GetProperty().SetRenderLinesAsTubes(1) sl_actor.GetProperty().SetLineWidth(6) if bundle is None: for b in np.unique(tg.data_per_streamline['bundle']): idx = np.where(tg.data_per_streamline['bundle'] == b)[0] this_sl = list(streamlines[idx]) if color is not None: sl_actor = actor.line(this_sl, color) sl_actor.GetProperty().SetRenderLinesAsTubes(1) sl_actor.GetProperty().SetLineWidth(6) else: sl_actor = actor.line(this_sl, Tableau_20.colors[np.mod(20, int(b))]) sl_actor.GetProperty().SetRenderLinesAsTubes(1) sl_actor.GetProperty().SetLineWidth(6) ren.add(sl_actor) else: idx = np.where(tg.data_per_streamline['bundle'] == bundle)[0] this_sl = list(streamlines[idx]) if color is not None: sl_actor = actor.line(this_sl, color) sl_actor.GetProperty().SetRenderLinesAsTubes(1) sl_actor.GetProperty().SetLineWidth(6) else: sl_actor = actor.line(this_sl, Tableau_20.colors[np.mod(20, int(bundle))]) sl_actor.GetProperty().SetRenderLinesAsTubes(1) sl_actor.GetProperty().SetLineWidth(6) ren.add(sl_actor) return _inline_interact(ren, inline, interact)
""" Example #1: Bootstrap direction getter with CSD Model """ from dipy.direction import BootDirectionGetter from dipy.tracking.streamline import Streamlines from dipy.data import small_sphere boot_dg_csd = BootDirectionGetter.from_data(data, csd_model, max_angle=30., sphere=small_sphere) boot_streamline_generator = LocalTracking(boot_dg_csd, classifier, seeds, affine, step_size=.5) streamlines = Streamlines(boot_streamline_generator) renderer.clear() renderer.add(actor.line(streamlines, line_colors(streamlines))) window.record(renderer, out_path='bootstrap_dg_CSD.png', size=(600, 600)) """ .. figure:: bootstrap_dg_CSD.png :align: center **Corpus Callosum Bootstrap Probabilistic Direction Getter** We have created a bootstrapped probabilistic set of streamlines. If you repeat the fiber tracking (keeping all inputs the same) you will NOT get exactly the same set of streamlines. We can save the streamlines as a Trackvis file so it can be loaded into other software for visualization or further analysis. """ save_trk("bootstrap_dg_CSD.trk", streamlines, affine, labels.shape)
streamlines = Streamlines(streamlines_generator) """ Next, we will create a visualization of these streamlines, relative to this subject's T1-weighted anatomy: """ from dipy.viz import window, actor from dipy.viz.colormap import line_colors from dipy.data import read_stanford_t1 from dipy.tracking.utils import move_streamlines from numpy.linalg import inv t1 = read_stanford_t1() t1_data = t1.get_data() t1_aff = t1.affine color = line_colors(streamlines) # Enables/disables interactive visualization interactive = True """ To speed up visualization, we will select a random sub-set of streamlines to display. This is particularly important, if you track from seeds throughout the entire white matter, generating many streamlines. In this case, for demonstration purposes, we subselect 900 streamlines. """ from dipy.tracking.streamline import select_random_set_of_streamlines plot_streamlines = select_random_set_of_streamlines(streamlines, 900) streamlines_actor = actor.streamtube(
def lines_to_vtk_polydata(lines, colors=None): """ Create a vtkPolyData with lines and colors Parameters ---------- lines : list list of N curves represented as 2D ndarrays colors : array (N, 3), list of arrays, tuple (3,), array (K,), None If None then a standard orientation colormap is used for every line. If one tuple of color is used. Then all streamlines will have the same colour. If an array (N, 3) is given, where N is equal to the number of lines. Then every line is coloured with a different RGB color. If a list of RGB arrays is given then every point of every line takes a different color. If an array (K, 3) is given, where K is the number of points of all lines then every point is colored with a different RGB color. If an array (K,) is given, where K is the number of points of all lines then these are considered as the values to be used by the colormap. If an array (L,) is given, where L is the number of streamlines then these are considered as the values to be used by the colormap per streamline. If an array (X, Y, Z) or (X, Y, Z, 3) is given then the values for the colormap are interpolated automatically using trilinear interpolation. Returns ------- poly_data : vtkPolyData is_colormap : bool, true if the input color array was a colormap """ # Get the 3d points_array points_array = np.vstack(lines) nb_lines = len(lines) nb_points = len(points_array) lines_range = range(nb_lines) # Get lines_array in vtk input format lines_array = [] # Using np.intp (instead of int64), because of a bug in numpy: # https://github.com/nipy/dipy/pull/789 # https://github.com/numpy/numpy/issues/4384 points_per_line = np.zeros([nb_lines], np.intp) current_position = 0 for i in lines_range: current_len = len(lines[i]) points_per_line[i] = current_len end_position = current_position + current_len lines_array += [current_len] lines_array += range(current_position, end_position) current_position = end_position lines_array = np.array(lines_array) # Set Points to vtk array format vtk_points = numpy_to_vtk_points(points_array) # Set Lines to vtk array format vtk_lines = vtk.vtkCellArray() vtk_lines.GetData().DeepCopy(ns.numpy_to_vtk(lines_array)) vtk_lines.SetNumberOfCells(nb_lines) is_colormap = False # Get colors_array (reformat to have colors for each points) # - if/else tested and work in normal simple case if colors is None: # set automatic rgb colors cols_arr = line_colors(lines) colors_mapper = np.repeat(lines_range, points_per_line, axis=0) vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper]) else: cols_arr = np.asarray(colors) if cols_arr.dtype == np.object: # colors is a list of colors vtk_colors = numpy_to_vtk_colors(255 * np.vstack(colors)) else: if len(cols_arr) == nb_points: if cols_arr.ndim == 1: # values for every point vtk_colors = ns.numpy_to_vtk(cols_arr, deep=True) is_colormap = True elif cols_arr.ndim == 2: # map color to each point vtk_colors = numpy_to_vtk_colors(255 * cols_arr) elif cols_arr.ndim == 1: if len(cols_arr) == nb_lines: # values for every streamline cols_arrx = [] for (i, value) in enumerate(colors): cols_arrx += lines[i].shape[0] * [value] cols_arrx = np.array(cols_arrx) vtk_colors = ns.numpy_to_vtk(cols_arrx, deep=True) is_colormap = True else: # the same colors for all points vtk_colors = numpy_to_vtk_colors( np.tile(255 * cols_arr, (nb_points, 1))) elif cols_arr.ndim == 2: # map color to each line colors_mapper = np.repeat(lines_range, points_per_line, axis=0) vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper]) else: # colormap # get colors for each vertex cols_arr = map_coordinates_3d_4d(cols_arr, points_array) vtk_colors = ns.numpy_to_vtk(cols_arr, deep=True) is_colormap = True vtk_colors.SetName("Colors") # Create the poly_data poly_data = vtk.vtkPolyData() poly_data.SetPoints(vtk_points) poly_data.SetLines(vtk_lines) poly_data.GetPointData().SetScalars(vtk_colors) return poly_data, is_colormap
labels = labels_img.get_data() affine = hardi_img.affine seed_mask = labels == 2 white_matter = (labels == 1) | (labels == 2) seeds = utils.seeds_from_mask(seed_mask, density=1, affine=affine) csd_model = ConstrainedSphericalDeconvModel(gtab, None, sh_order=6) csd_fit = csd_model.fit(data, mask=white_matter) from dipy.reconst.shm import CsaOdfModel csa_model = CsaOdfModel(gtab, sh_order=6) gfa = csa_model.fit(data, mask=white_matter).gfa classifier = ThresholdTissueClassifier(gfa, .25) from dipy.direction import BootDirectionGetter from dipy.tracking.streamline import Streamlines from dipy.data import small_sphere boot_dg_csd = BootDirectionGetter.from_data(data, csd_model, max_angle=30., sphere=small_sphere) boot_streamline_generator = LocalTracking(boot_dg_csd, classifier, seeds, affine, step_size=.5) streamlines = Streamlines(boot_streamline_generator) renderer.clear() renderer.add(actor.line(streamlines, cmap.line_colors(streamlines))) window.record(renderer, out_path='bootstrap_dg_CSD.png', size=(600, 600))
def lines_to_vtk_polydata(lines, colors=None): """ Create a vtkPolyData with lines and colors Parameters ---------- lines : list list of N curves represented as 2D ndarrays colors : array (N, 3), list of arrays, tuple (3,), array (K,), None If None then a standard orientation colormap is used for every line. If one tuple of color is used. Then all streamlines will have the same colour. If an array (N, 3) is given, where N is equal to the number of lines. Then every line is coloured with a different RGB color. If a list of RGB arrays is given then every point of every line takes a different color. If an array (K, 3) is given, where K is the number of points of all lines then every point is colored with a different RGB color. If an array (K,) is given, where K is the number of points of all lines then these are considered as the values to be used by the colormap. If an array (L,) is given, where L is the number of streamlines then these are considered as the values to be used by the colormap per streamline. If an array (X, Y, Z) or (X, Y, Z, 3) is given then the values for the colormap are interpolated automatically using trilinear interpolation. Returns ------- poly_data : vtkPolyData is_colormap : bool, true if the input color array was a colormap """ # Get the 3d points_array points_array = np.vstack(lines) nb_lines = len(lines) nb_points = len(points_array) lines_range = range(nb_lines) # Get lines_array in vtk input format lines_array = [] # Using np.intp (instead of int64), because of a bug in numpy: # https://github.com/nipy/dipy/pull/789 # https://github.com/numpy/numpy/issues/4384 points_per_line = np.zeros([nb_lines], np.intp) current_position = 0 for i in lines_range: current_len = len(lines[i]) points_per_line[i] = current_len end_position = current_position + current_len lines_array += [current_len] lines_array += range(current_position, end_position) current_position = end_position lines_array = np.array(lines_array) # Set Points to vtk array format vtk_points = numpy_to_vtk_points(points_array) # Set Lines to vtk array format vtk_lines = vtk.vtkCellArray() vtk_lines.GetData().DeepCopy(ns.numpy_to_vtk(lines_array)) vtk_lines.SetNumberOfCells(nb_lines) is_colormap = False # Get colors_array (reformat to have colors for each points) # - if/else tested and work in normal simple case if colors is None: # set automatic rgb colors cols_arr = line_colors(lines) colors_mapper = np.repeat(lines_range, points_per_line, axis=0) vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper]) else: cols_arr = np.asarray(colors) if cols_arr.dtype == np.object: # colors is a list of colors vtk_colors = numpy_to_vtk_colors(255 * np.vstack(colors)) else: if len(cols_arr) == nb_points: if cols_arr.ndim == 1: # values for every point vtk_colors = ns.numpy_to_vtk(cols_arr, deep=True) is_colormap = True elif cols_arr.ndim == 2: # map color to each point vtk_colors = numpy_to_vtk_colors(255 * cols_arr) elif cols_arr.ndim == 1: if len(cols_arr) == nb_lines: # values for every streamline cols_arrx = [] for (i, value) in enumerate(colors): cols_arrx += lines[i].shape[0] * [value] cols_arrx = np.array(cols_arrx) vtk_colors = ns.numpy_to_vtk(cols_arrx, deep=True) is_colormap = True else: # the same colors for all points vtk_colors = numpy_to_vtk_colors(np.tile(255 * cols_arr, (nb_points, 1))) elif cols_arr.ndim == 2: # map color to each line colors_mapper = np.repeat(lines_range, points_per_line, axis=0) vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper]) else: # colormap # get colors for each vertex cols_arr = map_coordinates_3d_4d(cols_arr, points_array) vtk_colors = ns.numpy_to_vtk(cols_arr, deep=True) is_colormap = True vtk_colors.SetName("Colors") # Create the poly_data poly_data = vtk.vtkPolyData() poly_data.SetPoints(vtk_points) poly_data.SetLines(vtk_lines) poly_data.GetPointData().SetScalars(vtk_colors) return poly_data, is_colormap
streamlines = Streamlines(streamlines_generator) """ Next, we will create a visualization of these streamlines, relative to this subject's T1-weighted anatomy: """ from dipy.viz import window, actor, colormap as cmap from dipy.data import read_stanford_t1 from dipy.tracking.utils import move_streamlines from numpy.linalg import inv t1 = read_stanford_t1() t1_data = t1.get_data() t1_aff = t1.affine color = cmap.line_colors(streamlines) # Enables/disables interactive visualization interactive = False """ To speed up visualization, we will select a random sub-set of streamlines to display. This is particularly important, if you track from seeds throughout the entire white matter, generating many streamlines. In this case, for demonstration purposes, we subselect 900 streamlines. """ from dipy.tracking.streamline import select_random_set_of_streamlines plot_streamlines = select_random_set_of_streamlines(streamlines, 900) streamlines_actor = actor.streamtube(
Finally, we can bring it all together using ``LocalTracking``. We will then display the resulting streamlines using the fvtk module. """ from dipy.tracking.local import LocalTracking from dipy.viz import fvtk from dipy.viz.colormap import line_colors # Initialization of LocalTracking. The computation happens in the next step. streamlines = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=.5) # Compute streamlines and store as a list. streamlines = list(streamlines) # Prepare the display objects. color = line_colors(streamlines) streamlines_actor = fvtk.line(streamlines, line_colors(streamlines)) # Create the 3d display. r = fvtk.ren() fvtk.add(r, streamlines_actor) # Save still images for this static example. Or for interactivity use fvtk.show fvtk.record(r, n_frames=1, out_path='deterministic.png', size=(800, 800)) """ .. figure:: deterministic.png :align: center **Corpus Callosum Deterministic**
""" # Make a corpus callosum seed mask for tracking seed_mask = labels == 2 seeds = utils.seeds_from_mask(seed_mask, density=[1, 1, 1], affine=affine) # Make a streamline bundle model of the corpus callosum ROI connectivity streamlines = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=2) streamlines = Streamlines(streamlines) # Visualize the streamlines and the Path Length Map base ROI # (in this case also the seed ROI) streamlines_actor = actor.line(streamlines, cmap.line_colors(streamlines)) surface_opacity = 0.5 surface_color = [0, 1, 1] seedroi_actor = actor.contour_from_roi(seed_mask, affine, surface_color, surface_opacity) ren = window.Renderer() ren.add(streamlines_actor) ren.add(seedroi_actor) """ If you set interactive to True (below), the rendering will pop up in an interactive window. """ interactive = False
hdr['dim'] = csapeaks.gfa.shape[:3] """ Save the streamlines. """ csa_streamlines_trk = ((sl, None, None) for sl in csa_streamlines) csa_sl_fname = 'csa_prob_streamline.trk' nib.trackvis.write(csa_sl_fname, csa_streamlines_trk, hdr) """ Visualize the streamlines with fvtk (python vtk is required). """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors r = fvtk.ren() fvtk.add(r, fvtk.line(csa_streamlines, line_colors(csa_streamlines))) print('Saving illustration as csa_prob_tracks.png') fvtk.record(r, n_frames=1, out_path='csa_prob_tracks.png', size=(600, 600)) """ .. figure:: csa_prob_tracks.png :align: center **Probabilistic streamlines applied on an ODF field modulated by GFA**. """
streamlines = list(streamlines) """ Next, we will create a visualization of these streamlines, relative to this subject's T1-weighted anatomy: """ from dipy.viz import fvtk from dipy.viz.colormap import line_colors from dipy.data import read_stanford_t1 from dipy.tracking.utils import move_streamlines from numpy.linalg import inv t1 = read_stanford_t1() t1_data = t1.get_data() t1_aff = t1.affine color = line_colors(streamlines) """ To speed up visualization, we will select a random sub-set of streamlines to display. This is particularly important, if you track from seeds throughout the entire white matter, generating many streamlines. In this case, for demonstration purposes, we subselect 900 streamlines. """ from dipy.tracking.streamline import select_random_set_of_streamlines plot_streamlines = select_random_set_of_streamlines(streamlines, 900) streamlines_actor = fvtk.streamtube(list( move_streamlines(plot_streamlines, inv(t1_aff))), line_colors(streamlines), linewidth=0.1)
Create a scene. """ r=fvtk.ren() """ Every streamline will be coloured according to its orientation """ from dipy.viz.colormap import line_colors """ fvtk.line adds a streamline actor for streamline visualization and fvtk.add adds this actor in the scene """ fvtk.add(r, fvtk.line(tensor_streamlines, line_colors(tensor_streamlines))) print('Saving illustration as tensor_tracks.png') fvtk.record(r, n_frames=1, out_path='tensor_tracking.png', size=(600, 600)) """ .. figure:: tensor_tracking.png :align: center **Deterministic streamlines with EuDX on a Tensor Field**. .. include:: ../links_names.inc """
all_streamlines_threshold_classifier = LocalTracking(dg, threshold_classifier, seeds, affine, step_size=.5, return_all=True) save_trk("deterministic_threshold_classifier_all.trk", all_streamlines_threshold_classifier, affine, labels.shape) streamlines = [sl for sl in all_streamlines_threshold_classifier] fvtk.clear(ren) fvtk.add(ren, fvtk.line(streamlines, line_colors(streamlines))) fvtk.record(ren, out_path='all_streamlines_threshold_classifier.png', size=(600, 600)) """ .. figure:: all_streamlines_threshold_classifier.png :align: center **Deterministic tractography using a thresholded fractional anisotropy.** """ """ Binary Tissue Classifier ------------------------ A binary mask can be used to define where the tracking stops. The binary
""" ren = fvtk.ren() """ Every streamline will be coloured according to its orientation """ from dipy.viz.colormap import line_colors """ fvtk.line adds a streamline actor for streamline visualization and fvtk.add adds this actor in the scene """ fvtk.add(ren, fvtk.streamtube(tensor_streamlines, line_colors(tensor_streamlines))) print('Saving illustration as tensor_tracks.png') ren.SetBackground(1, 1, 1) fvtk.record(ren, n_frames=1, out_path='tensor_tracks.png', size=(600, 600)) """ .. figure:: tensor_tracks.png :align: center Deterministic streamlines with EuDX on a Tensor Field. References ----------
from dipy.tracking.local import LocalTracking from dipy.viz import window, actor from dipy.viz.colormap import line_colors from dipy.tracking.streamline import Streamlines # Enables/disables interactive visualization interactive = False # Initialization of LocalTracking. The computation happens in the next step. streamlines_generator = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=.5) # Generate streamlines object streamlines = Streamlines(streamlines_generator) # Prepare the display objects. color = line_colors(streamlines) if window.have_vtk: streamlines_actor = actor.line(streamlines, line_colors(streamlines)) # Create the 3D display. r = window.Renderer() r.add(streamlines_actor) # Save still images for this static example. Or for interactivity use window.record(r, n_frames=1, out_path='deterministic.png', size=(800, 800)) if interactive: window.show(r) """ .. figure:: deterministic.png
threshold_classifier, seeds, affine, step_size=.5, return_all=True) save_trk("deterministic_threshold_classifier_all.trk", all_streamlines_threshold_classifier, affine, labels.shape) streamlines = Streamlines(all_streamlines_threshold_classifier) if have_fury: window.clear(ren) ren.add(actor.line(streamlines, cmap.line_colors(streamlines))) window.record(ren, out_path='all_streamlines_threshold_classifier.png', size=(600, 600)) if interactive: window.show(ren) """ .. figure:: all_streamlines_threshold_classifier.png :align: center **Deterministic tractography using a thresholded fractional anisotropy.** """ """ Binary Tissue Classifier