Exemplo n.º 1
0
def show_bundles(bundles,
                 colors=None,
                 show=True,
                 fname=None,
                 fa=False,
                 str_tube=False):

    ren = window.Renderer()
    ren.SetBackground(1., 1, 1)
    if str_tube:
        bundle_actor = actor.streamtube(bundles, colors, linewidth=0.5)
        ren.add(bundle_actor)
    else:
        for (i, bundle) in enumerate(bundles):
            color = colors[i]
            #         lines_actor = actor.streamtube(bundle, color, linewidth=0.05

            lines_actor = actor.line(bundle, color, linewidth=2.5)
            #lines_actor.RotateX(-90)
            #lines_actor.RotateZ(90)
            ren.add(lines_actor)

    if fa:
        fa, affine_fa = load_nifti(
            '/Users/alex/code/Wenlin/data/wenlin_results/bmfaN54900.nii.gz')
        fa_actor = actor.slicer(fa, affine_fa)
        ren.add(fa_actor)

    if show:
        window.show(ren)
    if fname is not None:
        sleep(1)
        window.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Exemplo n.º 2
0
def window_show_test(bundles, mask_roi, anat, interactive=True, outpath=None):
    """

    :param bundles:
    :param mask_roi:
    :param anat:
    :param interactive:
    :param outpath:
    :return:
    """

    candidate_streamlines_actor = actor.streamtube(
        bundles, cmap.line_colors(candidate_sl))
    ROI_actor = actor.contour_from_roi(mask_roi,
                                       color=(1., 1., 0.),
                                       opacity=0.5)

    ren = window.Renderer()
    if anat:
        vol_actor = actor.slicer(anat)
        vol_actor.display(x=40)
        vol_actor2 = vol_actor.copy()
        vol_actor2.display(z=35)

    # Add display objects to canvas
    ren.add(candidate_streamlines_actor)
    ren.add(ROI_actor)
    ren.add(vol_actor)
    ren.add(vol_actor2)
    if outpath is not None:
        window.record(ren, n_frames=1, out_path=outpath, size=(800, 800))
    if interactive:
        window.show(ren)
Exemplo n.º 3
0
def test_order_transparent():

    renderer = window.Renderer()

    lines = [
        np.array([[-1, 0, 0.], [1, 0, 0.]]),
        np.array([[-1, 1, 0.], [1, 1, 0.]])
    ]
    colors = np.array([[1., 0., 0.], [0., .5, 0.]])
    stream_actor = actor.streamtube(lines, colors, linewidth=0.3, opacity=0.5)

    renderer.add(stream_actor)

    renderer.reset_camera()

    # green in front
    renderer.elevation(90)
    renderer.camera().OrthogonalizeViewUp()
    renderer.reset_clipping_range()

    renderer.reset_camera()

    not_xvfb = os.environ.get("TEST_WITH_XVFB", False)

    if not_xvfb:
        arr = window.snapshot(renderer,
                              fname='green_front.png',
                              offscreen=True,
                              order_transparent=False)
    else:
        arr = window.snapshot(renderer,
                              fname='green_front.png',
                              offscreen=False,
                              order_transparent=False)

    # therefore the green component must have a higher value (in RGB terms)
    npt.assert_equal(arr[150, 150][1] > arr[150, 150][0], True)

    # red in front
    renderer.elevation(-180)
    renderer.camera().OrthogonalizeViewUp()
    renderer.reset_clipping_range()

    if not_xvfb:
        arr = window.snapshot(renderer,
                              fname='red_front.png',
                              offscreen=True,
                              order_transparent=True)
    else:
        arr = window.snapshot(renderer,
                              fname='red_front.png',
                              offscreen=False,
                              order_transparent=True)

    # therefore the red component must have a higher value (in RGB terms)
    npt.assert_equal(arr[150, 150][0] > arr[150, 150][1], True)
Exemplo n.º 4
0
def test_streamtube_and_line_actors():
    renderer = window.renderer()

    line1 = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2.]])
    line2 = line1 + np.array([0.5, 0., 0.])

    lines = [line1, line2]
    colors = np.array([[1, 0, 0], [0, 0, 1.]])
    c = actor.line(lines, colors, linewidth=3)
    window.add(renderer, c)

    c = actor.line(lines, colors, spline_subdiv=5, linewidth=3)
    window.add(renderer, c)

    # create streamtubes of the same lines and shift them a bit
    c2 = actor.streamtube(lines, colors, linewidth=.1)
    c2.SetPosition(2, 0, 0)
    window.add(renderer, c2)

    arr = window.snapshot(renderer)

    report = window.analyze_snapshot(arr,
                                     colors=[(255, 0, 0), (0, 0, 255)],
                                     find_objects=True)

    npt.assert_equal(report.objects, 4)
    npt.assert_equal(report.colors_found, [True, True])

    # as before with splines
    c2 = actor.streamtube(lines, colors, spline_subdiv=5, linewidth=.1)
    c2.SetPosition(2, 0, 0)
    window.add(renderer, c2)

    arr = window.snapshot(renderer)

    report = window.analyze_snapshot(arr,
                                     colors=[(255, 0, 0), (0, 0, 255)],
                                     find_objects=True)

    npt.assert_equal(report.objects, 4)
    npt.assert_equal(report.colors_found, [True, True])
Exemplo n.º 5
0
def test_streamtube_and_line_actors():
    renderer = window.renderer()

    line1 = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2.]])
    line2 = line1 + np.array([0.5, 0., 0.])

    lines = [line1, line2]
    colors = np.array([[1, 0, 0], [0, 0, 1.]])
    c = actor.line(lines, colors, linewidth=3)
    window.add(renderer, c)

    c = actor.line(lines, colors, spline_subdiv=5, linewidth=3)
    window.add(renderer, c)

    # create streamtubes of the same lines and shift them a bit
    c2 = actor.streamtube(lines, colors, linewidth=.1)
    c2.SetPosition(2, 0, 0)
    window.add(renderer, c2)

    arr = window.snapshot(renderer)

    report = window.analyze_snapshot(arr,
                                     colors=[(255, 0, 0), (0, 0, 255)],
                                     find_objects=True)

    npt.assert_equal(report.objects, 4)
    npt.assert_equal(report.colors_found, [True, True])

    # as before with splines
    c2 = actor.streamtube(lines, colors, spline_subdiv=5, linewidth=.1)
    c2.SetPosition(2, 0, 0)
    window.add(renderer, c2)

    arr = window.snapshot(renderer)

    report = window.analyze_snapshot(arr,
                                     colors=[(255, 0, 0), (0, 0, 255)],
                                     find_objects=True)

    npt.assert_equal(report.objects, 4)
    npt.assert_equal(report.colors_found, [True, True])
def show_template_bundles(bundles, static, show=True, fname=None):
    scene = window.Scene()
    template_actor = actor.slicer(static)
    scene.add(template_actor)

    lines_actor = actor.streamtube(bundles,
                                   window.colors.orange,
                                   linewidth=0.3)
    scene.add(lines_actor)

    if show:
        window.show(scene)
    if fname is not None:
        window.record(scene, n_frames=1, out_path=fname, size=(900, 900))
Exemplo n.º 7
0
def show_both_bundles(bundles, colors=None, show=True, fname=None):

    scene = window.Scene()
    scene.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        streamtube_actor = actor.streamtube(bundle, color, linewidth=0.3)
        streamtube_actor.RotateX(-90)
        streamtube_actor.RotateZ(90)
        scene.add(streamtube_actor)
    if show:
        window.show(scene)
    elif fname is not None:
        window.record(scene, out_path=fname, size=(900, 900))
