def show_all_bundles(start, end):

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.)
    from dipy.viz.fvtk import colors as c

    colors = [c.alice_blue, c.maroon, c.alizarin_crimson, c.mars_orange, c.antique_white,
             c.mars_yellow, c.aquamarine, c.melon, c.aquamarine_medium, c.midnight_blue,
             c.aureoline_yellow, c.mint, c.azure, c.mint_cream, c.banana, c.misty_rose,
             c.beige]

    print(len(colors))

    for (i, bundle) in enumerate(bundle_names[start:end]):

        bun = load_bundle(bundle)

        bun_actor = vtk_a.streamtube(bun, colors[i], linewidth=0.5, tube_sides=9)
        fvtk.add(ren, bun_actor)

    fvtk.show(ren, size=(1800, 1000))
    #fvtk.record(ren, n_frames=100, out_path='test.png', 
    #            magnification=1)
    fvtk.record(ren, size=(1800, 1000), n_frames=100, out_path='test.png', 
                path_numbering=True, magnification=1)
Example #2
0
def visualize_bundles(trk, ren=None, inline=True, interact=False):
    """
    Visualize bundles in 3D using fvtk


    """
    if isinstance(trk, str):
        trk = nib.streamlines.load(trk)

    if ren is None:
        ren = fvtk.ren()

    for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
        idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
        this_sl = list(trk.streamlines[idx])
        sl_actor = fvtk.line(this_sl, Tableau_20.colors[int(b)])
        fvtk.add(ren, sl_actor)

    if inline:
        tdir = tempfile.gettempdir()
        fname = op.join(tdir, "fig.png")
        fvtk.record(ren, out_path=fname)
        display.display_png(display.Image(fname))

    if interact:
        fvtk.show(ren)

    return ren
def show(imgtck, clusters, out_path):
    colormap = fvtk.create_colormap(np.ravel(clusters.centroids), name='jet')
    colormap_full = np.ones((len(imgtck.streamlines), 3))
    for cluster, color in zip(clusters, colormap):
        colormap_full[cluster.indices] = color

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    fvtk.add(ren, fvtk.streamtube(imgtck.streamlines, colormap_full))
    fvtk.record(ren, n_frames=1, out_path=out_path, size=(600, 600))
    fvtk.show(ren)
def show_odfs(peaks, sphere, fname):
    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.)
    odf = np.dot(peaks.shm_coeff, peaks.invB)
    #odf = odf[14:24, 22, 23:33]
    #odf = odf[:, 22, :]
    odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fname, size=(600, 600))
Example #5
0
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_odfs(fpng, odf_sh, invB, sphere):
    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.0)
    odf = np.dot(odf_sh, invB)
    print(odf.shape)
    odf = odf[14:24, 22, 23:33]
    # odf = odf[:, 22, :]
    # odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fpng, size=(900, 900))
    fvtk.clear(ren)
def show_odfs_with_map2(odf, sphere, map, w, fpng):
    ren = fvtk.ren()
    sfu = fvtk.sphere_funcs(odf, sphere, norm=True)
    #sfu.RotateX(-90)
    sfu.SetPosition(w, w, 1)
    sfu.SetScale(0.435)

    sli = fvtk.slicer(map, plane_i=None, plane_k=[0], outline=False)
    #sli.RotateX(-90)
    fvtk.add(ren, sli)
    fvtk.add(ren, sfu)
    #fvtk.add(ren, fvtk.axes((20, 20, 20)))

    #fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fpng, magnification=2, size=(900, 900))
def show_both_bundles(bundles, colors=None, show=False, fname=None):

    ren = fvtk.ren()
    ren.SetBackground(1.0, 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
def show_both_bundles(bundles, colors=None, show=False, fname=None):

    ren = fvtk.ren()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
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
Example #11
0
def show_bundles(streamlines, clusters, show_b=True):
    # Color each streamline according to the cluster they belong to.
    colormap = fvtk.create_colormap(np.arange(len(clusters)))
    colormap_full = np.ones((len(streamlines), 3))
    for cluster, color in zip(clusters, colormap):
        colormap_full[cluster.indices] = color

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    fvtk.add(ren, fvtk.streamtube(streamlines, colormap_full))
    fvtk.record(ren,
                n_frames=1,
                out_path='fornix_clusters_cosine.png',
                size=(600, 600))

    if show_b:
        fvtk.show(ren)
def show_all_bundles(bundles, colors=None, show=True, fname=None):

    ren = fvtk.ren()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        if colors is None:
            color = np.random.rand(3)
        else:
            color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.15 * 2)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    #fvtk.add(ren, fvtk.axes((20, 20, 20)))
    if show:
        fvtk.show(ren)
    if fname is not None:
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
def show_peak_directions(fpng, peaks, scale=0.3, x=10, y=0, z=10):
    r = fvtk.ren()

    for index in ndindex(peaks.shape[:-1]):
        peak = peaks[index]
        directions = peak.reshape(peak.shape[0] / 3, 3)

        # pos = np.array(index)
        for i in xrange(directions.shape[0]):
            if norm(directions[i]) != 0:
                line_actor = fvtk.line(
                    index + scale * np.vstack((-directions[i], directions[i])), abs(directions[i] / norm(directions[i]))
                )
                line_actor.RotateX(-90)
                fvtk.add(r, line_actor)

    fvtk.show(r)
    fvtk.record(r, out_path=fpng, size=(900, 900))
    fvtk.clear(r)