Exemplo n.º 8
0
def show_fascicles_wholebrain(s_list,
                              vec_vols,
                              folder_name,
                              mask_type,
                              downsamp=1,
                              scale=[3, 6],
                              hue=[0.25, -0.05],
                              saturation=[0.1, 1.0]):

    s_img = folder_name + r'\streamlines' + r'\fascicles_AxCaliber_weighted_3d_' + mask_type + '.png'
    #hue = [0.4, 0.7] # blues
    #hue = [0.25, -0.05] #Hot
    #hue = [0, 1] #All

    weighted = True
    '''
    if weighted:
        scale = [0, 3]


    else:
        scale = [0, 6]
        vec_vols = np.log(vec_vols)
        #vec_vols = vec_vols-np.nanmin(vec_vols)/(np.nanmax(vec_vols)-np.nanmin(vec_vols))
    '''

    if downsamp != 1:
        vec_vols = vec_vols[::downsamp]
        s_list = s_list[::downsamp]

    lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                           saturation_range=saturation,
                                           scale_range=scale)
    bar = actor.scalar_bar(lut_cmap)
    #w_actor = actor.line(s_list, vec_vols, linewidth=1.2, lookup_colormap=lut_cmap)
    w_actor = actor.streamtube(s_list,
                               vec_vols,
                               linewidth=0.6,
                               lookup_colormap=lut_cmap)

    #w_actor = actor.streamtube(s_list, vec_vols, linewidth=0.3, lookup_colormap=lut_cmap)
    #w_actor = actor.line(s_list, linewidth=1.0, lookup_colormap=lut_cmap)

    r = window.Renderer()
    #r.SetBackground(*window.colors.white)
    r.add(w_actor)
    r.add(bar)
    window.show(r)
    r.set_camera(r.camera_info())
    window.record(r, out_path=s_img, size=(800, 800))
Exemplo n.º 9
0
def show_both_bundles(bundles, colors=None, show=True, fname=None):

    ren = window.Renderer()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines_actor = actor.streamtube(bundle, color, linewidth=0.3)
        lines_actor.RotateX(-90)
        lines_actor.RotateZ(90)
        ren.add(lines_actor)
    if show:
        window.show(ren)
    if fname is not None:
        sleep(1)
        window.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Exemplo n.º 10
0
def show_both_bundles(bundles, colors=None, show=True, fname=None):

    ren = window.Renderer()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines_actor = actor.streamtube(bundle, color, linewidth=0.3)
        lines_actor.RotateX(-90)
        lines_actor.RotateZ(90)
        ren.add(lines_actor)
    if show:
        window.show(ren)
    if fname is not None:
        sleep(1)
        window.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Exemplo n.º 11
0
def viewclusters(clusters,streamlines, outpath=None, interactive=False):
    #Linked to viewing clusters. If outpath given, will save info to right location, if interactive, will show window
    colormap = actor.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

    scene = window.Scene()
    scene.SetBackground(1, 1, 1)
    scene.add(actor.streamtube(streamlines, colormap_full))
    window.record(scene, out_path=outpath, size=(600, 600))

    # Enables/disables interactive visualization
    if interactive:
        window.show(scene)
Exemplo n.º 12
0
def test_order_transparent():

    renderer = window.Renderer()

    lines = [np.array([[-1, 0, 0.], [1, 0, 0.]]),
             np.array([[-1, 1, 0.], [1, 1, 0.]])]
    colors = np.array([[1., 0., 0.], [0., .5, 0.]])
    stream_actor = actor.streamtube(lines, colors, linewidth=0.3, opacity=0.5)

    renderer.add(stream_actor)

    renderer.reset_camera()

    # green in front
    renderer.elevation(90)
    renderer.camera().OrthogonalizeViewUp()
    renderer.reset_clipping_range()

    renderer.reset_camera()

    not_xvfb = os.environ.get("TEST_WITH_XVFB", False)

    if not_xvfb:
        arr = window.snapshot(renderer, fname='green_front.png',
                              offscreen=True, order_transparent=False)
    else:
        arr = window.snapshot(renderer, fname='green_front.png',
                              offscreen=False, order_transparent=False)

    # therefore the green component must have a higher value (in RGB terms)
    npt.assert_equal(arr[150, 150][1] > arr[150, 150][0], True)

    # red in front
    renderer.elevation(-180)
    renderer.camera().OrthogonalizeViewUp()
    renderer.reset_clipping_range()

    if not_xvfb:
        arr = window.snapshot(renderer, fname='red_front.png',
                              offscreen=True, order_transparent=True)
    else:
        arr = window.snapshot(renderer, fname='red_front.png',
                              offscreen=False, order_transparent=True)

    # therefore the red component must have a higher value (in RGB terms)
    npt.assert_equal(arr[150, 150][0] > arr[150, 150][1], True)
Exemplo n.º 13
0
def show_tracts(hue, saturation, scale, streamlines, mean_vol_per_tract,
                folder_name, fig_type):
    from dipy.viz import window, actor
    lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                           saturation_range=saturation,
                                           scale_range=scale)
    streamlines_actor = actor.streamtube(streamlines,
                                         mean_vol_per_tract,
                                         linewidth=0.5,
                                         lookup_colormap=lut_cmap)
    bar = actor.scalar_bar(lut_cmap)
    r = window.Scene()
    r.add(streamlines_actor)
    r.add(bar)
    mean_pasi_weighted_img = f'{folder_name}{os.sep}streamlines{os.sep}mean_pasi_weighted{fig_type}.png'
    window.show(r)
    r.set_camera(r.camera_info())
    window.record(r, out_path=mean_pasi_weighted_img, size=(800, 800))
Exemplo n.º 14
0
    def update(self):
        if not self.has_changed:
            return  # Nothing changed

        self.has_changed = False

        # Update centroids actor.
        # Remove old centroid actors.
        self.ren.rm(*self.centroid_actors)

        # Create an actor for every centroid.
        self.centroid_actors = []
        for cluster, color in zip(self.clusters, self.clusters_colors):
            centroid_actor = actor.streamtube([cluster.centroid],
                                              colors=color,
                                              linewidth=0.1 +
                                              0.1 * np.log(len(cluster)))
            centroid_actor.SetVisibility(self.centroids_visible)
            self.ren.add(centroid_actor)
            # TODO add a click callback
            self.centroid_actors.append(centroid_actor)
Exemplo n.º 15
0
    def add_actors(ren, bundles):
        for name in bundles:
            streamlines = None
            for filename in files:
                if name in os.path.basename(filename):
                    print("Loading: {}".format(os.path.basename(filename)))
                    streamlines = nib.streamlines.load(filename).streamlines
                    break
            if streamlines is None:
                print("Bundle not found: {}".format(name))
                continue

            idx = np.arange(len(streamlines))
            rng.shuffle(idx)
            streamlines = streamlines[idx][:subsample]
            color = bundle2color[name]
            act = actor.streamtube(
                streamlines,
                colors=np.asarray(color) / 255.,
                opacity=1.,
                linewidth=0.3,
            )
            ren.add(act)
Exemplo n.º 16
0
feature = VectorOfEndpointsFeature()
metric = CosineMetric(feature)
qb = QuickBundles(threshold=0.1, metric=metric)
clusters = qb.cluster(streamlines)

# Color each streamline according to the cluster they belong to.
colormap = actor.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
scene = window.Scene()
scene.clear()
scene.SetBackground(0, 0, 0)
scene.add(actor.streamtube(streamlines, colormap_full))
window.record(scene, out_path='cosine_metric.png', size=(600, 600))
if interactive:
    window.show(scene)

"""
.. figure:: cosine_metric.png
   :align: center

   Showing the streamlines colored according to their orientation.

.. include:: ../links_names.inc

References
----------
Exemplo n.º 17
0
qb = QuickBundles(threshold=25.)
clusters = qb.cluster(s)

print("Nb. clusters:", len(clusters))
print("Cluster sizes:", map(len, clusters))
print("Small clusters:", clusters < 10)
print("Streamlines indices of the first cluster:\n", clusters[0].indices)
print("Centroid of the last cluster:\n", clusters[-1].centroid)

interactive = True

ren = window.Renderer()
'''
ren.SetBackground(1, 1, 1)
ren.add(actor.streamtube(streamlines, window.colors.white))
if interactive:
    window.show(ren)
'''

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

window.clear(ren)
ren.SetBackground(1, 1, 1)
ren.add(actor.streamtube(s, window.colors.white, opacity=0.05))
ren.add(
    actor.streamtube(
        [clusters.centroids[i] for i in np.where(clusters > 9)[0]],
        colormap,
        linewidth=0.4))
if interactive:
    window.show(ren)
Exemplo n.º 18
0
           [  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.
"""

# Enables/disables interactive visualization
interactive = False

ren = window.Renderer()
ren.SetBackground(1, 1, 1)
ren.add(actor.streamtube(streamlines, window.colors.white))
window.record(ren, out_path='fornix_initial.png', size=(600, 600))
if interactive:
    window.show(ren)

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

   Initial Fornix dataset.

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