Example #14
0
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
Example #15
0
def show_both_bundles(bundles, colors=None, show_b=False, fname=None):
    """
    Show both bundles
    bundles: return of --pyfat/algorithm/fiber_math/bundle_registration
    example:
    show_both_bundles([cb_subj1, cb_subj2_aligned],
                     colors=[fvtk.colors.orange, fvtk.colors.red],
                     fname='after_registration.png')
    """
    ren = fvtk.ren()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show_b:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Example #16
0
                            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))
"""

.. figure:: life_candidates.png
   :align: center

   **Candidate connectome before life optimization**

"""
"""

Next, we initialize a LiFE model. We import the `dipy.tracking.life` module,
which contains the classes and functions that implement the model:

"""
all_shift = [c + np.array([10, 0, 0]) for c in all]
all_shift2 = [c + np.array([20, 0, 0]) for c in all]

colors = np.zeros((len(all), 3))
colors2 = np.zeros((len(all), 3))
for (i, a) in enumerate(all):
    #print a[0]
    colors[i] = cm.boys2rgb(allo[i])
    colors2[i] = cm.orient2rgb(allo[i])

fvtk.add(r, fvtk.line(all_shift, colors, linewidth=1.))
fvtk.add(r, fvtk.line(all_shift2, colors2, linewidth=2.))
"""

.. figure:: visualize_cross1000000.png
   :align: center

   **The crossings of a region of interest shown with one color, or boy2rgb or standard orient2rgb colormap**.

.. include:: ../links_names.inc

"""

# To show the figure
# fvtk.show(r,size=(800,800))

# Here's how we make the illustration.
print('Saving illustration as visualize_cross1000000.png')
fvtk.record(r, n_frames=1, out_path='visualize_cross', size=(600, 600))
Example #18
0
clusters = qb.cluster(streamlines)
"""
We will now visualize the clustering result.
"""

# Color each streamline according to the cluster they belong to.
colormap = fvtk.create_colormap(np.ravel(clusters.centroids))
colormap_full = np.ones((len(streamlines), 3))
for cluster, color in zip(clusters, colormap):
    colormap_full[cluster.indices] = color

ren = fvtk.ren()
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.streamtube(streamlines, colormap_full))
fvtk.record(ren,
            n_frames=1,
            out_path='fornix_clusters_arclength.png',
            size=(600, 600))
"""
.. figure:: fornix_clusters_arclength.png
   :align: center

   **Showing the different clusters obtained by using the arc length**.


Extending `Metric`
==================
This section will guide you through the creation of a new metric that can be
used in the context of this clustering framework. For a list of available
metrics in Dipy see :ref:`example_segment_clustering_metrics`.

Assuming a set of streamlines, we want a metric that computes the cosine
"""

qb = QuickBundles(streamlines, dist_thr=10., pts=18)

"""
qb has attributes like `centroids` (cluster representatives), `total_clusters`
(total number of clusters) and methods like `partitions` (complete description
of all clusters) and `label2tracksids` (provides the indices of the streamlines
which belong in a specific cluster).

Lets first show the initial dataset.
"""

r = fvtk.ren()
fvtk.add(r, fvtk.line(streamlines, fvtk.white, opacity=1, linewidth=3))
fvtk.record(r, n_frames=1, out_path='fornix_initial.png', size=(600, 600))

"""
.. figure:: fornix_initial.png
   :align: center

   **Initial Fornix dataset**.

Show the centroids of the fornix after clustering (with random colors):
"""

centroids = qb.centroids
colormap = np.random.rand(len(centroids), 3)

fvtk.clear(r)
fvtk.add(r, fvtk.line(centroids, colormap, opacity=1., linewidth=5))
Example #20
0
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

"""
# Instantiate model
from dipy.reconst.multi_voxel import multi_voxel_fit
SparseKernelModel.fit = multi_voxel_fit(SparseKernelModel.fit)

#from dipy.segment.mask import median_otsu
#maskdata, mask = median_otsu(data, 3, 1, True,
#                             vol_idx=range(10, 50), dilate=2)

# Select segment of data to work with
data_small = data[13:43, 44:74, 28:29]

fit = model.fit(data_small)

sphere = get_sphere('symmetric724')
odfs = fit.odf(sphere)

# It is common for some models to produce negative values, we can remove those
# using ``np.clip``
odfs = np.clip(odfs, 0, np.max(odfs, -1)[..., None])

# Visualie

from dipy.viz import fvtk
r = fvtk.ren()
fvtk.add(r, fvtk.sphere_funcs(odfs, sphere, colormap='jet'))

fn = model.__class__.__name__ + '_odfs.png'
print('Saving illustration as %s' % fn)
fvtk.record(r, n_frames=1, out_path=fn, size=(600, 600))
Example #22
0
fit_wls = dti_wls.fit(data)

fa1 = fit_wls.fa
evals1 = fit_wls.evals
evecs1 = fit_wls.evecs
cfa1 = dti.color_fa(fa1, evecs1)
sphere = dpd.get_sphere('symmetric724')

"""
We visualize the ODFs in the ROI using fvtk:
"""

ren = fvtk.ren()
fvtk.add(ren, fvtk.tensor(evals1, evecs1, cfa1, sphere))
print('Saving illustration as tensor_ellipsoids_wls.png')
fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids_wls.png',
            size=(600, 600))

"""
.. figure:: tensor_ellipsoids_wls.png
   :align: center

   **Tensor Ellipsoids**.