colormap = actor.create_colormap(np.arange(len(clusters)))
"""


"""

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)
Exemplo n.º 20
0
           [  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.
"""

# Enables/disables interactive visualization
interactive = False

scene = window.Scene()
scene.SetBackground(1, 1, 1)
scene.add(actor.streamtube(streamlines, window.colors.white))
window.record(scene, out_path='fornix_initial.png', size=(600, 600))
if interactive:
    window.show(scene)

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

   Initial Fornix dataset.

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

colormap = colormap.create_colormap(np.arange(len(clusters)))
Exemplo n.º 21
0
def connective_streamlines_figuremaker(allstreamlines,
                                       ROI_streamlines,
                                       ROI_names,
                                       anat_path,
                                       threshold=10.,
                                       verbose=False):

    #streamlines = Streamlines(res['af.left'])
    #streamlines.extend(res['cst.right'])
    #streamlines.extend(res['cc_1'])
    world_coords = True

    # Cluster sizes: [64, 191, 47, 1]

    # Small clusters: array([False, False, False, True], dtype=bool)

    scene = window.Scene()
    scene.SetBackground(1, 1, 1)

    colors = [
        'white', 'cadmium_red_deep', 'misty_rose', 'slate_grey_dark',
        'ivory_black', 'chartreuse'
    ]
    colors = [
        window.colors.white, window.colors.cadmium_red_deep,
        window.colors.misty_rose, window.colors.slate_grey_dark,
        window.colors.ivory_black, window.colors.chartreuse
    ]
    i = 0
    for ROI in ROI_streamlines:
        ROI_streamline = allstreamlines[ROI]
        qb = QuickBundles(threshold=threshold)
        clusters = qb.cluster(ROI_streamline)
        if verbose:
            print("Nb. clusters:", len(clusters))
            print("Cluster sizes:", map(len, clusters))
            print("Small clusters:", clusters < 10)
            print("Streamlines indices of the first cluster:\n",
                  clusters[0].indices)
            print("Centroid of the last cluster:\n", clusters[-1].centroid)
        #if not world_coords:
        #    from dipy.tracking.streamline import transform_streamlines
        #    streamlines = transform_streamlines(ROI_streamline, np.linalg.inv(affine))
        scene = window.Scene()
        #stream_actor = actor.line(ROI_streamline)
        #scene.add(actor.streamtube(ROI_streamline, window.colors.misty_rose))
        scene.add(actor.streamtube(ROI_streamline, colors[i]))

        #if not world_coords:
        #    image_actor_z = actor.slicer(data, affine=np.eye(4))
        #else:
        #    image_actor_z = actor.slicer(data, affine)

        slicer_opacity = 0.6
        i = i + 1

    anat_nifti = load_nifti(anat_path)
    try:
        data = anat_nifti.data
    except AttributeError:
        data = anat_nifti[0]
    try:
        affine = anat_nifti.affine
    except AttributeError:
        affine = anat_nifti[1]
    shape = np.shape(data)
    image_actor_z = actor.slicer(data[:, :, :, 0], affine)
    image_actor_z.opacity(slicer_opacity)

    image_actor_x = image_actor_z.copy()
    x_midpoint = int(np.round(shape[0] / 2))
    image_actor_x.display_extent(x_midpoint, x_midpoint, 0, shape[1] - 1, 0,
                                 shape[2] - 1)

    image_actor_y = image_actor_z.copy()
    y_midpoint = int(np.round(shape[1] / 2))
    image_actor_y.display_extent(0, shape[0] - 1, y_midpoint, y_midpoint, 0,
                                 shape[2] - 1)

    scene.add(image_actor_z)
    scene.add(image_actor_x)
    scene.add(image_actor_y)
    global size
    size = scene.GetSize()
    show_m = window.ShowManager(scene, size=(1200, 900))
    show_m.initialize()

    interactive = True
    interactive = False
    if interactive:

        show_m.add_window_callback(win_callback)
        show_m.render()
        show_m.start()
    else:
        window.record(scene,
                      out_path='bundles_and_3_slices.png',
                      size=(1200, 900),
                      reset_camera=False)
Exemplo n.º 22
0
from __future__ import print_function
import numpy as np
from dipy.viz import window, actor, widget
from dipy.data import fetch_viz_icons, read_viz_icons

"""
First, we add a couple of streamtubes to the Renderer
"""

renderer = window.Renderer()

lines = [np.array([[-1, 0, 0.], [1, 0, 0.]]),
         np.array([[-1, 1, 0.], [1, 1, 0.]])]
colors = np.array([[1., 0., 0.], [0., .5, 0.]])
stream_actor = actor.streamtube(lines, colors, linewidth=0.3, lod=False)
renderer.add(stream_actor)

"""
The ``ShowManager`` allows to break the visualization process in steps so that
the widgets can be added and updated properly.
"""

show_manager = window.ShowManager(renderer, size=(800, 800),
                                  order_transparent=True)

"""
Next we add the widgets and their callbacks.
"""

qb = QuickBundles(threshold=2., metric=metric)
clusters = qb.cluster(streamlines)

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

# Color each streamline according to the cluster they belong to.
colormap = actor.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 = window.Renderer()
ren.SetBackground(1, 1, 1)
ren.add(actor.streamtube(streamlines, colormap_full))
window.record(ren, out_path='fornix_clusters_arclength.png', size=(600, 600))

# Enables/disables interactive visualization
interactive = False
if interactive:
    window.show(ren)

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

   Showing the different clusters obtained by using the arc length.


Extending `Metric`
Exemplo n.º 24
0
    def build_scene(self):

        scene = window.Renderer()
        for (t, streamlines) in enumerate(self.tractograms):
            if self.random_colors:
                colors = self.prng.random_sample(3)
            else:
                colors = None

            if self.cluster:

                print(' Clustering threshold {} \n'.format(self.cluster_thr))
                clusters = qbx_and_merge(streamlines,
                                         [40, 30, 25, 20, self.cluster_thr])
                self.tractogram_clusters[t] = clusters
                centroids = clusters.centroids
                print(' Number of centroids is {}'.format(len(centroids)))
                sizes = np.array([len(c) for c in clusters])
                linewidths = np.interp(sizes,
                                       [sizes.min(), sizes.max()], [0.1, 2.])
                centroid_lengths = np.array([length(c) for c in centroids])

                print(' Minimum number of streamlines in cluster {}'.format(
                    sizes.min()))

                print(' Maximum number of streamlines in cluster {}'.format(
                    sizes.max()))

                print(' Construct cluster actors')
                for (i, c) in enumerate(centroids):

                    centroid_actor = actor.streamtube([c],
                                                      colors,
                                                      linewidth=linewidths[i],
                                                      lod=False)
                    scene.add(centroid_actor)

                    cluster_actor = actor.line(clusters[i], lod=False)
                    cluster_actor.GetProperty().SetRenderLinesAsTubes(1)
                    cluster_actor.GetProperty().SetLineWidth(6)
                    cluster_actor.GetProperty().SetOpacity(1)
                    cluster_actor.VisibilityOff()

                    scene.add(cluster_actor)

                    # Every centroid actor (cea) is paired to a cluster actor
                    # (cla).

                    self.cea[centroid_actor] = {
                        'cluster_actor': cluster_actor,
                        'cluster': i,
                        'tractogram': t,
                        'size': sizes[i],
                        'length': centroid_lengths[i],
                        'selected': 0,
                        'expanded': 0
                    }

                    self.cla[cluster_actor] = {
                        'centroid_actor': centroid_actor,
                        'cluster': i,
                        'tractogram': t,
                        'size': sizes[i],
                        'length': centroid_lengths[i],
                        'selected': 0
                    }
                    apply_shader(self, cluster_actor)
                    apply_shader(self, centroid_actor)

            else:

                streamline_actor = actor.line(streamlines, colors=colors)
                streamline_actor.GetProperty().SetEdgeVisibility(1)
                streamline_actor.GetProperty().SetRenderLinesAsTubes(1)
                streamline_actor.GetProperty().SetLineWidth(6)
                streamline_actor.GetProperty().SetOpacity(1)
                scene.add(streamline_actor)
        return scene
Exemplo n.º 25
0
polydata_in = load_polydata(fib_file_name)
streamlines_in = get_streamlines(polydata_in)
streamlines = []

for line in streamlines_in:
    dist = line[:-1] - line[1:]
    line_length = np.sum(np.sqrt(np.sum(np.square(dist), axis=1)))
        
    if line_length > min_length:
        streamlines.append(line)

#streamlines_sub = streamlines
streamlines_sub = streamlines[::100]

print len(streamlines_in), len(streamlines_sub)

actor = streamtube(streamlines_sub, linewidth=linewidth, tube_sides=tube_sides, spline_subdiv=spline_subdiv)

renderer = window.Renderer()
renderer.add(actor)
my_window = window.show(renderer)

#objexporter = vtk.vtkOBJExporter()
#objexporter.SetInput(my_window)
#objexporter.SetFileName(save_file)
#objexporter.SetFileName("/home/eti/home_mint/Nic/s100_s100_tube_flow.obj")
#objexporter.Write()

#save_polydata(actor.GetMapper().GetInput(), save_file)
Exemplo n.º 26
0
    def add_cluster_actors(self, scene, tractograms,
                           threshold, enable_callbacks=True):
        """ Add streamline actors to the scene

        Parameters
        ----------
        scene : Scene
        tractograms : list
            list of tractograms
        threshold : float
            Cluster threshold
        enable_callbacks : bool
            Enable callbacks for selecting clusters
        """
        color_gen = distinguishable_colormap()
        for (t, sft) in enumerate(tractograms):
            streamlines = sft.streamlines

            if self.random_colors:
                colors = next(color_gen)
            else:
                colors = None

            if not self.world_coords:
                # TODO we need to read the affine of a tractogram
                # from a StatefullTractogram
                msg = 'Currently native coordinates are not supported'
                msg += ' for streamlines'
                raise ValueError(msg)

            if self.cluster:

                print(' Clustering threshold {} \n'.format(threshold))
                clusters = qbx_and_merge(streamlines,
                                         [40, 30, 25, 20, threshold])
                self.tractogram_clusters[t] = clusters
                centroids = clusters.centroids
                print(' Number of centroids is {}'.format(len(centroids)))
                sizes = np.array([len(c) for c in clusters])
                linewidths = np.interp(sizes,
                                       [sizes.min(), sizes.max()], [0.1, 2.])
                centroid_lengths = np.array([length(c) for c in centroids])

                print(' Minimum number of streamlines in cluster {}'
                      .format(sizes.min()))

                print(' Maximum number of streamlines in cluster {}'
                      .format(sizes.max()))

                print(' Construct cluster actors')
                for (i, c) in enumerate(centroids):

                    centroid_actor = actor.streamtube([c], colors,
                                                      linewidth=linewidths[i],
                                                      lod=False)
                    scene.add(centroid_actor)
                    self.mem.centroid_actors.append(centroid_actor)

                    cluster_actor = actor.line(clusters[i],
                                               lod=False)
                    cluster_actor.GetProperty().SetRenderLinesAsTubes(1)
                    cluster_actor.GetProperty().SetLineWidth(6)
                    cluster_actor.GetProperty().SetOpacity(1)
                    cluster_actor.VisibilityOff()

                    scene.add(cluster_actor)
                    self.mem.cluster_actors.append(cluster_actor)

                    # Every centroid actor (cea) is paired to a cluster actor
                    # (cla).

                    self.cea[centroid_actor] = {
                        'cluster_actor': cluster_actor,
                        'cluster': i, 'tractogram': t,
                        'size': sizes[i], 'length': centroid_lengths[i],
                        'selected': 0, 'expanded': 0}

                    self.cla[cluster_actor] = {
                        'centroid_actor': centroid_actor,
                        'cluster': i, 'tractogram': t,
                        'size': sizes[i], 'length': centroid_lengths[i],
                        'selected': 0, 'highlighted': 0}
                    apply_shader(self, cluster_actor)
                    apply_shader(self, centroid_actor)

            else:

                streamline_actor = actor.line(streamlines, colors=colors)
                streamline_actor.GetProperty().SetEdgeVisibility(1)
                streamline_actor.GetProperty().SetRenderLinesAsTubes(1)
                streamline_actor.GetProperty().SetLineWidth(6)
                streamline_actor.GetProperty().SetOpacity(1)
                scene.add(streamline_actor)
                self.mem.streamline_actors.append(streamline_actor)

        if not enable_callbacks:
            return

        def left_click_centroid_callback(obj, event):

            self.cea[obj]['selected'] = not self.cea[obj]['selected']
            self.cla[self.cea[obj]['cluster_actor']]['selected'] = \
                self.cea[obj]['selected']
            self.show_m.render()

        def left_click_cluster_callback(obj, event):

            if self.cla[obj]['selected']:
                self.cla[obj]['centroid_actor'].VisibilityOn()
                ca = self.cla[obj]['centroid_actor']
                self.cea[ca]['selected'] = 0
                obj.VisibilityOff()
                self.cea[ca]['expanded'] = 0

            self.show_m.render()

        for cl in self.cla:
            cl.AddObserver('LeftButtonPressEvent', left_click_cluster_callback,
                           1.0)
            self.cla[cl]['centroid_actor'].AddObserver(
                'LeftButtonPressEvent', left_click_centroid_callback, 1.0)
Exemplo n.º 27
0
clusters = qb.cluster(streamlines)

# Extract feature of every streamline.
centers = np.asarray(list(map(feature.extract, streamlines)))

# Color each center of mass according to the cluster they belong to.
colormap = colormap.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
scene = window.Scene()
scene.clear()
scene.SetBackground(0, 0, 0)
scene.add(actor.streamtube(streamlines, window.colors.white, opacity=0.05))
scene.add(actor.point(centers[:, 0, :], colormap_full, point_radius=0.2))
window.record(scene,
              n_frames=1,
              out_path='center_of_mass_feature.png',
              size=(600, 600))
if interactive:
    window.show(scene)
"""
.. 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:
Exemplo n.º 28
0
clusters = qb.cluster(streamlines)

# Extract feature of every streamline.
centers = np.asarray(list(map(feature.extract, streamlines)))

# Color each center of mass according to the cluster they belong to.
colormap = actor.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 = window.Renderer()
window.clear(ren)
ren.SetBackground(0, 0, 0)
ren.add(actor.streamtube(streamlines, window.colors.white, opacity=0.05))
ren.add(actor.point(centers[:, 0, :], colormap_full, point_radius=0.2))
window.record(ren, n_frames=1, out_path='center_of_mass_feature.png', size=(600, 600))
if interactive:
    window.show(ren)

"""
.. 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
Exemplo n.º 29
0
    #mean_vol_per_tract.append(np.nanmedian(s))

hue = [0.25, -0.05]
saturation = [0, 1]
scale = [3, 12]

if downsamp != 1:
    mean_vol_per_tract = mean_vol_per_tract[::downsamp]
    str1 = str1[::downsamp]

mean_pasi_weighted_img = f'{folder_name}{os.sep}streamlines{os.sep}CC_3-12_Exp_DTI_PreReg_1_ds2_tube0p3.png'

lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                       saturation_range=saturation,
                                       scale_range=scale)

#str2 = transform_streamlines(str1, np.linalg.inv(affine2))
streamlines_actor = actor.streamtube(str1,
                                     mean_vol_per_tract,
                                     linewidth=0.3,
                                     lookup_colormap=lut_cmap)
bar = actor.scalar_bar(lut_cmap)
r = window.Scene()
r.add(streamlines_actor)
r.add(bar)
#r.SetBackground(*window.colors.white)

window.show(r)
r.set_camera(r.camera_info())
window.record(r, out_path=mean_pasi_weighted_img, size=(800, 800))
Exemplo n.º 30
0
def viewstreamlines_anat(streamlines_full,
                         anat_path,
                         affine,
                         ratio=1,
                         threshold=10.,
                         verbose=False):

    scene = window.Scene()
    scene.SetBackground(1, 1, 1)

    #colors = ['white', 'cadmium_red_deep', 'misty_rose', 'slate_grey_dark', 'ivory_black', 'chartreuse']
    colors = [
        window.colors.white, window.colors.cadmium_red_deep,
        window.colors.misty_rose, window.colors.slate_grey_dark,
        window.colors.ivory_black, window.colors.chartreuse
    ]
    streamline_cut = []
    i = 0
    if ratio != 1:
        for streamline in streamlines_full:
            if i % ratio == 0:
                streamline_cut.append(streamline)
            i += 1
    else:
        streamline_cut = streamlines_full
    qb = QuickBundles(threshold=threshold)
    clusters = qb.cluster(streamline_cut)

    if verbose:
        print("Nb. clusters:", len(clusters))
        print("Cluster sizes:", map(len, clusters))
        print("Small clusters:", clusters < 10)
        print("Streamlines indices of the first cluster:\n",
              clusters[0].indices)
        print("Centroid of the last clustker:\n", clusters[-1].centroid)

    j = 0
    scene = window.Scene()
    scene.add(actor.streamtube(streamline_cut, colors[j]))
    slicer_opacity = 0.6
    j += 1

    if isinstance(anat_path, str) and os.path.exists(anat_path):
        anat_nifti = load_nifti(anat_path)
        try:
            data = anat_nifti.data
        except AttributeError:
            data = anat_nifti[0]
        if affine is None:
            try:
                affine = anat_nifti.affine
            except AttributeError:
                affine = anat_nifti[1]
    else:
        data = anat_path

    shape = np.shape(data)
    if np.size(shape) == 4:
        data = data[:, :, :, 0]
    image_actor_z = actor.slicer(data, affine)
    image_actor_z.opacity(slicer_opacity)

    image_actor_x = image_actor_z.copy()
    x_midpoint = int(np.round(shape[0] / 2))
    image_actor_x.display_extent(x_midpoint, x_midpoint, 0, shape[1] - 1, 0,
                                 shape[2] - 1)

    image_actor_y = image_actor_z.copy()
    y_midpoint = int(np.round(shape[1] / 2))
    image_actor_y.display_extent(0, shape[0] - 1, y_midpoint, y_midpoint, 0,
                                 shape[2] - 1)

    scene.add(image_actor_z)
    scene.add(image_actor_x)
    scene.add(image_actor_y)
    global size
    size = scene.GetSize()
    show_m = window.ShowManager(scene, size=(1200, 900))
    show_m.initialize()

    interactive = True
    interactive = False
    if interactive:

        show_m.add_window_callback(win_callback)
        show_m.render()
        show_m.start()
    else:
        window.record(scene,
                      out_path='bundles_and_3_slices.png',
                      size=(1200, 900),
                      reset_camera=False)
Exemplo n.º 31
0
if num_of_bundles <= 6:
    colors = color_list_dis
else:
    colors = color_list

fa, affine_fa = load_nifti(
    '/Users/alex/code/Wenlin/data/wenlin_results/bmfaN54900.nii.gz')
fa_actor = actor.slicer(fa, affine_fa)

bundle_list_center = [group_clusters.centroids[idx] for idx in top_idx]
bundle_list = [group_clusters.clusters[idx] for idx in top_idx]
ren = window.Renderer()
ren.SetBackground(1., 1, 1)

bundle_actor = actor.streamtube(bundle_list_center, colors, linewidth=0.1)

for (i, bundle) in enumerate(bundle_list):
    color = colors[i]
    lines_actor = actor.line(bundle, color, opacity=0.9)
    ren.add(lines_actor)

ren.add(bundle_actor)
#uncomment this to show fa
#ren.add(fa_actor)
window.show(ren)

# %%
num_of_bundles = 20
top_idx_group1 = sorted(range(len(group1_clusters.clusters_sizes())),
                        key=lambda i: group1_clusters.clusters_sizes()[i],
Exemplo n.º 32
0
def test_button_and_slider_widgets():

    interactive = False
    renderer = window.Renderer()

    # create some minimalistic streamlines
    lines = [np.array([[-1, 0, 0.], [1, 0, 0.]]),
             np.array([[-1, 1, 0.], [1, 1, 0.]])]
    colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]])
    stream_actor = actor.streamtube(lines, colors)

    renderer.add(stream_actor)

    # the show manager allows to break the rendering process
    # in steps so that the widgets can be added properly
    show_manager = window.ShowManager(renderer, size=(800, 800))

    if interactive:
        show_manager.initialize()
        show_manager.render()

    def button_callback(obj, event):
        print('Camera pressed')

    def button_plus_callback(obj, event):
        print('+ pressed')

    def button_minus_callback(obj, event):
        print('- pressed')

    fetch_viz_icons()
    button_png = read_viz_icons(fname='camera.png')

    button = widget.button(show_manager.iren,
                           show_manager.ren,
                           button_callback,
                           button_png, (.98, 1.), (80, 50))

    button_png_plus = read_viz_icons(fname='plus.png')
    button_plus = widget.button(show_manager.iren,
                                show_manager.ren,
                                button_plus_callback,
                                button_png_plus, (.98, .9), (120, 50))

    button_png_minus = read_viz_icons(fname='minus.png')
    button_minus = widget.button(show_manager.iren,
                                 show_manager.ren,
                                 button_minus_callback,
                                 button_png_minus, (.98, .9), (50, 50))

    def print_status(obj, event):
        rep = obj.GetRepresentation()
        stream_actor.SetPosition((rep.GetValue(), 0, 0))

    slider = widget.slider(show_manager.iren, show_manager.ren,
                           callback=print_status,
                           min_value=-1,
                           max_value=1,
                           value=0.,
                           label="X",
                           right_normalized_pos=(.98, 0.6),
                           size=(120, 0), label_format="%0.2lf")

    # This callback is used to update the buttons/sliders' position
    # so they can stay on the right side of the window when the window
    # is being resized.

    global size
    size = renderer.GetSize()

    def win_callback(obj, event):
        global size
        if size != obj.GetSize():

            button.place(renderer)
            button_plus.place(renderer)
            button_minus.place(renderer)
            slider.place(renderer)
            size = obj.GetSize()

    if interactive:
        # show_manager.add_window_callback(win_callback)
        # you can also register any callback in a vtk way like this
        # show_manager.window.AddObserver(vtk.vtkCommand.ModifiedEvent,
        #                                 win_callback)

        show_manager.render()
        show_manager.start()

    if not interactive:
        button.Off()
        slider.Off()
        # Uncomment below to test the slider and button with analyze
        # button.place(renderer)
        # slider.place(renderer)

        arr = window.snapshot(renderer, size=(800, 800))
        report = window.analyze_snapshot(arr)
        npt.assert_equal(report.objects, 2)
        # imshow(report.labels, origin='lower')

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors, 1)
Exemplo n.º 33
0
"""

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.
Exemplo n.º 34
0
"""


"""

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
ren = window.Renderer()
ren.add(candidate_streamlines_actor)
ren.add(cc_ROI_actor)
ren.add(vol_actor)
ren.add(vol_actor2)
Exemplo n.º 35
0
bundle_downsampled2 = [approx_polygon_track(s, 0.25) for s in bundle]
n_pts_ds2 = [len(streamline) for streamline in bundle_downsampled2]

"""
Both, ``downsample`` and ``approx_polygon_track`` can be thought as methods for
lossy compression of streamlines.
"""

from dipy.viz import window, actor

# Enables/disables interactive visualization
interactive = False

ren = window.Renderer()
ren.SetBackground(*window.colors.white)
bundle_actor = actor.streamtube(bundle, window.colors.red, linewidth=0.3)

ren.add(bundle_actor)

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

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

ren.add(bundle_actor2)
ren.add(bundle_actor3)

ren.set_camera(position=(0, 0, 0), focal_point=(30, 0, 0))
window.record(out_path='simulated_cosine_bundle.png', size=(900, 900))
if interactive:
Exemplo n.º 36
0
Arquivo: app.py Projeto: grlee77/dipy
    def build_scene(self):

        scene = window.Renderer()
        for (t, streamlines) in enumerate(self.tractograms):
            if self.random_colors:
                colors = self.prng.random_sample(3)
            else:
                colors = None

            if self.cluster:

                print(' Clustering threshold {} \n'.format(self.cluster_thr))
                clusters = qbx_and_merge(streamlines,
                                         [40, 30, 25, 20, self.cluster_thr])
                self.tractogram_clusters[t] = clusters
                centroids = clusters.centroids
                print(' Number of centroids is {}'.format(len(centroids)))
                sizes = np.array([len(c) for c in clusters])
                linewidths = np.interp(sizes,
                                       [sizes.min(), sizes.max()], [0.1, 2.])
                centroid_lengths = np.array([length(c) for c in centroids])

                print(' Minimum number of streamlines in cluster {}'
                      .format(sizes.min()))

                print(' Maximum number of streamlines in cluster {}'
                      .format(sizes.max()))

                print(' Construct cluster actors')
                for (i, c) in enumerate(centroids):

                    centroid_actor = actor.streamtube([c], colors,
                                                      linewidth=linewidths[i],
                                                      lod=False)
                    scene.add(centroid_actor)

                    cluster_actor = actor.line(clusters[i],
                                               lod=False)
                    cluster_actor.GetProperty().SetRenderLinesAsTubes(1)
                    cluster_actor.GetProperty().SetLineWidth(6)
                    cluster_actor.GetProperty().SetOpacity(1)
                    cluster_actor.VisibilityOff()

                    scene.add(cluster_actor)

                    # Every centroid actor (cea) is paired to a cluster actor
                    # (cla).

                    self.cea[centroid_actor] = {
                        'cluster_actor': cluster_actor,
                        'cluster': i, 'tractogram': t,
                        'size': sizes[i], 'length': centroid_lengths[i],
                        'selected': 0, 'expanded': 0}

                    self.cla[cluster_actor] = {
                        'centroid_actor': centroid_actor,
                        'cluster': i, 'tractogram': t,
                        'size': sizes[i], 'length': centroid_lengths[i],
                        'selected': 0}
                    apply_shader(self, cluster_actor)
                    apply_shader(self, centroid_actor)

            else:

                streamline_actor = actor.line(streamlines, colors=colors)
                streamline_actor.GetProperty().SetEdgeVisibility(1)
                streamline_actor.GetProperty().SetRenderLinesAsTubes(1)
                streamline_actor.GetProperty().SetLineWidth(6)
                streamline_actor.GetProperty().SetOpacity(1)
                scene.add(streamline_actor)
        return scene
Exemplo n.º 37
0
def test_custom_interactor_style_events(recording=False):
    print("Using VTK {}".format(vtk.vtkVersion.GetVTKVersion()))
    filename = "test_custom_interactor_style_events.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)
    renderer = window.Renderer()

    # the show manager allows to break the rendering process
    # in steps so that the widgets can be added properly
    interactor_style = interactor.CustomInteractorStyle()
    show_manager = window.ShowManager(renderer, size=(800, 800), reset_camera=False, interactor_style=interactor_style)

    # Create a cursor, a circle that will follow the mouse.
    polygon_source = vtk.vtkRegularPolygonSource()
    polygon_source.GeneratePolygonOff()  # Only the outline of the circle.
    polygon_source.SetNumberOfSides(50)
    polygon_source.SetRadius(10)
    polygon_source.SetRadius
    polygon_source.SetCenter(0, 0, 0)

    mapper = vtk.vtkPolyDataMapper2D()
    vtk_utils.set_input(mapper, polygon_source.GetOutputPort())

    cursor = vtk.vtkActor2D()
    cursor.SetMapper(mapper)
    cursor.GetProperty().SetColor(1, 0.5, 0)
    renderer.add(cursor)

    def follow_mouse(iren, obj):
        obj.SetPosition(*iren.event.position)
        iren.force_render()

    interactor_style.add_active_prop(cursor)
    interactor_style.add_callback(cursor, "MouseMoveEvent", follow_mouse)

    # create some minimalistic streamlines
    lines = [np.array([[-1, 0, 0.0], [1, 0, 0.0]]), np.array([[-1, 1, 0.0], [1, 1, 0.0]])]
    colors = np.array([[1.0, 0.0, 0.0], [0.3, 0.7, 0.0]])
    tube1 = actor.streamtube([lines[0]], colors[0])
    tube2 = actor.streamtube([lines[1]], colors[1])
    renderer.add(tube1)
    renderer.add(tube2)

    # Define some counter callback.
    states = defaultdict(lambda: 0)

    def counter(iren, obj):
        states[iren.event.name] += 1

    # Assign the counter callback to every possible event.
    for event in [
        "CharEvent",
        "MouseMoveEvent",
        "KeyPressEvent",
        "KeyReleaseEvent",
        "LeftButtonPressEvent",
        "LeftButtonReleaseEvent",
        "RightButtonPressEvent",
        "RightButtonReleaseEvent",
        "MiddleButtonPressEvent",
        "MiddleButtonReleaseEvent",
    ]:
        interactor_style.add_callback(tube1, event, counter)

    # Add callback to scale up/down tube1.
    def scale_up_obj(iren, obj):
        counter(iren, obj)
        scale = np.asarray(obj.GetScale()) + 0.1
        obj.SetScale(*scale)
        iren.force_render()
        iren.event.abort()  # Stop propagating the event.

    def scale_down_obj(iren, obj):
        counter(iren, obj)
        scale = np.array(obj.GetScale()) - 0.1
        obj.SetScale(*scale)
        iren.force_render()
        iren.event.abort()  # Stop propagating the event.

    interactor_style.add_callback(tube2, "MouseWheelForwardEvent", scale_up_obj)
    interactor_style.add_callback(tube2, "MouseWheelBackwardEvent", scale_down_obj)

    # Add callback to hide/show tube1.
    def toggle_visibility(iren, obj):
        key = iren.event.key
        if key.lower() == "v":
            obj.SetVisibility(not obj.GetVisibility())
            iren.force_render()

    interactor_style.add_active_prop(tube1)
    interactor_style.add_active_prop(tube2)
    interactor_style.remove_active_prop(tube2)
    interactor_style.add_callback(tube1, "CharEvent", toggle_visibility)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(states.items()))
    else:
        show_manager.play_events_from_file(recording_filename)
        msg = "Wrong count for '{}'."
        expected = [
            ("CharEvent", 6),
            ("KeyPressEvent", 6),
            ("KeyReleaseEvent", 6),
            ("MouseMoveEvent", 1652),
            ("LeftButtonPressEvent", 1),
            ("RightButtonPressEvent", 1),
            ("MiddleButtonPressEvent", 2),
            ("LeftButtonReleaseEvent", 1),
            ("MouseWheelForwardEvent", 3),
            ("MouseWheelBackwardEvent", 1),
            ("MiddleButtonReleaseEvent", 2),
            ("RightButtonReleaseEvent", 1),
        ]

        # Useful loop for debugging.
        for event, count in expected:
            if states[event] != count:
                print("{}: {} vs. {} (expected)".format(event, states[event], count))

        for event, count in expected:
            npt.assert_equal(states[event], count, err_msg=msg.format(event))
Exemplo n.º 38
0
def test_custom_interactor_style_events(recording=False):
    print("Using VTK {}".format(vtk.vtkVersion.GetVTKVersion()))
    filename = "test_custom_interactor_style_events.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)
    renderer = window.Renderer()

    # the show manager allows to break the rendering process
    # in steps so that the widgets can be added properly
    interactor_style = interactor.CustomInteractorStyle()
    show_manager = window.ShowManager(renderer,
                                      size=(800, 800),
                                      reset_camera=False,
                                      interactor_style=interactor_style)

    # Create a cursor, a circle that will follow the mouse.
    polygon_source = vtk.vtkRegularPolygonSource()
    polygon_source.GeneratePolygonOff()  # Only the outline of the circle.
    polygon_source.SetNumberOfSides(50)
    polygon_source.SetRadius(10)
    # polygon_source.SetRadius
    polygon_source.SetCenter(0, 0, 0)

    mapper = vtk.vtkPolyDataMapper2D()
    vtk_utils.set_input(mapper, polygon_source.GetOutputPort())

    cursor = vtk.vtkActor2D()
    cursor.SetMapper(mapper)
    cursor.GetProperty().SetColor(1, 0.5, 0)
    renderer.add(cursor)

    def follow_mouse(iren, obj):
        obj.SetPosition(*iren.event.position)
        iren.force_render()

    interactor_style.add_active_prop(cursor)
    interactor_style.add_callback(cursor, "MouseMoveEvent", follow_mouse)

    # create some minimalistic streamlines
    lines = [
        np.array([[-1, 0, 0.], [1, 0, 0.]]),
        np.array([[-1, 1, 0.], [1, 1, 0.]])
    ]
    colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]])
    tube1 = actor.streamtube([lines[0]], colors[0])
    tube2 = actor.streamtube([lines[1]], colors[1])
    renderer.add(tube1)
    renderer.add(tube2)

    # Define some counter callback.
    states = defaultdict(lambda: 0)

    def counter(iren, obj):
        states[iren.event.name] += 1

    # Assign the counter callback to every possible event.
    for event in [
            "CharEvent", "MouseMoveEvent", "KeyPressEvent", "KeyReleaseEvent",
            "LeftButtonPressEvent", "LeftButtonReleaseEvent",
            "RightButtonPressEvent", "RightButtonReleaseEvent",
            "MiddleButtonPressEvent", "MiddleButtonReleaseEvent"
    ]:
        interactor_style.add_callback(tube1, event, counter)

    # Add callback to scale up/down tube1.
    def scale_up_obj(iren, obj):
        counter(iren, obj)
        scale = np.asarray(obj.GetScale()) + 0.1
        obj.SetScale(*scale)
        iren.force_render()
        iren.event.abort()  # Stop propagating the event.

    def scale_down_obj(iren, obj):
        counter(iren, obj)
        scale = np.array(obj.GetScale()) - 0.1
        obj.SetScale(*scale)
        iren.force_render()
        iren.event.abort()  # Stop propagating the event.

    interactor_style.add_callback(tube2, "MouseWheelForwardEvent",
                                  scale_up_obj)
    interactor_style.add_callback(tube2, "MouseWheelBackwardEvent",
                                  scale_down_obj)

    # Add callback to hide/show tube1.
    def toggle_visibility(iren, obj):
        key = iren.event.key
        if key.lower() == "v":
            obj.SetVisibility(not obj.GetVisibility())
            iren.force_render()

    interactor_style.add_active_prop(tube1)
    interactor_style.add_active_prop(tube2)
    interactor_style.remove_active_prop(tube2)
    interactor_style.add_callback(tube1, "CharEvent", toggle_visibility)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(states.items()))
    else:
        show_manager.play_events_from_file(recording_filename)
        msg = ("Wrong count for '{}'.")
        expected = [('CharEvent', 6), ('KeyPressEvent', 6),
                    ('KeyReleaseEvent', 6), ('MouseMoveEvent', 1652),
                    ('LeftButtonPressEvent', 1), ('RightButtonPressEvent', 1),
                    ('MiddleButtonPressEvent', 2),
                    ('LeftButtonReleaseEvent', 1),
                    ('MouseWheelForwardEvent', 3),
                    ('MouseWheelBackwardEvent', 1),
                    ('MiddleButtonReleaseEvent', 2),
                    ('RightButtonReleaseEvent', 1)]

        # Useful loop for debugging.
        for event, count in expected:
            if states[event] != count:
                print("{}: {} vs. {} (expected)".format(
                    event, states[event], count))

        for event, count in expected:
            npt.assert_equal(states[event], count, err_msg=msg.format(event))