"""

fvtk.clear(ren)

"""
Next, we corrupt the data with some noise. To simulate a subject that moves
intermittently, we will replace a few of the images with a very low signal
"""
Example #23
0
dsid_model = DiffusionSpectrumDeconvModel(gtab)

dsid_odf = dsid_model.fit(signal).odf(sphere)
"""
Finally, we can visualize the ground truth ODF, together with the DSI and DSI
with deconvolution ODFs and observe that with the deconvolved method it is
easier to resolve the correct fiber directions because the ODF is sharper.
"""

from dipy.viz import fvtk

ren = fvtk.ren()

odfs = np.vstack((odf_gt, dsi_odf, dsid_odf))[:, None, None]

odf_actor = fvtk.sphere_funcs(odfs, sphere)
odf_actor.RotateX(90)
fvtk.add(ren, odf_actor)
fvtk.record(ren, out_path='dsid.png', size=(300, 300))
"""
.. figure:: dsid.png
    :align: center

    **Ground truth ODF (left), DSI ODF (middle), DSI with Deconvolution ODF(right)**

.. [Canales10] Canales-Rodriguez et al., Deconvolution in Diffusion Spectrum Imaging,
			   Neuroimage, vol 50, no 1, 136-149, 2010.

"""
Example #24
0
distributed on the hemisphere. Let's visualize them.
"""

from dipy.viz import fvtk

ren = fvtk.ren()
ren.SetBackground(1, 1, 1)
fvtk.add(ren,
         fvtk.point(hsph_initial.vertices, fvtk.colors.red, point_radius=0.05))
fvtk.add(
    ren, fvtk.point(hsph_updated.vertices,
                    fvtk.colors.green,
                    point_radius=0.05))

print('Saving illustration as initial_vs_updated.png')
fvtk.record(ren, out_path='initial_vs_updated.png', size=(300, 300))
"""
.. figure:: initial_vs_updated.png
   :align: center

   **Example of electrostatic repulsion of red points which become green points**.

We can also create a sphere from the hemisphere and show it in the following way.
"""

sph = Sphere(xyz=np.vstack((hsph_updated.vertices, -hsph_updated.vertices)))

fvtk.rm_all(ren)
fvtk.add(ren, fvtk.point(sph.vertices, fvtk.colors.green, point_radius=0.05))

print('Saving illustration as full_sphere.png')
Example #25
0
filename = os.path.join(os.getcwd(), 'test_data', filename)
plt.style.use('ggplot')

# Create a render object
ren = fvtk.ren()

# Define values for fODF reconstruction
evals = np.array([2, 2, 5])

evecs = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])

# Set a shpere
sphere = get_sphere('symmetric642')

# Assign responses
response_odf = single_tensor_odf(sphere.vertices, evals, evecs)

response_actor = fvtk.sphere_funcs(response_odf, sphere)

# Render the spherical function
fvtk.add(ren, response_actor)
print('[  OK  ]\t Saving illustration: ' + filename)
fvtk.record(ren, out_path=filename, size=size)
print('[  OK  ] DONE!')

# Visualise the output
img = plt.imread(filename)
plt.imshow(img)
plt.axis('off')
plt.show()
Example #26
0
dsid_odf = dsid_model.fit(signal).odf(sphere)

"""
Finally, we can visualize the ground truth ODF, together with the DSI and DSI
with deconvolution ODFs and observe that with the deconvolved method it is
easier to resolve the correct fiber directions because the ODF is sharper.
"""

from dipy.viz import fvtk

ren = fvtk.ren()

odfs = np.vstack((odf_gt, dsi_odf, dsid_odf))[:, None, None]

odf_actor = fvtk.sphere_funcs(odfs, sphere)
odf_actor.RotateX(90)
fvtk.add(ren, odf_actor)
fvtk.record(ren, out_path='dsid.png', size=(300, 300))

"""
.. figure:: dsid.png
    :align: center

    **Ground truth ODF (left), DSI ODF (middle), DSI with Deconvolution ODF(right)**

.. [Canales10] Canales-Rodriguez et al., Deconvolution in Diffusion Spectrum Imaging,
			   Neuroimage, vol 50, no 1, 136-149, 2010.

"""
Example #27
0
           [  74.72344208,   86.60827637,   84.9391861 ],
           [  70.40846252,   85.15874481,   82.4484024 ],
           [  66.74534607,   86.00262451,   78.82582092],
           [  64.02451324,   88.43942261,   75.0697403 ]], dtype=float32)


`clusters` has also attributes like `centroids` (cluster representatives), and
methods like `add`, `remove`, and `clear` to modify the clustering result.

Lets first show the initial dataset.
"""

ren = fvtk.ren()
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white))
fvtk.record(ren, n_frames=1, out_path='fornix_initial.png', size=(600, 600))
"""
.. figure:: fornix_initial.png
   :align: center

   Initial Fornix dataset.

Show the centroids of the fornix after clustering (with random colors):
"""

colormap = fvtk.create_colormap(np.arange(len(clusters)))

fvtk.clear(ren)
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
fvtk.add(ren, fvtk.streamtube(clusters.centroids, colormap, linewidth=0.4))
                                                     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
tissue classifier stops the tracking whenever the tracking position is outside
the mask. Here, we show how to obtain the binary tissue classifier from
Example #29
0
"""
Fitting the model to this small volume of data, we calculate the ODF of this
model on the sphere, and plot it.
"""

sf_fit = sf_model.fit(data_small)
sf_odf = sf_fit.odf(sphere)

fodf_spheres = fvtk.sphere_funcs(sf_odf, sphere, scale=1.3, norm=True)

ren = fvtk.ren()
fvtk.add(ren, fodf_spheres)

print('Saving illustration as sf_odfs.png')
fvtk.record(ren, out_path='sf_odfs.png', size=(1000, 1000))

"""
We can extract the peaks from the ODF, and plot these as well
"""

sf_peaks = dpp.peaks_from_model(sf_model,
                                data_small,
                                sphere,
                                relative_peak_threshold=.5,
                                min_separation_angle=25,
                                return_sh=False)


fvtk.clear(ren)
fodf_peaks = fvtk.peaks(sf_peaks.peak_dirs, sf_peaks.peak_values, scale=1.3)
Example #30
0
stopping_values[:] = FA[..., None]

"""
For quality assurance we can also visualize a slice from the direction field
which we will use as the basis to perform the tracking.
"""

ren = fvtk.ren()

slice_no = data.shape[2] / 2

fvtk.add(ren, fvtk.peaks(csd_peaks.peak_dirs[:, :, slice_no:slice_no + 1],
                         stopping_values[:, :, slice_no:slice_no + 1]))

print('Saving illustration as csd_direction_field.png')
fvtk.record(ren, out_path='csd_direction_field.png', size=(900, 900))

"""
.. figure:: csd_direction_field.png
 :align: center

 **Direction Field (peaks)**

``EuDX`` [Garyfallidis12]_ is a fast algorithm that we use here to generate
streamlines. If the parameter ``seeds`` is a positive integer it will generate
that number of randomly placed seeds everywhere in the volume. Alternatively,
you can specify the exact seed points using an array (N, 3) where N is the
number of seed points. For simplicity, here we will use the first option
(random seeds). ``a_low`` is the threshold of the fist parameter
(``stopping_values``) which means that there will that tracking will stop in
regions with FA < 0.1.
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))
shutil.move("life_candidates.png", args.output_life_candidates)
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO)

    assert_inputs_exist(parser, [args.bvecs_in, args.eddyparams])
    assert_outputs_exists(parser, args,
                          [args.bvecs_out, args.trans, args.angles])

    _, bvecs = read_bvals_bvecs(None, args.bvecs_in)

    eddy = np.loadtxt(args.eddyparams)
    eddy_a = np.array(eddy)
    bvecs_rotated = np.zeros(bvecs.shape)
    norm_diff = np.zeros(bvecs.shape[0])
    angle = np.zeros(bvecs.shape[0])

    # Documentation here: http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/eddy/Faq
    # Will eddy rotate my bvecs for me?
    # No, it will not. There is nothing to prevent you from doing that
    # yourself though. eddy produces two output files, one with the corrected
    # images and another a text file with one row of parameters for each volume
    # in the --imain file. Columns 4-6 of these rows pertain to rotation
    # (in radians) around around the x-, y- and z-axes respectively.
    # eddy uses "pre-multiplication".
    # IMPORTANT: from various emails with FSL's people, we couldn't directly
    #            get the information about the handedness of the system.
    #            From the FAQ linked earlier, we deduced that the system
    #            is considered left-handed, and therefore the following
    #            matrices are correct.
    for i in range(len(bvecs)):
        theta_x = eddy_a[i, 3]
        theta_y = eddy_a[i, 4]
        theta_z = eddy_a[i, 5]
        Rx = np.array([[1, 0, 0], [0, np.cos(theta_x),
                                   np.sin(theta_x)],
                       [0, -np.sin(theta_x),
                        np.cos(theta_x)]])
        Ry = np.array([[np.cos(theta_y), 0, -np.sin(theta_y)], [0, 1, 0],
                       [np.sin(theta_y), 0,
                        np.cos(theta_y)]])
        Rz = np.array([[np.cos(theta_z), np.sin(theta_z), 0],
                       [-np.sin(theta_z), np.cos(theta_z), 0], [0, 0, 1]])
        v = bvecs[i, :]
        rotation_matrix = np.linalg.inv(np.dot(np.dot(Rx, Ry), Rz))
        v_rotated = np.dot(rotation_matrix, v)
        bvecs_rotated[i, :] = v_rotated
        norm_diff[i] = np.linalg.norm(v - v_rotated)
        if np.linalg.norm(v):
            angle[i] = np.arctan2(np.linalg.norm(np.cross(v, v_rotated)),
                                  np.dot(v, v_rotated))

    logging.info('%s mm is the maximum translation error', np.max(norm_diff))
    logging.info('%s degrees is the maximum rotation error',
                 np.max(angle) * 180 / np.pi)

    if args.vis:
        print('Red points are the original & Green points are the motion '
              'corrected ones')
        ren = fvtk.ren()
        sphere_actor = fvtk.point(bvecs,
                                  colors=fvtk.colors.red,
                                  opacity=1,
                                  point_radius=0.01,
                                  theta=10,
                                  phi=20)
        fvtk.add(ren, sphere_actor)
        sphere_actor_rot = fvtk.point(bvecs_rotated,
                                      colors=fvtk.colors.green,
                                      opacity=1,
                                      point_radius=0.01,
                                      theta=10,
                                      phi=20)
        fvtk.add(ren, sphere_actor_rot)
        fvtk.show(ren)

        fvtk.record(ren,
                    n_frames=1,
                    out_path=args.bvecs_out + '.png',
                    size=(600, 600))

    np.savetxt(args.bvecs_out, bvecs_rotated.T)

    if args.trans:
        np.savetxt(args.trans, norm_diff)

    if args.angles:
        np.savetxt(args.angles, angle * 180 / np.pi)