Exemplo n.º 39
0
def test_bundle_maps():
    renderer = window.renderer()
    bundle = fornix_streamlines()
    bundle, shift = center_streamlines(bundle)

    mat = np.array([[1, 0, 0, 100],
                    [0, 1, 0, 100],
                    [0, 0, 1, 100],
                    [0, 0, 0, 1.]])

    bundle = transform_streamlines(bundle, mat)

    # metric = np.random.rand(*(200, 200, 200))
    metric = 100 * np.ones((200, 200, 200))

    # add lower values
    metric[100, :, :] = 100 * 0.5

    # create a nice orange-red colormap
    lut = actor.colormap_lookup_table(scale_range=(0., 100.),
                                      hue_range=(0., 0.1),
                                      saturation_range=(1, 1),
                                      value_range=(1., 1))

    line = actor.line(bundle, metric, linewidth=0.1, lookup_colormap=lut)
    window.add(renderer, line)
    window.add(renderer, actor.scalar_bar(lut, ' '))

    report = window.analyze_renderer(renderer)

    npt.assert_almost_equal(report.actors, 1)
    # window.show(renderer)

    renderer.clear()

    nb_points = np.sum([len(b) for b in bundle])
    values = 100 * np.random.rand(nb_points)
    # values[:nb_points/2] = 0

    line = actor.streamtube(bundle, values, linewidth=0.1, lookup_colormap=lut)
    renderer.add(line)
    # window.show(renderer)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors_classnames[0], 'vtkLODActor')

    renderer.clear()

    colors = np.random.rand(nb_points, 3)
    # values[:nb_points/2] = 0

    line = actor.line(bundle, colors, linewidth=2)
    renderer.add(line)
    # window.show(renderer)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors_classnames[0], 'vtkLODActor')
    # window.show(renderer)

    arr = window.snapshot(renderer)
    report2 = window.analyze_snapshot(arr)
    npt.assert_equal(report2.objects, 1)

    # try other input options for colors
    renderer.clear()
    actor.line(bundle, (1., 0.5, 0))
    actor.line(bundle, np.arange(len(bundle)))
    actor.line(bundle)
    colors = [np.random.rand(*b.shape) for b in bundle]
    actor.line(bundle, colors=colors)