Example #33
0
Fit the SHORE model to the data
"""

asmfit = asm.fit(data_small)

"""
Load an odf reconstruction sphere
"""

sphere = get_sphere('symmetric724')

"""
Compute the ODF  
"""

odf = asmfit.odf(sphere)
print('odf.shape (%d, %d, %d)' % odf.shape)

"""
Display the ODFs
"""

r = fvtk.ren()
fvtk.add(r, fvtk.sphere_funcs(odf, sphere, colormap='jet'))
fvtk.show(r)
fvtk.record(r, n_frames=1, out_path='odfs.png', size=(600, 600))
"""
.. include:: ../links_names.inc

"""
Example #34
0
streamlines_actor = fvtk.streamtube(
    list(move_streamlines(plot_streamlines, inv(t1_aff))),
    line_colors(streamlines), linewidth=0.1)

vol_actor = fvtk.slicer(t1_data)

vol_actor.display(40, None, None)
vol_actor2 = vol_actor.copy()
vol_actor2.display(None, None, 35)

ren = fvtk.ren()
fvtk.add(ren, streamlines_actor)
fvtk.add(ren, vol_actor)
fvtk.add(ren, vol_actor2)

fvtk.record(ren, n_frames=1, out_path='sfm_streamlines.png',
            size=(800, 800))

"""
.. figure:: sfm_streamlines.png
   :align: center

   **Sparse Fascicle Model tracks**

Finally, we can save these streamlines to a 'trk' file, for use in other
software, or for further analysis.
"""

from dipy.io.trackvis import save_trk
save_trk("sfm_detr.trk", streamlines, affine, labels.shape)

"""
# 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))
centers = np.asarray(map(feature.extract, streamlines))

# Color each center of mass according to the cluster they belong to.
rng = np.random.RandomState(42)
colormap = fvtk.create_colormap(np.arange(len(clusters)))
colormap_full = np.ones((len(streamlines), 3))
for cluster, color in zip(clusters, colormap):
    colormap_full[cluster.indices] = color

# Visualization
ren = fvtk.ren()
fvtk.clear(ren)
ren.SetBackground(0, 0, 0)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
fvtk.add(ren, fvtk.point(centers[:, 0, :], colormap_full, point_radius=0.2))
fvtk.record(ren, n_frames=1, out_path='center_of_mass_feature.png', size=(600, 600))

"""
.. figure:: center_of_mass_feature.png
   :align: center

   **Showing the center of mass of each streamline and colored according to
   the QuickBundles results**.

.. _clustering-examples-MidpointFeature:

Midpoint Feature
================
**What:** Instances of `MidpointFeature` extract the middle point of a
streamline. If there is an even number of points, the feature will then
correspond to the point halfway between the two middle points.
Example #37
0
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))

"""
.. figure:: corpuscallosum_axial.png
   :align: center

   **Corpus Callosum Axial**

.. include:: ../links_names.inc

.. figure:: corpuscallosum_sagittal.png
   :align: center
clusters = qb.cluster(streamlines)

"""
We will now visualize the clustering result.
"""

# Color each streamline according to the cluster they belong to.
colormap = fvtk.create_colormap(np.ravel(clusters.centroids))
colormap_full = np.ones((len(streamlines), 3))
for cluster, color in zip(clusters, colormap):
    colormap_full[cluster.indices] = color

ren = fvtk.ren()
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.streamtube(streamlines, colormap_full))
fvtk.record(ren, n_frames=1, out_path='fornix_clusters_arclength.png', size=(600, 600))

"""
.. figure:: fornix_clusters_arclength.png
   :align: center

   **Showing the different clusters obtained by using the arc length**.


Extending `Metric`
==================
This section will guide you through the creation of a new metric that can be
used in the context of this clustering framework. For a list of available
metrics in Dipy see :ref:`example_segment_clustering_metrics`.

Assuming a set of streamlines, we want a metric that computes the cosine
Example #39
0
"""
"""
For the ODF simulation we will need a sphere. Because we are interested in a
simulation of only a single voxel, we can use a sphere with very high
resolution. We generate that by subdividing the triangles of one of Dipy's
cached spheres, which we can read in the following way.
"""

sphere = get_sphere('symmetric724')
sphere = sphere.subdivide(2)

odf = multi_tensor_odf(sphere.vertices, mevals, angles, fractions)

from dipy.viz import fvtk

ren = fvtk.ren()

odf_actor = fvtk.sphere_funcs(odf, sphere)
odf_actor.RotateX(90)

fvtk.add(ren, odf_actor)

print('Saving illustration as multi_tensor_simulation')
fvtk.record(ren, out_path='multi_tensor_simulation.png', size=(300, 300))
"""
.. figure:: multi_tensor_simulation.png
   :align: center

   **Simulating a MultiTensor ODF**
"""
Example #40
0
evals = tenfit.evals[13:43, 44:74, 28:29]
evecs = tenfit.evecs[13:43, 44:74, 28:29]

"""
We can color the ellipsoids using the ``color_fa`` values that we calculated
above. In this example we additionally normalize the values to increase the
contrast.
"""

cfa = RGB[13:43, 44:74, 28:29]
cfa /= cfa.max()

fvtk.add(ren, fvtk.tensor(evals, evecs, cfa, sphere))

print('Saving illustration as tensor_ellipsoids.png')
fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png', size=(600, 600))

"""
.. figure:: tensor_ellipsoids.png
   :align: center

   **Tensor Ellipsoids**.
"""

fvtk.clear(ren)

"""
Finally, we can visualize the tensor orientation distribution functions
for the same area as we did with the ellipsoids.
"""
Example #41
0
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
r = fvtk.ren()
fvtk.add(r, vol_actor)
fvtk.add(r, vol_actor2)
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))
"""
.. figure:: corpuscallosum_axial.png
   :align: center

   **Corpus Callosum Axial**

.. include:: ../links_names.inc

.. figure:: corpuscallosum_sagittal.png
Example #42
0
fit_wls = dti_wls.fit(data)

fa1 = fit_wls.fa
evals1 = fit_wls.evals
evecs1 = fit_wls.evecs
cfa1 = dti.color_fa(fa1, evecs1)
sphere = dpd.get_sphere('symmetric724')
"""
We visualize the ODFs in the ROI using fvtk:
"""

ren = fvtk.ren()
fvtk.add(ren, fvtk.tensor(evals1, evecs1, cfa1, sphere))
print('Saving illustration as tensor_ellipsoids_wls.png')
fvtk.record(ren,
            n_frames=1,
            out_path='tensor_ellipsoids_wls.png',
            size=(600, 600))
"""
.. figure:: tensor_ellipsoids_wls.png
   :align: center

   Tensor Ellipsoids.
"""

fvtk.clear(ren)
"""
Next, we corrupt the data with some noise. To simulate a subject that moves
intermittently, we will replace a few of the images with a very low signal
"""

noisy_data = np.copy(data)
Example #43
0
from dipy.viz import fvtk
r=fvtk.ren()
fvtk.add(r,fvtk.line(ten_tracks,fvtk.red,opacity=0.05))
gqs_tracks2=[t+np.array([10,0,0]) for t in gqs_tracks]
fvtk.add(r,fvtk.line(gqs_tracks2,fvtk.green,opacity=0.05))

"""
Press 's' to save this screenshot when you have displayed it with ``fvtk.show``.
Or you can even record a video using ``fvtk.record``.

You would show the figure with something like::

    fvtk.show(r,png_magnify=1,size=(600,600))

To record a video of 50 frames of png, something like::

    fvtk.record(r,cam_pos=(0,40,-40),cam_focal=(5,0,0),n_frames=50,magnification=1,out_path='nii_2_tracks',size=(600,600),bgr_color=(0,0,0))

.. figure:: nii_2_tracks1000000.png
   :align: center

   **Same region of interest with different underlying voxel representations generates different tractographies**.

"""

# Here's how we make the figure.
print('Saving illustration as nii_2_tracks1000000.png')
fvtk.record(r,n_frames=1,out_path='nii_2_tracks',size=(600,600))

Example #44
0
fvtk.add(ren, lineactor)

# Horizontal (axial) slice of T1 data
vol_actor1 = fvtk.slicer(t1_data, affine=affine)
vol_actor1.display(None, None, 20)
fvtk.add(ren, vol_actor1)

# Vertical (sagittal) slice of T1 data
vol_actor2 = fvtk.slicer(t1_data, affine=affine)
vol_actor2.display(35, None, None)
fvtk.add(ren, vol_actor2)

# Show original fibers
fvtk.camera(ren, pos=(-264, 285, 155), focal=(0, -14, 9), viewup=(0, 0, 1),
            verbose=False)
fvtk.record(ren, n_frames=1, out_path='OR_before.png', size=(900, 900))

# Show thresholded fibers
fvtk.rm(ren, lineactor)
fvtk.add(ren, actor.line(fbc_sl_thres, clrs_thres, linewidth=0.2))
fvtk.record(ren, n_frames=1, out_path='OR_after.png', size=(900, 900))

"""
.. figure:: OR_before.png
   :align: center

   The optic radiation obtained through probabilistic tractography colored by
   local fiber to bundle coherence.

.. figure:: OR_after.png
   :align: center
Example #45
0
def record_slice(fname, data, k, show=False):
    ren = fvtk.ren()
    fvtk.add(ren, fvtk.slicer(data, plane_k=[k]))
    if show:
        fvtk.show(ren)
    fvtk.record(ren, out_path=fname, size=(600, 600))