Exemplo n.º 40
0
def test_button_and_slider_widgets():
    recording = False
    filename = "test_button_and_slider_widgets.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)
    renderer = window.Renderer()

    # create some minimalistic streamlines
    lines = [np.array([[-1, 0, 0.], [1, 0, 0.]]),
             np.array([[-1, 1, 0.], [1, 1, 0.]])]
    colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]])
    stream_actor = actor.streamtube(lines, colors)

    states = {'camera_button_count': 0,
              'plus_button_count': 0,
              'minus_button_count': 0,
              'slider_moved_count': 0,
              }

    renderer.add(stream_actor)

    # the show manager allows to break the rendering process
    # in steps so that the widgets can be added properly
    show_manager = window.ShowManager(renderer, size=(800, 800))

    if recording:
        show_manager.initialize()
        show_manager.render()

    def button_callback(obj, event):
        print('Camera pressed')
        states['camera_button_count'] += 1

    def button_plus_callback(obj, event):
        print('+ pressed')
        states['plus_button_count'] += 1

    def button_minus_callback(obj, event):
        print('- pressed')
        states['minus_button_count'] += 1

    fetch_viz_icons()
    button_png = read_viz_icons(fname='camera.png')

    button = widget.button(show_manager.iren,
                           show_manager.ren,
                           button_callback,
                           button_png, (.98, 1.), (80, 50))

    button_png_plus = read_viz_icons(fname='plus.png')
    button_plus = widget.button(show_manager.iren,
                                show_manager.ren,
                                button_plus_callback,
                                button_png_plus, (.98, .9), (120, 50))

    button_png_minus = read_viz_icons(fname='minus.png')
    button_minus = widget.button(show_manager.iren,
                                 show_manager.ren,
                                 button_minus_callback,
                                 button_png_minus, (.98, .9), (50, 50))

    def print_status(obj, event):
        rep = obj.GetRepresentation()
        stream_actor.SetPosition((rep.GetValue(), 0, 0))
        states['slider_moved_count'] += 1

    slider = widget.slider(show_manager.iren, show_manager.ren,
                           callback=print_status,
                           min_value=-1,
                           max_value=1,
                           value=0.,
                           label="X",
                           right_normalized_pos=(.98, 0.6),
                           size=(120, 0), label_format="%0.2lf")

    # This callback is used to update the buttons/sliders' position
    # so they can stay on the right side of the window when the window
    # is being resized.

    global size
    size = renderer.GetSize()

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(states)
    else:
        show_manager.play_events_from_file(recording_filename)
        npt.assert_equal(states["camera_button_count"], 7)
        npt.assert_equal(states["plus_button_count"], 3)
        npt.assert_equal(states["minus_button_count"], 4)
        npt.assert_equal(states["slider_moved_count"], 116)

    if not recording:
        button.Off()
        slider.Off()
        # Uncomment below to test the slider and button with analyze
        # button.place(renderer)
        # slider.place(renderer)

        arr = window.snapshot(renderer, size=(800, 800))
        report = window.analyze_snapshot(arr)
        # import pylab as plt
        # plt.imshow(report.labels, origin='lower')
        # plt.show()
        npt.assert_equal(report.objects, 4)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors, 1)