Example #46
0
fvtk.add(ren, lineactor)

# Horizontal (axial) slice of T1 data
vol_actor1 = fvtk.slicer(t1_data, affine=affine)
vol_actor1.display(None, None, 20)
fvtk.add(ren, vol_actor1)

# Vertical (sagittal) slice of T1 data
vol_actor2 = fvtk.slicer(t1_data, affine=affine)
vol_actor2.display(35, None, None)
fvtk.add(ren, vol_actor2)

# Show original fibers
fvtk.camera(ren, pos=(-264, 285, 155), focal=(0, -14, 9), viewup=(0, 0, 1),
            verbose=False)
fvtk.record(ren, n_frames=1, out_path='OR_before.png', size=(900, 900))

# Show thresholded fibers
fvtk.rm(ren, lineactor)
fvtk.add(ren, actor.line(fbc_sl_thres, clrs_thres, linewidth=0.2))
fvtk.record(ren, n_frames=1, out_path='OR_after.png', size=(900, 900))

"""
.. figure:: OR_before.png
   :align: center

   The optic radiation obtained through probabilistic tractography colored by 
   local fiber to bundle coherence.

.. figure:: OR_after.png
   :align: center
Example #47
0
# Color each center of mass according to the cluster they belong to.
rng = np.random.RandomState(42)
colormap = fvtk.create_colormap(np.arange(len(clusters)))
colormap_full = np.ones((len(streamlines), 3))
for cluster, color in zip(clusters, colormap):
    colormap_full[cluster.indices] = color

# Visualization
ren = fvtk.ren()
fvtk.clear(ren)
ren.SetBackground(0, 0, 0)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
fvtk.add(ren, fvtk.point(centers[:, 0, :], colormap_full, point_radius=0.2))
fvtk.record(ren,
            n_frames=1,
            out_path='center_of_mass_feature.png',
            size=(600, 600))
"""
.. figure:: center_of_mass_feature.png
   :align: center

   **Showing the center of mass of each streamline and colored according to
   the QuickBundles results**.

.. _clustering-examples-MidpointFeature:

Midpoint Feature
================
**What:** Instances of `MidpointFeature` extract the middle point of a
streamline. If there is an even number of points, the feature will then
correspond to the point halfway between the two middle points.
Example #48
0

"""
Reduce the number of points for faster visualization using the ``approx_polygon_track`` algorithm which retains points depending on how much they are need to define the shape of the track:
"""

T=[td.approx_polygon_track(t) for t in T]

"""
Show the initial *Fornix* dataset:
"""

r=fvtk.ren()
fvtk.add(r,fvtk.line(T,fvtk.white,opacity=1))
#fvtk.show(r)
fvtk.record(r,n_frames=1,out_path='fornix_initial',size=(600,600))

"""
.. figure:: fornix_initial1000000.png
   :align: center

   **Initial Fornix dataset**.
"""

"""
Show the *Fornix* after clustering (with random bundle colors):
"""

fvtk.clear(r)
colors=np.zeros((len(T),3))
for c in C:
md1 = dti.mean_diffusivity(tenfit.evals)
nibabel.save(nibabel.Nifti1Image(md1.astype(numpy.float32), img.affine),
             'output_md.nii')
shutil.move('output_md.nii', args.output_nifti1_md)
move_directory_files(input_dir, args.output_nifti1_md_files_path, copy=True)

fa = numpy.clip(fa, 0, 1)
rgb = color_fa(fa, tenfit.evecs)
nibabel.save(nibabel.Nifti1Image(numpy.array(255 * rgb, 'uint8'), img.affine),
             'output_rgb.nii')
shutil.move('output_rgb.nii', args.output_nifti1_rgb)
move_directory_files(input_dir, args.output_nifti1_rgb_files_path, copy=True)

sphere = get_sphere('symmetric724')
ren = fvtk.ren()

evals = tenfit.evals[13:43, 44:74, 28:29]
evecs = tenfit.evecs[13:43, 44:74, 28:29]
cfa = rgb[13:43, 44:74, 28:29]
cfa /= cfa.max()
fvtk.add(ren, fvtk.tensor(evals, evecs, cfa, sphere))
fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png', size=(600, 600))
shutil.move('tensor_ellipsoids.png', args.output_png_ellipsoids)

fvtk.clear(ren)

tensor_odfs = tenmodel.fit(data[20:50, 55:85, 38:39]).odf(sphere)
fvtk.add(ren, fvtk.sphere_funcs(tensor_odfs, sphere, colormap=None))
fvtk.record(ren, n_frames=1, out_path='tensor_odfs.png', size=(600, 600))
shutil.move('tensor_odfs.png', args.output_png_odfs)
Example #50
0
                   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,
          csapeaks.peak_indices,
          seeds=10000,
          odf_vertices=sphere.vertices,
          ang_thr=20.,
Example #51
0
axial_middle = data.shape[2] / 2
plt.figure('Showing the datasets')
plt.subplot(1, 2, 1).set_axis_off()
plt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower')
plt.subplot(1, 2, 2).set_axis_off()
plt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower')
plt.show()
plt.savefig('data.png', bbox_inches='tight')

from dipy.data import get_sphere
sphere = get_sphere('symmetric642')

from dipy.viz import fvtk
ren = fvtk.ren()

evals = tenfit.evals[55:85, 80:90, 40:45]
evecs = tenfit.evecs[55:85, 80:90, 40:45]

cfa = Rgbv[55:80, 80:90, 40:45]

#print cfa[1,1,1]
cfa /= cfa.max()

fvtk.add(ren, fvtk.tensor(evals, evecs, cfa))

fvtk.show(ren)
print('Saving illustration as fa.png')
fvtk.record(ren, n_frames=1, out_path='fa.png', size=(600, 600))
print "Hello World!"
Example #52
0
We can double-check that we have a good response function by visualizing the
response function's ODF. Here is how you would do that:
"""

from dipy.viz import fvtk
ren = fvtk.ren()
evals = response[0]
evecs = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]).T
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')
from dipy.sims.voxel import single_tensor_odf
response_odf = single_tensor_odf(sphere.vertices, evals, evecs)
response_actor = fvtk.sphere_funcs(response_odf, sphere)
fvtk.add(ren, response_actor)
print('Saving illustration as csd_response.png')
fvtk.record(ren, out_path='csd_response.png', size=(200, 200))

"""
.. figure:: csd_response.png
   :align: center

   **Estimated response function**.

"""

fvtk.rm(ren, response_actor)

"""
Depending on the dataset, FA threshold may not be the best way to find the
best possible response function. For one, it depends on the diffusion tensor
(FA and first eigenvector), which has lower accuracy at high
# 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
   :align: center

   **Corpus Callosum Deterministic**

We've created a deterministic set of streamlines, so called because if you
repeat the fiber tracking (keeping all the inputs the same) you will 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.
"""

from dipy.io.trackvis import save_trk
Example #54
0
Compute the ODFs
The radial order s can be increased to sharpen the results, but it might
also make the odfs noisier. Always check the results visually.
"""

odf = mapfit_both_iso.odf(sphere, s=2)
print('odf.shape (%d, %d, %d, %d)' % odf.shape)
"""
Display the ODFs
"""

r = fvtk.ren()
sfu = fvtk.sphere_funcs(odf, sphere, colormap='jet')
sfu.RotateX(-90)
fvtk.add(r, sfu)
fvtk.record(r, n_frames=1, out_path='odfs.png', size=(600, 600))
"""
.. figure:: odfs.png
   :align: center

   **Orientation distribution functions**.

.. [Ozarslan2013]_ Ozarslan E. et. al, "Mean apparent propagator (MAP) MRI: A
               novel diffusion imaging method for mapping tissue
               microstructure", NeuroImage, 2013.

.. [Fick2016]_ Fick, Rutger HJ, et al. "MAPL: Tissue microstructure estimation
               using Laplacian-regularized MAP-MRI and its application to HCP
               data." NeuroImage (2016).

.. [Craven1978]_ Craven et al. "Smoothing Noisy Data with Spline Functions."
Example #55
0
ren.SetBackground(*fvtk.colors.white)
bundle_actor = fvtk.streamtube(bundle, fvtk.colors.red, linewidth=0.3)

fvtk.add(ren, bundle_actor)

bundle_actor2 = fvtk.streamtube(bundle_downsampled, fvtk.colors.red, linewidth=0.3)
bundle_actor2.SetPosition(0, 40, 0)

bundle_actor3 = fvtk.streamtube(bundle_downsampled2, fvtk.colors.red, linewidth=0.3)
bundle_actor3.SetPosition(0, 80, 0)

fvtk.add(ren, bundle_actor2)
fvtk.add(ren, bundle_actor3)

fvtk.camera(ren, pos=(0, 0, 0), focal=(30, 0, 0))
fvtk.record(ren, out_path="simulated_cosine_bundle.png", size=(900, 900))

"""
.. figure:: simulated_cosine_bundle.png
   :align: center

   **Initial bundle (down), downsampled at 12 equidistant points (middle), downsampled not equidistantly(up)**

From the figure above we can see that all 3 bundles look quite similar. However,
when we plot the histogram of the number of points used for each streamline, it
becomes obvious that we have managed to reduce in a great amount the size of the
initial dataset.
"""

import matplotlib.pyplot as plt
Example #56
0
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**.

.. [Garyfallidis12] Garyfallidis E., "Towards an accurate brain tractography", PhD thesis, University of Cambridge, 2012.

.. include:: ../links_names.inc

"""
Example #57
0
plt.figure('Showing the datasets')
plt.subplot(1, 2, 1).set_axis_off()
plt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower')
plt.subplot(1, 2, 2).set_axis_off()
plt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower')
plt.show()
plt.savefig('data.png', bbox_inches='tight')


from dipy.data import get_sphere
sphere = get_sphere('symmetric642')

from dipy.viz import fvtk
ren = fvtk.ren()

evals=tenfit.evals[55:85,80:90,40:45]
evecs=tenfit.evecs[55:85,80:90,40:45]

cfa = Rgbv[55:80, 80:90, 40:45]

#print cfa[1,1,1]
cfa /= cfa.max()

fvtk.add(ren, fvtk.tensor(evals, evecs, cfa))


fvtk.show(ren)
print('Saving illustration as fa.png')
fvtk.record(ren, n_frames=1, out_path='fa.png', size=(600, 600))
print "Hello World!"