Exemplo n.º 41
0
def test_button_and_slider_widgets():
    recording = False
    filename = "test_button_and_slider_widgets.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)
    renderer = window.Renderer()

    # create some minimalistic streamlines
    lines = [
        np.array([[-1, 0, 0.], [1, 0, 0.]]),
        np.array([[-1, 1, 0.], [1, 1, 0.]])
    ]
    colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]])
    stream_actor = actor.streamtube(lines, colors)

    states = {
        'camera_button_count': 0,
        'plus_button_count': 0,
        'minus_button_count': 0,
        'slider_moved_count': 0,
    }

    renderer.add(stream_actor)

    # the show manager allows to break the rendering process
    # in steps so that the widgets can be added properly
    show_manager = window.ShowManager(renderer, size=(800, 800))

    if recording:
        show_manager.initialize()
        show_manager.render()

    def button_callback(obj, event):
        print('Camera pressed')
        states['camera_button_count'] += 1

    def button_plus_callback(obj, event):
        print('+ pressed')
        states['plus_button_count'] += 1

    def button_minus_callback(obj, event):
        print('- pressed')
        states['minus_button_count'] += 1

    fetch_viz_icons()
    button_png = read_viz_icons(fname='camera.png')

    button = widget.button(show_manager.iren, show_manager.ren,
                           button_callback, button_png, (.98, 1.), (80, 50))

    button_png_plus = read_viz_icons(fname='plus.png')
    button_plus = widget.button(show_manager.iren, show_manager.ren,
                                button_plus_callback, button_png_plus,
                                (.98, .9), (120, 50))

    button_png_minus = read_viz_icons(fname='minus.png')
    button_minus = widget.button(show_manager.iren, show_manager.ren,
                                 button_minus_callback, button_png_minus,
                                 (.98, .9), (50, 50))

    def print_status(obj, event):
        rep = obj.GetRepresentation()
        stream_actor.SetPosition((rep.GetValue(), 0, 0))
        states['slider_moved_count'] += 1

    slider = widget.slider(show_manager.iren,
                           show_manager.ren,
                           callback=print_status,
                           min_value=-1,
                           max_value=1,
                           value=0.,
                           label="X",
                           right_normalized_pos=(.98, 0.6),
                           size=(120, 0),
                           label_format="%0.2lf")

    # This callback is used to update the buttons/sliders' position
    # so they can stay on the right side of the window when the window
    # is being resized.

    global size
    size = renderer.GetSize()

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(states)
    else:
        show_manager.play_events_from_file(recording_filename)
        npt.assert_equal(states["camera_button_count"], 7)
        npt.assert_equal(states["plus_button_count"], 3)
        npt.assert_equal(states["minus_button_count"], 4)
        npt.assert_equal(states["slider_moved_count"], 116)

    if not recording:
        button.Off()
        slider.Off()
        # Uncomment below to test the slider and button with analyze
        # button.place(renderer)
        # slider.place(renderer)

        arr = window.snapshot(renderer, size=(800, 800))
        report = window.analyze_snapshot(arr)
        # import pylab as plt
        # plt.imshow(report.labels, origin='lower')
        # plt.show()
        npt.assert_equal(report.objects, 4)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors, 1)
Exemplo n.º 42
0
bundle_downsampled2 = [approx_polygon_track(s, 0.25) for s in bundle]
n_pts_ds2 = [len(streamline) for streamline in bundle_downsampled2]
"""
Both, ``set_number_of_points`` and ``approx_polygon_track`` can be thought as 
methods for lossy compression of streamlines.
"""

from dipy.viz import window, actor

# Enables/disables interactive visualization
interactive = False

ren = window.Renderer()
ren.SetBackground(*window.colors.white)
bundle_actor = actor.streamtube(bundle, window.colors.red, linewidth=0.3)

ren.add(bundle_actor)

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

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

ren.add(bundle_actor2)
ren.add(bundle_actor3)
Exemplo n.º 43
0
# 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(
    list(move_streamlines(plot_streamlines, inv(t1_aff))),
         cmap.line_colors(streamlines), linewidth=0.1)

vol_actor = actor.slicer(t1_data)

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

ren = window.Renderer()
ren.add(streamlines_actor)
ren.add(vol_actor)
ren.add(vol_actor2)

window.record(ren, out_path='sfm_streamlines.png', size=(800, 800))
if interactive:
'''
for line in streamlines:
  print(line.shape)
'''
# Do steamline clustering using QuickBundles (QB) using Eular's Method
# dist_thr (distance threshold) which affects number of clusters and their size
# pts (number of points in each streamline) which will be used for downsampling before clustering
# Default values : dist_thr = 4 & pts = 12
qb = QuickBundles(streamlines, dist_thr=20, pts=20)
clusters = qb.clusters()
print('Number of clusters %i' % qb.total_clusters)
print('Cluster size', qb.clusters_sizes())

# Display streamlines
ren = window.Renderer()
ren.add(actor.streamtube(streamlines, window.colors.white))
window.show(ren)
window.record(ren, out_path=filename + '_stream_lines_eu.png', size=(600, 600))

# Display centroids
window.clear(ren)
colormap = actor.create_colormap(np.arange(qb.total_clusters))
ren.add(actor.streamtube(streamlines, window.colors.white, opacity=0.1))
ren.add(actor.streamtube(qb.centroids, colormap, linewidth=0.5))
window.show(ren)
window.record(ren, out_path=filename + '_centroids_eu.png', size=(600, 600))

# Display tracks
window.clear(ren)
colormap_full = np.ones((len(streamlines), 3))
for cluster, color in zip(clusters.items(), colormap):
Exemplo n.º 45
0
def test_button_and_slider_widgets():

    interactive = False
    renderer = window.Renderer()

    # create some minimalistic streamlines
    lines = [
        np.array([[-1, 0, 0.], [1, 0, 0.]]),
        np.array([[-1, 1, 0.], [1, 1, 0.]])
    ]
    colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]])
    stream_actor = actor.streamtube(lines, colors)

    renderer.add(stream_actor)

    # the show manager allows to break the rendering process
    # in steps so that the widgets can be added properly
    show_manager = window.ShowManager(renderer, size=(800, 800))

    if interactive:
        show_manager.initialize()
        show_manager.render()

    def button_callback(obj, event):
        print('Camera pressed')

    def button_plus_callback(obj, event):
        print('+ pressed')

    def button_minus_callback(obj, event):
        print('- pressed')

    fetch_viz_icons()
    button_png = read_viz_icons(fname='camera.png')

    button = widget.button(show_manager.iren, show_manager.ren,
                           button_callback, button_png, (.98, 1.), (80, 50))

    button_png_plus = read_viz_icons(fname='plus.png')
    button_plus = widget.button(show_manager.iren, show_manager.ren,
                                button_plus_callback, button_png_plus,
                                (.98, .9), (120, 50))

    button_png_minus = read_viz_icons(fname='minus.png')
    button_minus = widget.button(show_manager.iren, show_manager.ren,
                                 button_minus_callback, button_png_minus,
                                 (.98, .9), (50, 50))

    def print_status(obj, event):
        rep = obj.GetRepresentation()
        stream_actor.SetPosition((rep.GetValue(), 0, 0))

    slider = widget.slider(show_manager.iren,
                           show_manager.ren,
                           callback=print_status,
                           min_value=-1,
                           max_value=1,
                           value=0.,
                           label="X",
                           right_normalized_pos=(.98, 0.6),
                           size=(120, 0),
                           label_format="%0.2lf")

    # This callback is used to update the buttons/sliders' position
    # so they can stay on the right side of the window when the window
    # is being resized.

    global size
    size = renderer.GetSize()

    def win_callback(obj, event):
        global size
        if size != obj.GetSize():

            button.place(renderer)
            button_plus.place(renderer)
            button_minus.place(renderer)
            slider.place(renderer)
            size = obj.GetSize()

    if interactive:
        # show_manager.add_window_callback(win_callback)
        # you can also register any callback in a vtk way like this
        # show_manager.window.AddObserver(vtk.vtkCommand.ModifiedEvent,
        #                                 win_callback)

        show_manager.render()
        show_manager.start()

    if not interactive:
        button.Off()
        slider.Off()
        # Uncomment below to test the slider and button with analyze
        # button.place(renderer)
        # slider.place(renderer)

        arr = window.snapshot(renderer, size=(800, 800))
        report = window.analyze_snapshot(arr)
        npt.assert_equal(report.objects, 2)
        # imshow(report.labels, origin='lower')

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors, 1)
Exemplo n.º 46
0
# 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(
    list(move_streamlines(plot_streamlines, inv(t1_aff))),
         cmap.line_colors(streamlines), linewidth=0.1)

vol_actor = actor.slicer(t1_data)

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

ren = window.Renderer()
ren.add(streamlines_actor)
ren.add(vol_actor)
ren.add(vol_actor2)

window.record(ren, out_path='sfm_streamlines.png', size=(800, 800))
if interactive:
"""
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.