Пример #1
0
def bundle_coherence(streamlines, affine, k, t1_data=None, interactive=False):

    # Compute lookup table

    # Apply FBC measures
    from dipy.tracking.fbcmeasures import FBCMeasures

    fbc = FBCMeasures(streamlines, k)

    # Calculate LFBC for original fibers
    fbc_sl_orig, clrs_orig, rfbc_orig = \
      fbc.get_points_rfbc_thresholded(0, emphasis=0.01)

    # Apply a threshold on the RFBC to remove spurious fibers
    fbc_sl_thres, clrs_thres, rfbc_thres = \
      fbc.get_points_rfbc_thresholded(0.125, emphasis=0.01)

    # Visualize the results
    from dipy.viz import window, actor

    # Create renderer
    ren = window.Renderer()

    # Original lines colored by LFBC
    lineactor = actor.line(fbc_sl_orig, clrs_orig, linewidth=0.2)
    ren.add(lineactor)

    # Horizontal (axial) slice of T1 data
    if t1_data is not None:
        vol_actor1 = actor.slicer(t1_data, affine=affine)
        vol_actor1.display(z=20)
        ren.add(vol_actor1)

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

    # Show original fibers
    ren.set_camera(position=(-264, 285, 155),
                   focal_point=(0, -14, 9),
                   view_up=(0, 0, 1))
    window.record(ren, n_frames=1, out_path='OR_before.png', size=(900, 900))
    if interactive:
        window.show(ren)

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

    return k
Пример #2
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))
Пример #3
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)
def simple_viewer(streamlines, vol, affine):

    from dipy.viz import actor, window

    renderer = window.Renderer()
    renderer.add(actor.line(streamlines))
    renderer.add(actor.slicer(vol, affine))
    window.show(renderer)
def simple_viewer(streamlines, vol, affine):

    from dipy.viz import actor, window

    renderer = window.Renderer()
    renderer.add(actor.line(streamlines))
    renderer.add(actor.slicer(vol, affine))
    window.show(renderer)
Пример #6
0
def genren_AGG(sls,
               sls2=None,
               niidata=None,
               roi1=None,
               roi2=None,
               roi3=None,
               aff=np.eye(4),
               putpath='test.png',
               showme=False,
               showaxes=False):

    renderer = window.Renderer()
    renderer.set_camera(position=(-606.93, -153.23, 28.70),
                        focal_point=(2.78, 11.06, 15.66),
                        view_up=(0, 0, 1))

    stream_actor = actor.line(sls)
    renderer.add(stream_actor)

    if sls2 is not None:
        stream_actor2 = actor.line(sls2, colors=(1, 1, 1))
        renderer.add(stream_actor2)

    if roi1 is not None:
        contour_actor1 = actor.contour_from_roi(roi1,
                                                affine=aff,
                                                color=(1., 1., 0.),
                                                opacity=0.5)
        renderer.add(contour_actor1)

    if roi2 is not None:
        contour_actor2 = actor.contour_from_roi(roi2,
                                                affine=aff,
                                                color=(1., 0., 0.),
                                                opacity=0.5)
        renderer.add(contour_actor2)

    if roi3 is not None:
        contour_actor3 = actor.contour_from_roi(roi3,
                                                affine=aff,
                                                color=(0., 0., 1.),
                                                opacity=0.5)
        renderer.add(contour_actor3)

    if niidata is not None:
        slice_actor = actor.slicer(niidata, affine=aff)
        renderer.add(slice_actor)

    if showaxes:
        axes = actor.axes()
        renderer.add(axes)

    if showme:
        window.show(renderer, size=(500, 500), reset_camera=False)
    window.record(renderer, out_path=putpath, size=(500, 500))
    # renderer.camera_info()
    del renderer
    return putpath
def show_two_images(vol1, affine1, vol2, affine2, shift=50):
    """ Show 2 images side by side"""

    renderer = window.Renderer()
    mean, std = vol1[vol1 > 0].mean(), vol1[vol1 > 0].std()
    value_range1 = (mean - 0.5 * std, mean + 1.5 * std)
    mean, std = vol2[vol2 > 0].mean(), vol2[vol2 > 0].std()
    value_range2 = (mean - 0.5 * std, mean + 1.5 * std)

    slice_actor1 = actor.slicer(vol1, affine1, value_range1)
    slice_actor2 = actor.slicer(vol2, affine2, value_range2)

    renderer.add(slice_actor1)
    renderer.add(slice_actor2)

    slice_actor2.SetPosition(slice_actor1.shape[0] + shift, 0, 0)

    window.show(renderer)
Пример #8
0
def show_two_images(vol1, affine1, vol2, affine2, shift=50):
    """ Show 2 images side by side"""

    renderer = window.Renderer()
    mean, std = vol1[vol1 > 0].mean(), vol1[vol1 > 0].std()
    value_range1 = (mean - 0.5 * std, mean + 1.5 * std)
    mean, std = vol2[vol2 > 0].mean(), vol2[vol2 > 0].std()
    value_range2 = (mean - 0.5 * std, mean + 1.5 * std)

    slice_actor1 = actor.slicer(vol1, affine1, value_range1)
    slice_actor2 = actor.slicer(vol2, affine2, value_range2)

    renderer.add(slice_actor1)
    renderer.add(slice_actor2)

    slice_actor2.SetPosition(slice_actor1.shape[0] + shift, 0, 0)

    window.show(renderer)
Пример #9
0
    def change_volume(istyle, obj, slider):
        vol_idx = int(np.round(slider.value))
        HORIMEM.slicer_vol_idx = vol_idx

        renderer.rm(HORIMEM.slicer_curr_actor_x)
        renderer.rm(HORIMEM.slicer_curr_actor_y)
        renderer.rm(HORIMEM.slicer_curr_actor_z)

        tmp = data[..., vol_idx]
        image_actor_z = actor.slicer(tmp,
                                     affine=affine,
                                     value_range=value_range,
                                     interpolation='nearest',
                                     picking_tol=0.025)

        tmp_new = image_actor_z.resliced_array()
        HORIMEM.slicer_vol = tmp_new

        z = HORIMEM.slicer_curr_z
        image_actor_z.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)

        HORIMEM.slicer_curr_actor_z = image_actor_z
        HORIMEM.slicer_curr_actor_x = image_actor_z.copy()

        if pam is not None:
            HORIMEM.slicer_peaks_actor_z = peaks_actor_z

        x = HORIMEM.slicer_curr_x
        HORIMEM.slicer_curr_actor_x.display_extent(x, x, 0, shape[1] - 1, 0,
                                                   shape[2] - 1)

        HORIMEM.slicer_curr_actor_y = image_actor_z.copy()
        y = HORIMEM.slicer_curr_y
        HORIMEM.slicer_curr_actor_y.display_extent(0, shape[0] - 1, y, y, 0,
                                                   shape[2] - 1)

        HORIMEM.slicer_curr_actor_z.AddObserver('LeftButtonPressEvent',
                                                left_click_picker_callback,
                                                1.0)
        HORIMEM.slicer_curr_actor_x.AddObserver('LeftButtonPressEvent',
                                                left_click_picker_callback,
                                                1.0)
        HORIMEM.slicer_curr_actor_y.AddObserver('LeftButtonPressEvent',
                                                left_click_picker_callback,
                                                1.0)
        renderer.add(HORIMEM.slicer_curr_actor_z)
        renderer.add(HORIMEM.slicer_curr_actor_x)
        renderer.add(HORIMEM.slicer_curr_actor_y)

        if pam is not None:
            renderer.add(HORIMEM.slicer_peaks_actor_z)

        r1, r2 = double_slider._values
        apply_colormap(r1, r2)

        istyle.force_render()
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))
Пример #11
0
    def aquire_odi(self, fitted_parameters):

        affine = np.eye(4)

        volume_res = fitted_parameters[
            'SD1WatsonDistributed_1_SD1Watson_1_odi']
        volume_im = actor.slicer(volume_res,
                                 interpolation='nearest',
                                 affine=affine,
                                 opacity=0.7)

        #z = int(np.round(volume_im.shape[2]/2))- 1
        #volume_im.display_extent(0, volume_im.shape[0] - 1,
        #                         0, volume_im.shape[1] - 1,
        #                         z, z)

        return volume_im
Пример #12
0
def create_image_actor(vol, opacity=0.6):
    data = vol.get_data()
    shape = vol.shape
    affine = vol.affine

    image_actor_z = actor.slicer(data, affine)
    slicer_opacity = opacity
    image_actor_z.opacity(slicer_opacity)
    image_actor_x = image_actor_z.copy()
    image_actor_x.opacity(slicer_opacity)
    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()
    image_actor_y.opacity(slicer_opacity)
    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)

    return image_actor_x, image_actor_y, image_actor_z
Пример #13
0
def show_mosaic(data, affine, border=70):
    """ Show a simple mosaic of the given image
    """

    renderer = window.Renderer()
    mean, std = data[data > 0].mean(), data[data > 0].std()
    value_range = (mean - 0.5 * std, mean + 1.5 * std)
    slice_actor = actor.slicer(data, affine, value_range)

    renderer.clear()
    renderer.projection('parallel')
    cnt = 0

    X, Y, Z = slice_actor.shape[:3]

    rows = 10
    cols = 15
    border = 70

    for j in range(rows):
        for i in range(cols):
            slice_mosaic = slice_actor.copy()
            slice_mosaic.display(None, None, cnt)
            slice_mosaic.SetPosition(
                (X + border) * i,
                0.5 * cols * (Y + border) - (Y + border) * j,
                0)
            renderer.add(slice_mosaic)
            cnt += 1
            if cnt > Z:
                break
        if cnt > Z:
            break

    renderer.reset_camera()
    renderer.zoom(1.6)

    window.show(renderer, size=(900, 600), reset_camera=False)
def show_mosaic(data, affine, border=70):
    """ Show a simple mosaic of the given image
    """

    renderer = window.Renderer()
    mean, std = data[data > 0].mean(), data[data > 0].std()
    value_range = (mean - 0.5 * std, mean + 1.5 * std)
    slice_actor = actor.slicer(data, affine, value_range)

    renderer.clear()
    renderer.projection('parallel')
    cnt = 0

    X, Y, Z = slice_actor.shape[:3]

    rows = 10
    cols = 15
    border = 70

    for j in range(rows):
        for i in range(cols):
            slice_mosaic = slice_actor.copy()
            slice_mosaic.display(None, None, cnt)
            slice_mosaic.SetPosition(
                (X + border) * i, 0.5 * cols * (Y + border) - (Y + border) * j,
                0)
            renderer.add(slice_mosaic)
            cnt += 1
            if cnt > Z:
                break
        if cnt > Z:
            break

    renderer.reset_camera()
    renderer.zoom(1.6)

    window.show(renderer, size=(900, 600), reset_camera=False)
Пример #15
0
def show_image(data, affine=None):
    renderer = window.Renderer()
    slicer = actor.slicer(data, affine)
    renderer.add(slicer)
    window.show(renderer)
Пример #16
0
def slicer_panel(scene,
                 iren,
                 data=None,
                 affine=None,
                 world_coords=False,
                 pam=None,
                 mask=None,
                 mem=GlobalHorizon()):
    """ Slicer panel with slicer included

    Parameters
    ----------
    scene : Scene
    iren : Interactor
    data : 3d ndarray
    affine : 4x4 ndarray
    world_coords : bool
        If True then the affine is applied.

    peaks : PeaksAndMetrics
        Default None
    mem :

    Returns
    -------
    panel : Panel

    """
    orig_shape = data.shape
    print('Original shape', orig_shape)
    ndim = data.ndim
    tmp = data
    if ndim == 4:
        if orig_shape[-1] > 3:
            orig_shape = orig_shape[:3]
            # Sometimes, first volume is null, so we try the next one.
            for i in range(orig_shape[-1]):
                tmp = data[..., i]
                value_range = np.percentile(data[..., i], q=[2, 98])
                if np.sum(np.diff(value_range)) != 0:
                    break
        if orig_shape[-1] == 3:
            value_range = (0, 1.)
            mem.slicer_rgb = True
    if ndim == 3:
        value_range = np.percentile(tmp, q=[2, 98])

    if np.sum(np.diff(value_range)) == 0:
        msg = "Your data does not have any contrast. "
        msg += "Please, check the value range of your data."
        warnings.warn(msg)

    if not world_coords:
        affine = np.eye(4)

    image_actor_z = actor.slicer(tmp,
                                 affine=affine,
                                 value_range=value_range,
                                 interpolation='nearest',
                                 picking_tol=0.025)

    tmp_new = image_actor_z.resliced_array()

    if len(data.shape) == 4:
        if data.shape[-1] == 3:
            print('Resized to RAS shape ', tmp_new.shape)
        else:
            print('Resized to RAS shape ', tmp_new.shape + (data.shape[-1], ))
    else:
        print('Resized to RAS shape ', tmp_new.shape)

    shape = tmp_new.shape

    if pam is not None:

        peaks_actor_z = actor.peak_slicer(pam.peak_dirs,
                                          None,
                                          mask=mask,
                                          affine=affine,
                                          colors=None)

    slicer_opacity = 1.
    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)

    if pam is not None:
        scene.add(peaks_actor_z)

    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    _color_slider(line_slider_z)

    def change_slice_z(slider):
        z = int(np.round(slider.value))
        mem.slicer_curr_actor_z.display_extent(0, shape[0] - 1, 0,
                                               shape[1] - 1, z, z)
        if pam is not None:
            mem.slicer_peaks_actor_z.display_extent(0, shape[0] - 1, 0,
                                                    shape[1] - 1, z, z)
        mem.slicer_curr_z = z
        scene.reset_clipping_range()

    line_slider_x = ui.LineSlider2D(min_value=0,
                                    max_value=shape[0] - 1,
                                    initial_value=shape[0] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    _color_slider(line_slider_x)

    def change_slice_x(slider):
        x = int(np.round(slider.value))
        mem.slicer_curr_actor_x.display_extent(x, x, 0, shape[1] - 1, 0,
                                               shape[2] - 1)
        scene.reset_clipping_range()
        mem.slicer_curr_x = x
        mem.window_timer_cnt += 100

    line_slider_y = ui.LineSlider2D(min_value=0,
                                    max_value=shape[1] - 1,
                                    initial_value=shape[1] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    _color_slider(line_slider_y)

    def change_slice_y(slider):
        y = int(np.round(slider.value))

        mem.slicer_curr_actor_y.display_extent(0, shape[0] - 1, y, y, 0,
                                               shape[2] - 1)
        scene.reset_clipping_range()
        mem.slicer_curr_y = y

    # TODO there is some small bug when starting the app the handles
    # are sitting a bit low
    double_slider = ui.LineDoubleSlider2D(length=140,
                                          initial_values=value_range,
                                          min_value=tmp.min(),
                                          max_value=tmp.max(),
                                          shape='square')

    _color_dslider(double_slider)

    def apply_colormap(r1, r2):
        if mem.slicer_rgb:
            return

        if mem.slicer_colormap == 'disting':
            # use distinguishable colors
            rgb = colormap.distinguishable_colormap(nb_colors=256)
            rgb = np.asarray(rgb)
        else:
            # use matplotlib colormaps
            rgb = colormap.create_colormap(np.linspace(r1, r2, 256),
                                           name=mem.slicer_colormap,
                                           auto=True)
        N = rgb.shape[0]

        lut = colormap.LookupTable()
        lut.SetNumberOfTableValues(N)
        lut.SetRange(r1, r2)
        for i in range(N):
            r, g, b = rgb[i]
            lut.SetTableValue(i, r, g, b)
        lut.SetRampToLinear()
        lut.Build()

        mem.slicer_curr_actor_z.output.SetLookupTable(lut)
        mem.slicer_curr_actor_z.output.Update()

    def on_change_ds(slider):

        values = slider._values
        r1, r2 = values
        apply_colormap(r1, r2)

    # TODO trying to see why there is a small bug in double slider
    # double_slider.left_disk_value = 0
    # double_slider.right_disk_value = 98

    # double_slider.update(0)
    # double_slider.update(1)

    double_slider.on_change = on_change_ds

    opacity_slider = ui.LineSlider2D(min_value=0.0,
                                     max_value=1.0,
                                     initial_value=slicer_opacity,
                                     length=140,
                                     text_template="{ratio:.0%}")

    _color_slider(opacity_slider)

    def change_opacity(slider):

        slicer_opacity = slider.value
        mem.slicer_curr_actor_x.opacity(slicer_opacity)
        mem.slicer_curr_actor_y.opacity(slicer_opacity)
        mem.slicer_curr_actor_z.opacity(slicer_opacity)

    volume_slider = ui.LineSlider2D(min_value=0,
                                    max_value=data.shape[-1] - 1,
                                    initial_value=0,
                                    length=140,
                                    text_template="{value:.0f}",
                                    shape='square')

    _color_slider(volume_slider)

    def change_volume(istyle, obj, slider):
        vol_idx = int(np.round(slider.value))
        mem.slicer_vol_idx = vol_idx

        scene.rm(mem.slicer_curr_actor_x)
        scene.rm(mem.slicer_curr_actor_y)
        scene.rm(mem.slicer_curr_actor_z)

        tmp = data[..., vol_idx]
        image_actor_z = actor.slicer(tmp,
                                     affine=affine,
                                     value_range=value_range,
                                     interpolation='nearest',
                                     picking_tol=0.025)

        tmp_new = image_actor_z.resliced_array()
        mem.slicer_vol = tmp_new

        z = mem.slicer_curr_z
        image_actor_z.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)

        mem.slicer_curr_actor_z = image_actor_z
        mem.slicer_curr_actor_x = image_actor_z.copy()

        if pam is not None:
            mem.slicer_peaks_actor_z = peaks_actor_z

        x = mem.slicer_curr_x
        mem.slicer_curr_actor_x.display_extent(x, x, 0, shape[1] - 1, 0,
                                               shape[2] - 1)

        mem.slicer_curr_actor_y = image_actor_z.copy()
        y = mem.slicer_curr_y
        mem.slicer_curr_actor_y.display_extent(0, shape[0] - 1, y, y, 0,
                                               shape[2] - 1)

        mem.slicer_curr_actor_z.AddObserver('LeftButtonPressEvent',
                                            left_click_picker_callback, 1.0)
        mem.slicer_curr_actor_x.AddObserver('LeftButtonPressEvent',
                                            left_click_picker_callback, 1.0)
        mem.slicer_curr_actor_y.AddObserver('LeftButtonPressEvent',
                                            left_click_picker_callback, 1.0)
        scene.add(mem.slicer_curr_actor_z)
        scene.add(mem.slicer_curr_actor_x)
        scene.add(mem.slicer_curr_actor_y)

        if pam is not None:
            scene.add(mem.slicer_peaks_actor_z)

        r1, r2 = double_slider._values
        apply_colormap(r1, r2)

        istyle.force_render()

    def left_click_picker_callback(obj, ev):
        ''' Get the value of the clicked voxel and show it in the panel.'''

        event_pos = iren.GetEventPosition()

        obj.picker.Pick(event_pos[0], event_pos[1], 0, scene)

        i, j, k = obj.picker.GetPointIJK()
        res = mem.slicer_vol[i, j, k]
        try:
            message = '%.3f' % res
        except TypeError:
            message = '%.3f %.3f %.3f' % (res[0], res[1], res[2])
        picker_label.message = '({}, {}, {})'.format(str(i), str(j), str(k)) \
            + ' ' + message

    mem.slicer_vol_idx = 0
    mem.slicer_vol = tmp_new
    mem.slicer_curr_actor_x = image_actor_x
    mem.slicer_curr_actor_y = image_actor_y
    mem.slicer_curr_actor_z = image_actor_z

    if pam is not None:
        # change_volume.peaks_actor_z = peaks_actor_z
        mem.slicer_peaks_actor_z = peaks_actor_z

    mem.slicer_curr_actor_x.AddObserver('LeftButtonPressEvent',
                                        left_click_picker_callback, 1.0)
    mem.slicer_curr_actor_y.AddObserver('LeftButtonPressEvent',
                                        left_click_picker_callback, 1.0)
    mem.slicer_curr_actor_z.AddObserver('LeftButtonPressEvent',
                                        left_click_picker_callback, 1.0)

    if pam is not None:
        mem.slicer_peaks_actor_z.AddObserver('LeftButtonPressEvent',
                                             left_click_picker_callback, 1.0)

    mem.slicer_curr_x = int(np.round(shape[0] / 2))
    mem.slicer_curr_y = int(np.round(shape[1] / 2))
    mem.slicer_curr_z = int(np.round(shape[2] / 2))

    line_slider_x.on_change = change_slice_x
    line_slider_y.on_change = change_slice_y
    line_slider_z.on_change = change_slice_z

    double_slider.on_change = on_change_ds

    opacity_slider.on_change = change_opacity

    volume_slider.handle_events(volume_slider.handle.actor)
    volume_slider.on_left_mouse_button_released = change_volume

    line_slider_label_x = build_label(text="X Slice")
    line_slider_label_x.visibility = True
    x_counter = itertools.count()

    def label_callback_x(obj, event):
        line_slider_label_x.visibility = not line_slider_label_x.visibility
        line_slider_x.set_visibility(line_slider_label_x.visibility)
        cnt = next(x_counter)
        if line_slider_label_x.visibility and cnt > 0:
            scene.add(mem.slicer_curr_actor_x)
        else:
            scene.rm(mem.slicer_curr_actor_x)
        iren.Render()

    line_slider_label_x.actor.AddObserver('LeftButtonPressEvent',
                                          label_callback_x, 1.0)

    line_slider_label_y = build_label(text="Y Slice")
    line_slider_label_y.visibility = True
    y_counter = itertools.count()

    def label_callback_y(obj, event):
        line_slider_label_y.visibility = not line_slider_label_y.visibility
        line_slider_y.set_visibility(line_slider_label_y.visibility)
        cnt = next(y_counter)
        if line_slider_label_y.visibility and cnt > 0:
            scene.add(mem.slicer_curr_actor_y)
        else:
            scene.rm(mem.slicer_curr_actor_y)
        iren.Render()

    line_slider_label_y.actor.AddObserver('LeftButtonPressEvent',
                                          label_callback_y, 1.0)

    line_slider_label_z = build_label(text="Z Slice")
    line_slider_label_z.visibility = True
    z_counter = itertools.count()

    def label_callback_z(obj, event):
        line_slider_label_z.visibility = not line_slider_label_z.visibility
        line_slider_z.set_visibility(line_slider_label_z.visibility)
        cnt = next(z_counter)
        if line_slider_label_z.visibility and cnt > 0:
            scene.add(mem.slicer_curr_actor_z)
        else:
            scene.rm(mem.slicer_curr_actor_z)

        iren.Render()

    line_slider_label_z.actor.AddObserver('LeftButtonPressEvent',
                                          label_callback_z, 1.0)

    opacity_slider_label = build_label(text="Opacity")
    volume_slider_label = build_label(text="Volume")
    picker_label = build_label(text='')
    double_slider_label = build_label(text='Colormap')
    slicer_panel_label = build_label(text="Slicer panel", bold=True)

    def label_colormap_callback(obj, event):

        if mem.slicer_colormap_cnt == len(mem.slicer_colormaps) - 1:
            mem.slicer_colormap_cnt = 0
        else:
            mem.slicer_colormap_cnt += 1

        cnt = mem.slicer_colormap_cnt
        mem.slicer_colormap = mem.slicer_colormaps[cnt]
        double_slider_label.message = mem.slicer_colormap
        values = double_slider._values
        r1, r2 = values
        apply_colormap(r1, r2)
        iren.Render()

    double_slider_label.actor.AddObserver('LeftButtonPressEvent',
                                          label_colormap_callback, 1.0)

    # volume_slider.on_right_mouse_button_released = change_volume2
    def label_opacity_callback(obj, event):
        if opacity_slider.value == 0:
            opacity_slider.value = 100
            opacity_slider.update()
            slicer_opacity = 1
        else:
            opacity_slider.value = 0
            opacity_slider.update()
            slicer_opacity = 0
        mem.slicer_curr_actor_x.opacity(slicer_opacity)
        mem.slicer_curr_actor_y.opacity(slicer_opacity)
        mem.slicer_curr_actor_z.opacity(slicer_opacity)
        iren.Render()

    opacity_slider_label.actor.AddObserver('LeftButtonPressEvent',
                                           label_opacity_callback, 1.0)

    if data.ndim == 4:
        panel_size = (320, 400 + 100)
    if data.ndim == 3:
        panel_size = (320, 300 + 100)

    panel = ui.Panel2D(size=panel_size,
                       position=(870, 10),
                       color=(1, 1, 1),
                       opacity=0.1,
                       align="right")

    ys = np.linspace(0, 1, 10)

    panel.add_element(line_slider_z, coords=(0.42, ys[1]))
    panel.add_element(line_slider_y, coords=(0.42, ys[2]))
    panel.add_element(line_slider_x, coords=(0.42, ys[3]))
    panel.add_element(opacity_slider, coords=(0.42, ys[4]))
    panel.add_element(double_slider, coords=(0.42, (ys[7] + ys[8]) / 2.))

    if data.ndim == 4:
        if data.shape[-1] > 3:
            panel.add_element(volume_slider, coords=(0.42, ys[6]))

    panel.add_element(line_slider_label_z, coords=(0.1, ys[1]))
    panel.add_element(line_slider_label_y, coords=(0.1, ys[2]))
    panel.add_element(line_slider_label_x, coords=(0.1, ys[3]))
    panel.add_element(opacity_slider_label, coords=(0.1, ys[4]))
    panel.add_element(double_slider_label, coords=(0.1, (ys[7] + ys[8]) / 2.))

    if data.ndim == 4:
        if data.shape[-1] > 3:
            panel.add_element(volume_slider_label, coords=(0.1, ys[6]))

    panel.add_element(picker_label, coords=(0.2, ys[5]))

    panel.add_element(slicer_panel_label, coords=(0.05, 0.9))

    scene.add(panel)

    # initialize colormap
    r1, r2 = value_range
    apply_colormap(r1, r2)

    return panel
Пример #17
0
    Nativegroupstreamlines = Nativegroupstreamlines1
    groupLinesFA = groupLinesFA1
    name = 'Group_Young'
else:
    Nativegroupstreamlines = Nativegroupstreamlines2
    groupLinesFA = groupLinesFA2
    name = 'Group_Old'

cmap = actor.colormap_lookup_table(scale_range=(np.min(groupLinesFA),
                                                np.max(groupLinesFA)))

renderer = window.Renderer()
stream_actor = actor.line(Nativegroupstreamlines,
                          np.array(groupLinesFA),
                          lookup_colormap=cmap)
fa_actor = actor.slicer(fa_control, np.eye(4))
renderer.add(stream_actor)
renderer.add(fa_actor)
bar = actor.scalar_bar(cmap)
renderer.add(bar)
# Uncomment the line below to show to display the window
window.show(renderer, size=(600, 600), reset_camera=False)
window.record(renderer,
              size=(600, 600),
              out_path=outpath + '/' + str(target_l) + '--' + str(target_r) +
              name + ' lineFA Viz.png')

# %%
##### color by points
group = 1
Пример #18
0
def test_slicer():
    renderer = window.renderer()
    data = (255 * np.random.rand(50, 50, 50))
    affine = np.eye(4)
    slicer = actor.slicer(data, affine)
    slicer.display(None, None, 25)
    renderer.add(slicer)

    renderer.reset_camera()
    renderer.reset_clipping_range()
    # window.show(renderer)

    # copy pixels in numpy array directly
    arr = window.snapshot(renderer, 'test_slicer.png', offscreen=True)
    import scipy
    print(scipy.__version__)
    print(scipy.__file__)

    print(arr.sum())
    print(np.sum(arr == 0))
    print(np.sum(arr > 0))
    print(arr.shape)
    print(arr.dtype)

    report = window.analyze_snapshot(arr, find_objects=True)

    npt.assert_equal(report.objects, 1)
    # print(arr[..., 0])

    # The slicer can cut directly a smaller part of the image
    slicer.display_extent(10, 30, 10, 30, 35, 35)
    renderer.ResetCamera()

    renderer.add(slicer)

    # save pixels in png file not a numpy array
    with TemporaryDirectory() as tmpdir:
        fname = os.path.join(tmpdir, 'slice.png')
        # window.show(renderer)
        window.snapshot(renderer, fname, offscreen=True)
        report = window.analyze_snapshot(fname, find_objects=True)
        npt.assert_equal(report.objects, 1)

    npt.assert_raises(ValueError, actor.slicer, np.ones(10))

    renderer.clear()

    rgb = np.zeros((30, 30, 30, 3))
    rgb[..., 0] = 1.
    rgb_actor = actor.slicer(rgb)

    renderer.add(rgb_actor)

    renderer.reset_camera()
    renderer.reset_clipping_range()

    arr = window.snapshot(renderer, offscreen=True)
    report = window.analyze_snapshot(arr, colors=[(255, 0, 0)])
    npt.assert_equal(report.objects, 1)
    npt.assert_equal(report.colors_found, [True])

    lut = actor.colormap_lookup_table(scale_range=(0, 255),
                                      hue_range=(0.4, 1.),
                                      saturation_range=(1, 1.),
                                      value_range=(0., 1.))
    renderer.clear()
    slicer_lut = actor.slicer(data, lookup_colormap=lut)

    slicer_lut.display(10, None, None)
    slicer_lut.display(None, 10, None)
    slicer_lut.display(None, None, 10)
    
    slicer_lut.opacity(0.5)
    slicer_lut.tolerance(0.03)
    slicer_lut2 = slicer_lut.copy()
    npt.assert_equal(slicer_lut2.GetOpacity(), 0.5)
    npt.assert_equal(slicer_lut2.picker.GetTolerance(), 0.03)
    slicer_lut2.opacity(1)
    slicer_lut2.tolerance(0.025)
    slicer_lut2.display(None, None, 10)
    renderer.add(slicer_lut2)

    renderer.reset_clipping_range()

    arr = window.snapshot(renderer, offscreen=True)
    report = window.analyze_snapshot(arr, find_objects=True)
    npt.assert_equal(report.objects, 1)

    renderer.clear()

    data = (255 * np.random.rand(50, 50, 50))
    affine = np.diag([1, 3, 2, 1])
    slicer = actor.slicer(data, affine, interpolation='nearest')
    slicer.display(None, None, 25)

    renderer.add(slicer)
    renderer.reset_camera()
    renderer.reset_clipping_range()

    arr = window.snapshot(renderer, offscreen=True)
    report = window.analyze_snapshot(arr, find_objects=True)
    npt.assert_equal(report.objects, 1)
    npt.assert_equal(data.shape, slicer.shape)

    renderer.clear()

    data = (255 * np.random.rand(50, 50, 50))
    affine = np.diag([1, 3, 2, 1])

    from dipy.align.reslice import reslice

    data2, affine2 = reslice(data, affine, zooms=(1, 3, 2),
                             new_zooms=(1, 1, 1))

    slicer = actor.slicer(data2, affine2, interpolation='linear')
    slicer.display(None, None, 25)

    renderer.add(slicer)
    renderer.reset_camera()
    renderer.reset_clipping_range()

    # window.show(renderer, reset_camera=False)
    arr = window.snapshot(renderer, offscreen=True)
    report = window.analyze_snapshot(arr, find_objects=True)
    npt.assert_equal(report.objects, 1)
    npt.assert_array_equal([1, 3, 2] * np.array(data.shape),
                           np.array(slicer.shape))
Пример #19
0
def fiber_simple_3d_show_advanced(img,
                                  streamlines,
                                  colors=None,
                                  linewidth=1,
                                  s='png',
                                  imgcolor=False):

    streamlines = streamlines
    data = img.get_data()
    shape = img.shape
    affine = img.affine
    """
    With our current design it is easy to decide in which space you want the
    streamlines and slices to appear. The default we have here is to appear in
    world coordinates (RAS 1mm).
    """

    world_coords = True
    """
    If we want to see the objects in native space we need to make sure that all
    objects which are currently in world coordinates are transformed back to
    native space using the inverse of the affine.
    """

    if not world_coords:
        from dipy.tracking.streamline import transform_streamlines
        streamlines = transform_streamlines(streamlines, np.linalg.inv(affine))
    """
    Now we create, a ``Renderer`` object and add the streamlines using the ``line``
    function and an image plane using the ``slice`` function.
    """

    ren = window.Renderer()
    stream_actor = actor.line(streamlines, colors=colors, linewidth=linewidth)
    """img colormap"""
    if imgcolor:
        lut = actor.colormap_lookup_table(scale_range=(0, 1),
                                          hue_range=(0, 1.),
                                          saturation_range=(0., 1.),
                                          value_range=(0., 1.))
    else:
        lut = None
    if not world_coords:
        image_actor_z = actor.slicer(data,
                                     affine=np.eye(4),
                                     lookup_colormap=lut)
    else:
        image_actor_z = actor.slicer(data, affine, lookup_colormap=lut)
    """
    We can also change also the opacity of the slicer.
    """

    slicer_opacity = 0.6
    image_actor_z.opacity(slicer_opacity)
    """
    We can add additonal slicers by copying the original and adjusting the
    ``display_extent``.
    """

    image_actor_x = image_actor_z.copy()
    image_actor_x.opacity(slicer_opacity)
    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()
    image_actor_y.opacity(slicer_opacity)
    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)
    """
    Connect the actors with the Renderer.
    """

    ren.add(stream_actor)
    ren.add(image_actor_z)
    ren.add(image_actor_x)
    ren.add(image_actor_y)
    """
    Now we would like to change the position of each ``image_actor`` using a
    slider. The sliders are widgets which require access to different areas of the
    visualization pipeline and therefore we don't recommend using them with
    ``show``. The more appropriate way is to use them with the ``ShowManager``
    object which allows accessing the pipeline in different areas. Here is how:
    """

    show_m = window.ShowManager(ren, size=(1200, 900))
    show_m.initialize()
    """
    After we have initialized the ``ShowManager`` we can go ahead and create
    sliders to move the slices and change their opacity.
    """

    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    line_slider_x = ui.LineSlider2D(min_value=0,
                                    max_value=shape[0] - 1,
                                    initial_value=shape[0] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    line_slider_y = ui.LineSlider2D(min_value=0,
                                    max_value=shape[1] - 1,
                                    initial_value=shape[1] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    opacity_slider = ui.LineSlider2D(min_value=0.0,
                                     max_value=1.0,
                                     initial_value=slicer_opacity,
                                     length=140)
    """
    Now we will write callbacks for the sliders and register them.
    """
    def change_slice_z(i_ren, obj, slider):
        z = int(np.round(slider.value))
        image_actor_z.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)

    def change_slice_x(i_ren, obj, slider):
        x = int(np.round(slider.value))
        image_actor_x.display_extent(x, x, 0, shape[1] - 1, 0, shape[2] - 1)

    def change_slice_y(i_ren, obj, slider):
        y = int(np.round(slider.value))
        image_actor_y.display_extent(0, shape[0] - 1, y, y, 0, shape[2] - 1)

    def change_opacity(i_ren, obj, slider):
        slicer_opacity = slider.value
        image_actor_z.opacity(slicer_opacity)
        image_actor_x.opacity(slicer_opacity)
        image_actor_y.opacity(slicer_opacity)

    line_slider_z.add_callback(line_slider_z.slider_disk, "MouseMoveEvent",
                               change_slice_z)
    line_slider_x.add_callback(line_slider_x.slider_disk, "MouseMoveEvent",
                               change_slice_x)
    line_slider_y.add_callback(line_slider_y.slider_disk, "MouseMoveEvent",
                               change_slice_y)
    opacity_slider.add_callback(opacity_slider.slider_disk, "MouseMoveEvent",
                                change_opacity)
    """
    We'll also create text labels to identify the sliders.
    """

    def build_label(text):
        label = ui.TextBlock2D()
        label.message = text
        label.font_size = 18
        label.font_family = 'Arial'
        label.justification = 'left'
        label.bold = False
        label.italic = False
        label.shadow = False
        # label.actor.GetTextProperty().SetBackgroundColor(0, 0, 0)
        # label.actor.GetTextProperty().SetBackgroundOpacity(0.0)
        label.color = (1, 1, 1)

        return label

    line_slider_label_z = build_label(text="Z Slice")
    line_slider_label_x = build_label(text="X Slice")
    line_slider_label_y = build_label(text="Y Slice")
    opacity_slider_label = build_label(text="Opacity")
    """
    Now we will create a ``panel`` to contain the sliders and labels.
    """

    panel = ui.Panel2D(center=(1030, 120),
                       size=(300, 200),
                       color=(1, 1, 1),
                       opacity=0.1,
                       align="right")

    panel.add_element(line_slider_label_x, 'relative', (0.1, 0.75))
    panel.add_element(line_slider_x, 'relative', (0.65, 0.8))
    panel.add_element(line_slider_label_y, 'relative', (0.1, 0.55))
    panel.add_element(line_slider_y, 'relative', (0.65, 0.6))
    panel.add_element(line_slider_label_z, 'relative', (0.1, 0.35))
    panel.add_element(line_slider_z, 'relative', (0.65, 0.4))
    panel.add_element(opacity_slider_label, 'relative', (0.1, 0.15))
    panel.add_element(opacity_slider, 'relative', (0.65, 0.2))

    show_m.ren.add(panel)
    """
    Then, we can render all the widgets and everything else in the screen and
    start the interaction using ``show_m.start()``.


    However, if you change the window size, the panel will not update its position
    properly. The solution to this issue is to update the position of the panel
    using its ``re_align`` method every time the window size changes.
    """

    global size
    size = ren.GetSize()

    def win_callback(obj, event):
        global size
        if size != obj.GetSize():
            size_old = size
            size = obj.GetSize()
            size_change = [size[0] - size_old[0], 0]
            panel.re_align(size_change)

    show_m.initialize()
    """
    Finally, please set the following variable to ``True`` to interact with the
    datasets in 3D.
    """

    interactive = True  #False

    ren.zoom(1.5)
    ren.reset_clipping_range()

    if interactive:

        show_m.add_window_callback(win_callback)
        show_m.render()
        show_m.start()

    else:

        window.record(
            ren,
            out_path=
            '/home/brain/workingdir/data/dwi/hcp/preprocessed/response_dhollander/'
            '100408/result/result20vs45/cc_clustering_png1/100408lr15_%s.png' %
            s,
            size=(1200, 900),
            reset_camera=False)
    """
    .. figure:: bundles_and_3_slices.png
       :align: center

       A few bundles with interactive slicing.
    """

    del show_m
    """
Пример #20
0
after the cleaning procedure via RFBC thresholding (see
:ref:`optic_radiation_after_cleaning`).
"""

# Visualize the results
from dipy.viz import window, actor

# Create scene
scene = window.Scene()

# Original lines colored by LFBC
lineactor = actor.line(fbc_sl_orig, clrs_orig, linewidth=0.2)
scene.add(lineactor)

# Horizontal (axial) slice of T1 data
vol_actor1 = actor.slicer(t1_data, affine=affine)
vol_actor1.display(z=20)
scene.add(vol_actor1)

# Vertical (sagittal) slice of T1 data
vol_actor2 = actor.slicer(t1_data, affine=affine)
vol_actor2.display(x=35)
scene.add(vol_actor2)

# Show original fibers
scene.set_camera(position=(-264, 285, 155),
                 focal_point=(0, -14, 9),
                 view_up=(0, 0, 1))
window.record(scene, n_frames=1, out_path='OR_before.png', size=(900, 900))
if interactive:
    window.show(scene)
Пример #21
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)
Пример #22
0
def main():
    # reads the tractography data in trk format
    # extracts streamlines and the file header. Streamlines should be in the same coordinate system as the FA map (used later).
    # input example: '/home/Example_data/tracts.trk'
    tractography_file = input(
        "Please, specify the file with tracts that you would like to analyse. File should be in the trk format. "
    )

    streams, hdr = load_trk(tractography_file)  # for old DIPY version
    # sft = load_trk(tractography_file, tractography_file)
    # streams = sft.streamlines
    streams_array = np.asarray(streams)
    print('imported tractography data:' + tractography_file)

    # load T1fs_conform image that operates in the same coordinates as simnibs except for the fact the center of mesh
    # is located at the image center
    # T1fs_conform image should be generated in advance during the head meshing procedure
    # input example: fname_T1='/home/Example_data/T1fs_conform.nii.gz'

    fname_T1 = input(
        "Please, specify the T1fs_conform image that has been generated during head meshing procedure. "
    )
    data_T1, affine_T1 = load_nifti(fname_T1)

    # load FA image in the same coordinates as tracts
    # input example:fname_FA='/home/Example_data/DTI_FA.nii'
    fname_FA = input("Please, specify the FA image. ")
    data_FA, affine_FA = load_nifti(fname_FA)

    print('loaded T1fs_conform.nii and FA images')

    # specify the head mesh file that is used later in simnibs to simulate induced electric field
    # input example:'/home/Example_data/SUBJECT_MESH.msh'
    global mesh_path
    mesh_path = input("Please, specify the head mesh file. ")

    last_slach = max([i for i, ltr in enumerate(mesh_path) if ltr == '/']) + 1
    global subject_name
    subject_name = mesh_path[last_slach:-4]

    # specify the directory where you would like to save your simulation results
    # input example:'/home/Example_data/Output'
    global out_dir
    out_dir = input(
        "Please, specify the directory where you would like to save your simulation results. "
    )
    out_dir = out_dir + '/simulation_at_pos_'

    # Co-registration of T1fs_conform and FA images. Performed in 4 steps.
    # Step 1. Calculation of the center of mass transform. Used later as starting transform.
    c_of_mass = transform_centers_of_mass(data_T1, affine_T1, data_FA,
                                          affine_FA)
    print('calculated c_of_mass transformation')

    # Step 2. Calculation of a 3D translation transform. Used in the next step as starting transform.
    nbins = 32
    sampling_prop = None
    metric = MutualInformationMetric(nbins, sampling_prop)
    level_iters = [10000, 1000, 100]
    sigmas = [3.0, 1.0, 0.0]
    factors = [4, 2, 1]
    affreg = AffineRegistration(metric=metric,
                                level_iters=level_iters,
                                sigmas=sigmas,
                                factors=factors)

    transform = TranslationTransform3D()
    params0 = None
    starting_affine = c_of_mass.affine
    translation = affreg.optimize(data_T1,
                                  data_FA,
                                  transform,
                                  params0,
                                  affine_T1,
                                  affine_FA,
                                  starting_affine=starting_affine)
    print('calculated 3D translation transform')

    # Step 3. Calculation of a Rigid 3D transform. Used in the next step as starting transform
    transform = RigidTransform3D()
    params0 = None
    starting_affine = translation.affine
    rigid = affreg.optimize(data_T1,
                            data_FA,
                            transform,
                            params0,
                            affine_T1,
                            affine_FA,
                            starting_affine=starting_affine)
    print('calculated Rigid 3D transform')

    # Step 4. Calculation of an affine transform. Used for co-registration of T1 and FA images.
    transform = AffineTransform3D()
    params0 = None
    starting_affine = rigid.affine
    affine = affreg.optimize(data_T1,
                             data_FA,
                             transform,
                             params0,
                             affine_T1,
                             affine_FA,
                             starting_affine=starting_affine)

    print('calculated Affine 3D transform')

    identity = np.eye(4)

    inv_affine_FA = np.linalg.inv(affine_FA)
    inv_affine_T1 = np.linalg.inv(affine_T1)
    inv_affine = np.linalg.inv(affine.affine)

    # transforming streamlines to FA space
    new_streams_FA = streamline.transform_streamlines(streams, inv_affine_FA)
    new_streams_FA_array = np.asarray(new_streams_FA)

    T1_to_FA = np.dot(inv_affine_FA, np.dot(affine.affine, affine_T1))
    FA_to_T1 = np.linalg.inv(T1_to_FA)

    # transforming streamlines from FA to T1 space
    new_streams_T1 = streamline.transform_streamlines(new_streams_FA, FA_to_T1)
    global new_streams_T1_array
    new_streams_T1_array = np.asarray(new_streams_T1)

    # calculating amline derivatives along the streamlines to get the local orientation of the streamlines
    global streams_array_derivative
    streams_array_derivative = copy.deepcopy(new_streams_T1_array)

    print('calculating amline derivatives')
    for stream in range(len(new_streams_T1_array)):
        my_steam = new_streams_T1_array[stream]
        for t in range(len(my_steam[:, 0])):
            streams_array_derivative[stream][t,
                                             0] = my_deriv(t, my_steam[:, 0])
            streams_array_derivative[stream][t,
                                             1] = my_deriv(t, my_steam[:, 1])
            streams_array_derivative[stream][t,
                                             2] = my_deriv(t, my_steam[:, 2])
            deriv_norm = np.linalg.norm(streams_array_derivative[stream][t, :])
            streams_array_derivative[stream][
                t, :] = streams_array_derivative[stream][t, :] / deriv_norm

    # to create a torus representing a coil in an interactive window

    torus = vtk.vtkParametricTorus()
    torus.SetRingRadius(5)
    torus.SetCrossSectionRadius(2)

    torusSource = vtk.vtkParametricFunctionSource()
    torusSource.SetParametricFunction(torus)
    torusSource.SetScalarModeToPhase()

    torusMapper = vtk.vtkPolyDataMapper()
    torusMapper.SetInputConnection(torusSource.GetOutputPort())
    torusMapper.SetScalarRange(0, 360)

    torusActor = vtk.vtkActor()
    torusActor.SetMapper(torusMapper)

    torus_pos_x = 100
    torus_pos_y = 129
    torus_pos_z = 211
    torusActor.SetPosition(torus_pos_x, torus_pos_y, torus_pos_z)

    list_streams_T1 = list(new_streams_T1)
    # adding one fictive bundle of length 1 with coordinates [0,0,0] to avoid some bugs with actor.line during visualization
    list_streams_T1.append(np.array([0, 0, 0]))

    global bundle_native
    bundle_native = list_streams_T1

    # generating a list of colors to visualize later the stimualtion effects
    effect_max = 0.100
    effect_min = -0.100
    global colors
    colors = [
        np.random.rand(*current_streamline.shape)
        for current_streamline in bundle_native
    ]

    for my_streamline in range(len(bundle_native) - 1):
        my_stream = copy.deepcopy(bundle_native[my_streamline])
        for point in range(len(my_stream)):
            colors[my_streamline][point] = vtkplotter.colors.colorMap(
                (effect_min + effect_max) / 2,
                name='jet',
                vmin=effect_min,
                vmax=effect_max)

    colors[my_streamline + 1] = vtkplotter.colors.colorMap(effect_min,
                                                           name='jet',
                                                           vmin=effect_min,
                                                           vmax=effect_max)

    # Vizualization of fibers over T1

    # i_coord = 0
    # j_coord = 0
    # k_coord = 0
    # global number_of_stimulations
    number_of_stimulations = 0

    actor_line_list = []

    scene = window.Scene()
    scene.clear()
    scene.background((0.5, 0.5, 0.5))

    world_coords = False
    shape = data_T1.shape

    lut = actor.colormap_lookup_table(scale_range=(effect_min, effect_max),
                                      hue_range=(0.4, 1.),
                                      saturation_range=(1, 1.))

    # # the lines below is for a non-interactive demonstration run only.
    # # they should remain commented unless you set "interactive" to False
    # lut, colors = change_TMS_effects(torus_pos_x, torus_pos_y, torus_pos_z)
    # bar =  actor.scalar_bar(lut)
    # bar.SetTitle("TMS effect")
    # bar.SetHeight(0.3)
    # bar.SetWidth(0.10)
    # bar.SetPosition(0.85, 0.3)
    # scene.add(bar)

    actor_line_list.append(
        actor.line(bundle_native,
                   colors,
                   linewidth=5,
                   fake_tube=True,
                   lookup_colormap=lut))

    if not world_coords:
        image_actor_z = actor.slicer(data_T1, identity)
    else:
        image_actor_z = actor.slicer(data_T1, identity)

    slicer_opacity = 0.6
    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)
    """
    Connect the actors with the scene.
    """

    scene.add(actor_line_list[0])
    scene.add(image_actor_z)
    scene.add(image_actor_x)
    scene.add(image_actor_y)

    show_m = window.ShowManager(scene, size=(1200, 900))
    show_m.initialize()
    """
    Create sliders to move the slices and change their opacity.
    """

    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    line_slider_x = ui.LineSlider2D(min_value=0,
                                    max_value=shape[0] - 1,
                                    initial_value=shape[0] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    line_slider_y = ui.LineSlider2D(min_value=0,
                                    max_value=shape[1] - 1,
                                    initial_value=shape[1] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    opacity_slider = ui.LineSlider2D(min_value=0.0,
                                     max_value=1.0,
                                     initial_value=slicer_opacity,
                                     length=140)
    """
    Сallbacks for the sliders.
    """
    def change_slice_z(slider):
        z = int(np.round(slider.value))
        image_actor_z.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)

    def change_slice_x(slider):
        x = int(np.round(slider.value))
        image_actor_x.display_extent(x, x, 0, shape[1] - 1, 0, shape[2] - 1)

    def change_slice_y(slider):
        y = int(np.round(slider.value))
        image_actor_y.display_extent(0, shape[0] - 1, y, y, 0, shape[2] - 1)

    def change_opacity(slider):
        slicer_opacity = slider.value
        image_actor_z.opacity(slicer_opacity)
        image_actor_x.opacity(slicer_opacity)
        image_actor_y.opacity(slicer_opacity)

    line_slider_z.on_change = change_slice_z
    line_slider_x.on_change = change_slice_x
    line_slider_y.on_change = change_slice_y
    opacity_slider.on_change = change_opacity
    """
    Сreate text labels to identify the sliders.
    """

    def build_label(text):
        label = ui.TextBlock2D()
        label.message = text
        label.font_size = 18
        label.font_family = 'Arial'
        label.justification = 'left'
        label.bold = False
        label.italic = False
        label.shadow = False
        label.background = (0, 0, 0)
        label.color = (1, 1, 1)
        return label

    line_slider_label_z = build_label(text="Z Slice")
    line_slider_label_x = build_label(text="X Slice")
    line_slider_label_y = build_label(text="Y Slice")
    opacity_slider_label = build_label(text="Opacity")
    """
    Create a ``panel`` to contain the sliders and labels.
    """

    panel = ui.Panel2D(size=(300, 200),
                       color=(1, 1, 1),
                       opacity=0.1,
                       align="right")
    panel.center = (1030, 120)

    panel.add_element(line_slider_label_x, (0.1, 0.75))
    panel.add_element(line_slider_x, (0.38, 0.75))
    panel.add_element(line_slider_label_y, (0.1, 0.55))
    panel.add_element(line_slider_y, (0.38, 0.55))
    panel.add_element(line_slider_label_z, (0.1, 0.35))
    panel.add_element(line_slider_z, (0.38, 0.35))
    panel.add_element(opacity_slider_label, (0.1, 0.15))
    panel.add_element(opacity_slider, (0.38, 0.15))

    scene.add(panel)
    """
    Create a ``panel`` to show the value of a picked voxel.
    """

    label_position = ui.TextBlock2D(text='Position:')
    label_value = ui.TextBlock2D(text='Value:')

    result_position = ui.TextBlock2D(text='')
    result_value = ui.TextBlock2D(text='')

    text2 = ui.TextBlock2D(text='Calculate')

    panel_picking = ui.Panel2D(size=(250, 125),
                               color=(1, 1, 1),
                               opacity=0.1,
                               align="left")
    panel_picking.center = (200, 120)

    panel_picking.add_element(label_position, (0.1, 0.75))
    panel_picking.add_element(label_value, (0.1, 0.45))

    panel_picking.add_element(result_position, (0.45, 0.75))
    panel_picking.add_element(result_value, (0.45, 0.45))

    panel_picking.add_element(text2, (0.1, 0.15))

    icon_files = []
    icon_files.append(('left', read_viz_icons(fname='circle-left.png')))
    button_example = ui.Button2D(icon_fnames=icon_files, size=(100, 30))
    panel_picking.add_element(button_example, (0.5, 0.1))

    def change_text_callback(i_ren, obj, button):
        text2.message = str(i_coord) + ' ' + str(j_coord) + ' ' + str(k_coord)
        torusActor.SetPosition(i_coord, j_coord, k_coord)
        print(i_coord, j_coord, k_coord)
        lut, colors = change_TMS_effects(i_coord, j_coord, k_coord)
        scene.rm(actor_line_list[0])
        actor_line_list.append(
            actor.line(bundle_native,
                       colors,
                       linewidth=5,
                       fake_tube=True,
                       lookup_colormap=lut))
        scene.add(actor_line_list[1])

        nonlocal number_of_stimulations
        global bar
        if number_of_stimulations > 0:
            scene.rm(bar)
        else:
            number_of_stimulations = number_of_stimulations + 1

        bar = actor.scalar_bar(lut)
        bar.SetTitle("TMS effect")

        bar.SetHeight(0.3)
        bar.SetWidth(0.10)  # the width is set first
        bar.SetPosition(0.85, 0.3)
        scene.add(bar)

        actor_line_list.pop(0)
        i_ren.force_render()

    button_example.on_left_mouse_button_clicked = change_text_callback

    scene.add(panel_picking)
    scene.add(torusActor)

    def left_click_callback(obj, ev):
        """Get the value of the clicked voxel and show it in the panel."""
        event_pos = show_m.iren.GetEventPosition()

        obj.picker.Pick(event_pos[0], event_pos[1], 0, scene)

        global i_coord, j_coord, k_coord
        i_coord, j_coord, k_coord = obj.picker.GetPointIJK()
        print(i_coord, j_coord, k_coord)
        result_position.message = '({}, {}, {})'.format(
            str(i_coord), str(j_coord), str(k_coord))
        result_value.message = '%.8f' % data_T1[i_coord, j_coord, k_coord]
        torusActor.SetPosition(i_coord, j_coord, k_coord)

    image_actor_z.AddObserver('LeftButtonPressEvent', left_click_callback, 1.0)

    global size
    size = scene.GetSize()

    def win_callback(obj, event):
        global size
        if size != obj.GetSize():
            size_old = size
            size = obj.GetSize()
            size_change = [size[0] - size_old[0], 0]
            panel.re_align(size_change)

    show_m.initialize()
    """
    Set the following variable to ``True`` to interact with the datasets in 3D.
    """
    interactive = True

    scene.zoom(2.0)
    scene.reset_clipping_range()
    scene.set_camera(position=(-642.07, 495.40, 148.49),
                     focal_point=(127.50, 127.50, 127.50),
                     view_up=(0.02, -0.01, 1.00))

    if interactive:
        show_m.add_window_callback(win_callback)
        show_m.render()
        show_m.start()
    else:
        window.record(scene,
                      out_path=out_dir + '/bundles_and_effects.png',
                      size=(1200, 900),
                      reset_camera=True)
Пример #23
0
def slicer_panel(renderer, data=None, affine=None, world_coords=False):
    """ Slicer panel with slicer included

    Parameters
    ----------
    renderer : Renderer
    data : 3d ndarray
    affine : 4x4 ndarray
    world_coords : bool
        If True then the affine is applied.

    Returns
    -------
    panel : Panel

    """

    shape = data.shape
    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
    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)

    renderer.add(image_actor_z)
    renderer.add(image_actor_x)
    renderer.add(image_actor_y)

    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    line_slider_x = ui.LineSlider2D(min_value=0,
                                    max_value=shape[0] - 1,
                                    initial_value=shape[0] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    line_slider_y = ui.LineSlider2D(min_value=0,
                                    max_value=shape[1] - 1,
                                    initial_value=shape[1] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    opacity_slider = ui.LineSlider2D(min_value=0.0,
                                     max_value=1.0,
                                     initial_value=slicer_opacity,
                                     length=140)

    def change_slice_z(slider):
        z = int(np.round(slider.value))
        image_actor_z.display_extent(0, shape[0] - 1,
                                     0, shape[1] - 1, z, z)

    def change_slice_x(slider):
        x = int(np.round(slider.value))
        image_actor_x.display_extent(x, x, 0, shape[1] - 1, 0,
                                     shape[2] - 1)

    def change_slice_y(slider):
        y = int(np.round(slider.value))
        image_actor_y.display_extent(0, shape[0] - 1, y, y,
                                     0, shape[2] - 1)

    def change_opacity(slider):
        slicer_opacity = slider.value
        image_actor_z.opacity(slicer_opacity)
        image_actor_x.opacity(slicer_opacity)
        image_actor_y.opacity(slicer_opacity)

    line_slider_z.on_change = change_slice_z
    line_slider_y.on_change = change_slice_y
    line_slider_x.on_change = change_slice_x
    opacity_slider.on_change = change_opacity

    line_slider_label_z = build_label(text="Z Slice")
    line_slider_label_x = build_label(text="X Slice")
    line_slider_label_y = build_label(text="Y Slice")
    opacity_slider_label = build_label(text="Opacity")

    panel = ui.Panel2D(size=(300, 200),
                       position=(850, 110),
                       color=(1, 1, 1),
                       opacity=0.1,
                       align="right")

    panel.add_element(line_slider_label_x, coords=(0.1, 0.75))
    panel.add_element(line_slider_x, coords=(0.4, 0.8))
    panel.add_element(line_slider_label_y, coords=(0.1, 0.55))
    panel.add_element(line_slider_y, coords=(0.4, 0.6))
    panel.add_element(line_slider_label_z, coords=(0.1, 0.35))
    panel.add_element(line_slider_z, coords=(0.4, 0.4))
    panel.add_element(opacity_slider_label, coords=(0.1, 0.15))
    panel.add_element(opacity_slider, coords=(0.4, 0.2))

    renderer.add(panel)
    return panel
Пример #24
0
def show_odfs_and_fa(fa, pam, mask, affine, sphere, ftmp='odf.mmap',
                     basis_type=None, norm_odfs=True, scale_odfs=0.5):
    
    renderer = window.Renderer()
    renderer.background((1, 1, 1))
    
    slice_actor = actor.slicer(fa) #, value_range)
    
    odf_shape = fa.shape + (sphere.vertices.shape[0],)
    odfs = np.memmap(ftmp, dtype=np.float32, mode='w+',
                     shape=odf_shape)
    
    sph_harm_basis = sph_harm_lookup.get(basis_type)

    if sph_harm_basis is None:
        raise ValueError("Invalid basis name.")
    B, m, n = sph_harm_basis(8, sphere.theta, sphere.phi)

    odfs[:] = np.dot(pam.shm_coeff.astype('f4'), B.T.astype('f4'))
    
    odf_slicer = actor.odf_slicer(odfs, mask=mask,
                                  sphere=sphere, scale=scale_odfs,
                                  norm=norm_odfs, colormap='magma')
        
    renderer.add(odf_slicer)
    renderer.add(slice_actor)
    
    show_m = window.ShowManager(renderer, size=(2000, 1000))
    show_m.initialize()
    
    """
    We'll start by creating the panel and adding it to the ``ShowManager``
    """
    
    label_position = ui.TextBlock2D(text='Position:')
    label_value = ui.TextBlock2D(text='Value:')
    
    result_position = ui.TextBlock2D(text='')
    result_value = ui.TextBlock2D(text='')
    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)
    
    def change_slice_z(i_ren, obj, slider):
        z = int(np.round(slider.value))
        slice_actor.display(z=z)
        odf_slicer.display(z=z)
        show_m.render()
    
    line_slider_z.add_callback(line_slider_z.slider_disk,
                               "LeftButtonReleaseEvent",
                               change_slice_z)
    
    panel_picking = ui.Panel2D(center=(200, 120),
                               size=(250, 225),
                               color=(0, 0, 0),
                               opacity=0.75,
                               align="left")
    
    # panel_picking.add_element(label_position, 'relative', (0.1, 0.55))
    # panel_picking.add_element(label_value, 'relative', (0.1, 0.25))
    
    # panel_picking.add_element(result_position, 'relative', (0.45, 0.55))
    # panel_picking.add_element(result_value, 'relative', (0.45, 0.25))
    
    panel_picking.add_element(line_slider_z, 'relative', (0.5, 0.9))
    
    show_m.ren.add(panel_picking)
    
    def left_click_callback(obj, ev):
        """Get the value of the clicked voxel and show it in the panel."""
        event_pos = show_m.iren.GetEventPosition()
    
        obj.picker.Pick(event_pos[0],
                        event_pos[1],
                        0,
                        show_m.ren)
    
        i, j, k = obj.picker.GetPointIJK()
        print(i,j,k)
        result_position.message = '({}, {}, {})'.format(str(i), str(j), str(k))
        result_value.message = '%.3f' % fa[i, j, k]
    
    slice_actor.SetInterpolate(True)
    slice_actor.AddObserver('LeftButtonPressEvent', left_click_callback, 1.0)
        
    show_m.start()
    
    odfs._mmap.close()
    del odfs
    os.remove(ftmp)
Пример #25
0
    def initialize_scene(self):
        self.ren = window.Renderer()
        self.iren = CustomInteractorStyle()
        self.show_m = window.ShowManager(self.ren,
                                         size=self.screen_size,
                                         interactor_style=self.iren)

        # Add clustering panel to the scene.
        self.clustering_panel = self._make_clustering_panel()
        self.clustering_panel.set_visibility(False)
        self.ren.add(self.clustering_panel)

        # Add "Reset/Home" button
        def reset_button_callback(iren, obj, button):
            # iren: CustomInteractorStyle
            # obj: vtkActor picked
            # button: Button2D
            print("Merging remaining bundles...")

            streamlines = nib.streamlines.ArraySequence()
            for k, bundle in self.bundles.items():
                streamlines.extend(bundle.streamlines)
                self.remove_bundle(k)

            if len(streamlines) == 0:
                print("No streamlines left to merge.")
                iren.force_render()
                iren.event.abort()  # Stop propagating the event.
                return

            # Add new root bundle to the scene.
            self.add_bundle(self.root_bundle, Bundle(streamlines))
            self._add_bundle_right_click_callback(
                self.bundles[self.root_bundle], self.root_bundle)
            self.select(None)

            print("{} streamlines merged.".format(len(streamlines)))
            button.color = (1, 1, 1)  # Restore color.
            iren.force_render()
            iren.event.abort()  # Stop propagating the event.

        reset_button = gui_2d.Button2D(
            icon_fnames={'reset': read_viz_icons(fname='home3_neg.png')})
        reset_button.color = (1, 1, 1)
        reset_button.add_callback("LeftButtonPressEvent",
                                  animate_button_callback)
        reset_button.add_callback("LeftButtonReleaseEvent",
                                  reset_button_callback)
        reset_button.set_center(
            (self.screen_size[0] - 20, self.screen_size[1] - 60))
        self.ren.add(reset_button)

        # Add toggle "Centroid/Streamlines" button
        def centroids_toggle_button_callback(iren, obj, button):
            if button.current_icon_name == "streamlines":
                button.next_icon()
                for bundle in self.bundles.values():
                    bundle.show_centroids()
                    bundle.hide_streamlines()

            elif button.current_icon_name == "centroids":
                button.next_icon()
                for bundle in self.bundles.values():
                    bundle.hide_centroids()
                    bundle.show_streamlines()

            iren.force_render()
            iren.event.abort()  # Stop propagating the event.

        centroids_toggle_button = gui_2d.Button2D(
            icon_fnames={
                'streamlines': read_viz_icons(fname='database_neg.png'),
                'centroids': read_viz_icons(fname='centroid_neg.png')
            })
        centroids_toggle_button.color = (1, 1, 1)
        # centroids_toggle_button.add_callback("LeftButtonPressEvent", animate_button_callback)
        centroids_toggle_button.add_callback("LeftButtonReleaseEvent",
                                             centroids_toggle_button_callback)
        centroids_toggle_button.set_center((20, self.screen_size[1] - 20))
        self.ren.add(centroids_toggle_button)

        # Add objects to the scene.
        self.ren.add(self.bundles[self.root_bundle])
        self._add_bundle_right_click_callback(self.bundles[self.root_bundle],
                                              self.root_bundle)

        # Add shortcut keys.
        def select_biggest_cluster_onchar_callback(iren, evt_name):
            if self.verbose:
                print("Pressed {} (shift={}), (ctrl={}), (alt={})".format(
                    iren.event.key, iren.event.shift_key, iren.event.ctrl_key,
                    iren.event.alt_key))

            if iren.event.key.lower() == "escape":
                self.select(None)

            elif "tab" in iren.event.key.lower():
                if iren.event.shift_key:
                    self.select_previous()
                else:
                    self.select_next()
            elif iren.event.key == "c":
                for bundle in self.bundles.values():
                    bundle.show_centroids()
                    bundle.hide_streamlines()
                iren.force_render()
            elif iren.event.key == "C":
                for bundle in self.bundles.values():
                    bundle.hide_centroids()
                    bundle.show_streamlines()
                iren.force_render()

            iren.event.abort()  # Stop propagating the event.

        self.iren.AddObserver("CharEvent",
                              select_biggest_cluster_onchar_callback)

        # Add anatomy, if there is one.
        if self.anat is not None:
            anat_data = self.anat.get_data()
            if anat_data.ndim == 4:
                # Take b0 (assuming it is diffusion data)
                anat_data = anat_data[..., 0]

            self.anat_axial_slicer = actor.slicer(anat_data,
                                                  affine=self.anat.affine)
            self.anat_coronal_slicer = actor.slicer(anat_data,
                                                    affine=self.anat.affine)
            self.anat_sagittal_slicer = actor.slicer(anat_data,
                                                     affine=self.anat.affine)
            self.ren.add(self.anat_axial_slicer, self.anat_coronal_slicer,
                         self.anat_sagittal_slicer)
            self.anatomy_panel = self._make_anatomy_panel(
                self.anat_axial_slicer, self.anat_coronal_slicer,
                self.anat_sagittal_slicer)
            self.ren.add(self.anatomy_panel)
Пример #26
0
# Visualize the results
from dipy.viz import window, actor

# Enables/disables interactive visualization
interactive = False

# Create renderer
ren = window.Renderer()

# Original lines colored by LFBC
lineactor = actor.line(fbc_sl_orig, clrs_orig, linewidth=0.2)
ren.add(lineactor)

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

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

# Show original fibers
ren.set_camera(position=(-264, 285, 155), focal_point=(0, -14, 9), view_up=(0, 0, 1))
window.record(ren, n_frames=1, out_path='OR_before.png', size=(900, 900))
if interactive:
    window.show(ren)

# Show thresholded fibers
Пример #27
0
"""

if not world_coords:
    from dipy.tracking.streamline import transform_streamlines
    streamlines = transform_streamlines(streamlines, np.linalg.inv(affine))

"""
Now we create, a ``Renderer`` object and add the streamlines using the ``line``
function and an image plane using the ``slice`` function.
"""

ren = window.Renderer()
stream_actor = actor.line(streamlines)

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

"""
We can also change also the opacity of the slicer
"""

slicer_opacity = .6
image_actor.opacity(slicer_opacity)

"""
Connect the actors with the Renderer.
"""

ren.add(stream_actor)
Пример #28
0
        bundle.append(templine)
    all_bundles.append(bundle)
    all_colors.append(tract['color'])
    split_name = tract['name'].split(' ')
    imagename = '_'.join(split_name)

    for d in range(len(camera_pos)):  # directions: axial, sagittal, coronal
        renderer = window.Renderer()
        stream_actor = actor.streamtube(bundle, colors=tract['color'],
                                        linewidth=1)
        renderer.set_camera(position=camera_pos[d],
                            focal_point=focal_point[d],
                            view_up=view_up[d])

        renderer.add(stream_actor)
        slice_actor = actor.slicer(data, affine, value_range)
        if d == 0:
            slice_actor.display(z=int(slice_view[0]))
        elif d == 2:
            slice_actor.display(y=int(slice_view[2]))
        else:
            slice_actor.display(x=int(slice_view[1]))
        renderer.add(slice_actor)

#        show_m = window.ShowManager(renderer, size=(800, 700))
#        show_m.initialize()
#        show_m.render()
#        show_m.start()
#        renderer.camera_info() #get location of camera

        window.snapshot(renderer,
Пример #29
0
def test_slicer():
    renderer = window.renderer()
    data = (255 * np.random.rand(50, 50, 50))
    affine = np.eye(4)
    slicer = actor.slicer(data, affine)
    slicer.display(None, None, 25)
    window.add(renderer, slicer)

    renderer.reset_camera()
    renderer.reset_clipping_range()
    # window.show(renderer)

    # copy pixels in numpy array directly
    arr = window.snapshot(renderer, 'test_slicer.png')
    import scipy
    print(scipy.__version__)
    print(scipy.__file__)

    print(arr.sum())
    print(np.sum(arr == 0))
    print(np.sum(arr > 0))
    print(arr.shape)
    print(arr.dtype)

    report = window.analyze_snapshot(arr, find_objects=True)

    print(report)

    npt.assert_equal(report.objects, 1)
    # print(arr[..., 0])

    # The slicer can cut directly a smaller part of the image
    slicer.display_extent(10, 30, 10, 30, 35, 35)
    renderer.ResetCamera()

    window.add(renderer, slicer)

    # save pixels in png file not a numpy array
    with TemporaryDirectory() as tmpdir:
        fname = os.path.join(tmpdir, 'slice.png')
        # window.show(renderer)
        arr = window.snapshot(renderer, fname)
        report = window.analyze_snapshot(fname, find_objects=True)
        npt.assert_equal(report.objects, 1)

    npt.assert_raises(ValueError, actor.slicer, np.ones(10))

    renderer.clear()

    rgb = np.zeros((30, 30, 30, 3))
    rgb[..., 0] = 1.
    rgb_actor = actor.slicer(rgb)

    renderer.add(rgb_actor)

    renderer.reset_camera()
    renderer.reset_clipping_range()

    arr = window.snapshot(renderer)
    report = window.analyze_snapshot(arr, colors=[(255, 0, 0)])
    npt.assert_equal(report.objects, 1)
    npt.assert_equal(report.colors_found, [True])

    lut = actor.colormap_lookup_table(scale_range=(0, 255),
                                      hue_range=(0.4, 1.),
                                      saturation_range=(1, 1.),
                                      value_range=(0., 1.))
    renderer.clear()
    slicer_lut = actor.slicer(data, lookup_colormap=lut)

    slicer_lut.display(10, None, None)
    slicer_lut.display(None, 10, None)
    slicer_lut.display(None, None, 10)

    slicer_lut2 = slicer_lut.copy()
    slicer_lut2.display(None, None, 10)
    renderer.add(slicer_lut2)

    renderer.reset_clipping_range()

    arr = window.snapshot(renderer)
    report = window.analyze_snapshot(arr, find_objects=True)
    npt.assert_equal(report.objects, 1)
def simple_viewer(streamlines, vol, affine):

    renderer = window.Renderer()
    renderer.add(actor.line(streamlines))
    renderer.add(actor.slicer(vol, affine))
    window.show(renderer)
Пример #31
0
"""
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:
    window.show(ren)

"""
Пример #32
0
Render slices from T1 with a specific value range
=================================================

The T1 has usually a higher range of values than what can be visualized in an
image. We can set the range that we would like to see.
"""

mean, std = data[data > 0].mean(), data[data > 0].std()
value_range = (mean - 0.5 * std, mean + 1.5 * std)
"""
The ``slice`` function will read data and resample the data using an affine
transformation matrix. The default behavior of this function is to show the
middle slice of the last dimension of the resampled data.
"""

slice_actor = actor.slicer(data, affine, value_range)
"""
The ``slice_actor`` contains an axial slice.
"""

renderer.add(slice_actor)
"""
The same actor can show any different slice from the given data using its
``display`` function. However, if we want to show multiple slices we need to
copy the actor first.
"""

slice_actor2 = slice_actor.copy()
"""
Now we have a new ``slice_actor`` which displays the middle slice of sagittal
plane.
Пример #33
0
def test_odf_slicer(interactive=False):

    sphere = get_sphere('symmetric362')

    shape = (11, 11, 11, sphere.vertices.shape[0])

    fid, fname = mkstemp(suffix='_odf_slicer.mmap')
    print(fid)
    print(fname)

    odfs = np.memmap(fname, dtype=np.float64, mode='w+',
                     shape=shape)

    odfs[:] = 1

    affine = np.eye(4)
    renderer = window.Renderer()

    mask = np.ones(odfs.shape[:3])
    mask[:4, :4, :4] = 0

    odfs[..., 0] = 1

    odf_actor = actor.odf_slicer(odfs, affine,
                                 mask=mask, sphere=sphere, scale=.25,
                                 colormap='jet')
    fa = 0. * np.zeros(odfs.shape[:3])
    fa[:, 0, :] = 1.
    fa[:, -1, :] = 1.
    fa[0, :, :] = 1.
    fa[-1, :, :] = 1.
    fa[5, 5, 5] = 1

    k = 5
    I, J, K = odfs.shape[:3]

    fa_actor = actor.slicer(fa, affine)
    fa_actor.display_extent(0, I, 0, J, k, k)
    renderer.add(odf_actor)
    renderer.reset_camera()
    renderer.reset_clipping_range()

    odf_actor.display_extent(0, I, 0, J, k, k)
    odf_actor.GetProperty().SetOpacity(1.0)
    if interactive:
        window.show(renderer, reset_camera=False)

    arr = window.snapshot(renderer)
    report = window.analyze_snapshot(arr, find_objects=True)
    npt.assert_equal(report.objects, 11 * 11)

    renderer.clear()
    renderer.add(fa_actor)
    renderer.reset_camera()
    renderer.reset_clipping_range()
    if interactive:
        window.show(renderer)

    mask[:] = 0
    mask[5, 5, 5] = 1
    fa[5, 5, 5] = 0
    fa_actor = actor.slicer(fa, None)
    fa_actor.display(None, None, 5)
    odf_actor = actor.odf_slicer(odfs, None, mask=mask,
                                 sphere=sphere, scale=.25,
                                 colormap='jet',
                                 norm=False, global_cm=True)
    renderer.clear()
    renderer.add(fa_actor)
    renderer.add(odf_actor)
    renderer.reset_camera()
    renderer.reset_clipping_range()
    if interactive:
        window.show(renderer)

    renderer.clear()
    renderer.add(odf_actor)
    renderer.add(fa_actor)
    odfs[:, :, :] = 1
    mask = np.ones(odfs.shape[:3])
    odf_actor = actor.odf_slicer(odfs, None, mask=mask,
                                 sphere=sphere, scale=.25,
                                 colormap='jet',
                                 norm=False, global_cm=True)

    renderer.clear()
    renderer.add(odf_actor)
    renderer.add(fa_actor)
    renderer.add(actor.axes((11, 11, 11)))
    for i in range(11):
        odf_actor.display(i, None, None)
        fa_actor.display(i, None, None)
        if interactive:
            window.show(renderer)
    for j in range(11):
        odf_actor.display(None, j, None)
        fa_actor.display(None, j, None)
        if interactive:
            window.show(renderer)
    # with mask equal to zero everything should be black
    mask = np.zeros(odfs.shape[:3])
    odf_actor = actor.odf_slicer(odfs, None, mask=mask,
                                 sphere=sphere, scale=.25,
                                 colormap='plasma',
                                 norm=False, global_cm=True)
    renderer.clear()
    renderer.add(odf_actor)
    renderer.reset_camera()
    renderer.reset_clipping_range()
    if interactive:
        window.show(renderer)

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

    del odf_actor
    odfs._mmap.close()
    del odfs
    os.close(fid)

    os.remove(fname)
def simple_viewer(streamlines, vol, affine):

    renderer = window.Renderer()
    renderer.add(actor.line(streamlines))
    renderer.add(actor.slicer(vol, affine))
    window.show(renderer)
Пример #35
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)
Пример #36
0
def plotTrk(trkFile, target, anatFile, roi=None,
        xSlice=None, ySlice=None, zSlice=None,
        xRot=None, yRot=None, zRot=None):

    anatImage = nibabel.load(anatFile)
    trkImage = [s[0] for s in nibabel.trackvis.read(trkFile, points_space='rasmm')[0]]

    ren = window.Renderer()

    trkActor = actor.line(
        trkImage, dipy.viz.colormap.line_colors(trkImage))

    if xSlice is not None:
        anatActorSliceX = actor.slicer(anatImage.get_data(), anatImage.affine)
        anatActorSliceX.display(xSlice, None, None)
        # Apply rotation
        anatActorSliceX.RotateX(xRot)
        anatActorSliceX.RotateY(yRot)
        anatActorSliceX.RotateZ(zRot)

        ren.add(anatActorSliceX)

    if ySlice is not None:
        anatActorSliceY = actor.slicer(anatImage.get_data(), anatImage.affine)
        anatActorSliceY.display(None, ySlice, None)
        # Apply rotation
        anatActorSliceY.RotateX(xRot)
        anatActorSliceY.RotateY(yRot)
        anatActorSliceY.RotateZ(zRot)

        ren.add(anatActorSliceY)

    if zSlice is not None:
        anatActorSliceZ = actor.slicer(anatImage.get_data(), anatImage.affine)
        anatActorSliceZ.display(None, None, zSlice)
        # Apply rotation
        anatActorSliceZ.RotateX(xRot)
        anatActorSliceZ.RotateY(yRot)
        anatActorSliceZ.RotateZ(zRot)

        ren.add(anatActorSliceZ)

    trkActor.RotateX(xRot)
    trkActor.RotateY(yRot)
    trkActor.RotateZ(zRot)

    ren.add(trkActor)

    # Not in dipy 0.11.0 
    # Wait until next version
    # Already fixed here: https://github.com/nipy/dipy/pull/1163
    #if roi is not None:
    #    roiImage= nibabel.load(roi)
    #    roiActor = dipy.viz.fvtk.contour(
    #            roiImage.get_data(), affine=anatomicalImage.affine, levels=[1],
    #            colors=[(1., 1., 0.)], opacities=[1.])

    #    roiActor.RotateX(xRot)
    #    roiActor.RotateY(yRot)
    #    roiActor.RotateZ(zRot)

    #    ren.add(roiActor)
    ren.set_camera(
            position=(0,0,1), focal_point=(0,0,0), view_up=(0,1,0))#, verbose=False)
    #window.record(ren, out_path=target, size=(1200, 1200), n_frames=1)
    window.snapshot(ren, fname=target, size=(1200, 1200), offscreen=True)
Пример #37
0
streamlines = tck_file.streamlines[:10]
T1_file = nib.load('../data/T1w_acpc_dc_restore_brain1.25.nii.gz')
data = T1_file.get_data()
affine = T1_file.affine
shape = data.shape

world_coords = True
if not world_coords:
    from dipy.tracking.streamline import transform_streamlines
    streamlines = transform_streamlines(streamlines, np.linalg.inv(affine))

ren = window.Renderer()
stream_actor = actor.line(streamlines)

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
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)

ren.add(stream_actor)
Пример #38
0
def horizon(tractograms, data, affine, cluster=False, cluster_thr=15.,
            random_colors=False,
            length_lt=0, length_gt=np.inf, clusters_lt=0, clusters_gt=np.inf):

    rng = np.random.RandomState(42)
    slicer_opacity = .8

    ren = window.Renderer()
    global centroid_actors
    centroid_actors = []
    for streamlines in tractograms:

        print(' Number of streamlines loaded {} \n'.format(len(streamlines)))

        if not random_colors:
            ren.add(actor.line(streamlines, opacity=1., lod_points=10 ** 5))
        else:
            colors = rng.rand(3)
            ren.add(actor.line(streamlines, colors, opacity=1., lod_points=10 ** 5))

    class SimpleTrackBallNoBB(window.vtk.vtkInteractorStyleTrackballCamera):
        def HighlightProp(self, p):
            pass

    style = SimpleTrackBallNoBB()
    # very hackish way
    style.SetPickColor(0, 0, 0)
    # style.HighlightProp(None)
    show_m = window.ShowManager(ren, size=(1200, 900), interactor_style=style)
    show_m.initialize()

    if data is not None:
        #from dipy.core.geometry import rodrigues_axis_rotation
        #affine[:3, :3] = np.dot(affine[:3, :3], rodrigues_axis_rotation((0, 0, 1), 45))

        image_actor = actor.slicer(data, affine)
        image_actor.opacity(slicer_opacity)
        image_actor.SetInterpolate(False)
        ren.add(image_actor)

        ren.add(fvtk.axes((10, 10, 10)))

        last_value = [10]
        def change_slice(obj, event):
            new_value = int(np.round(obj.get_value()))
            if new_value == image_actor.shape[1] - 1 or new_value == 0:
                new_value = last_value[0] + np.sign(new_value - last_value[0])

            image_actor.display(None, new_value, None)
            obj.set_value(new_value)
            last_value[0] = new_value

        slider = widget.slider(show_m.iren, show_m.ren,
                               callback=change_slice,
                               min_value=0,
                               max_value=image_actor.shape[1] - 1,
                               value=image_actor.shape[1] / 2,
                               label="Move slice",
                               right_normalized_pos=(.98, 0.6),
                               size=(120, 0), label_format="%0.lf",
                               color=(1., 1., 1.),
                               selected_color=(0.86, 0.33, 1.))

        slider.SetAnimationModeToJump()

    global size
    size = ren.GetSize()
    # ren.background((1, 0.5, 0))
    ren.background((0, 0, 0))
    global picked_actors
    picked_actors = {}

    def pick_callback(obj, event):
        global centroid_actors
        global picked_actors

        prop = obj.GetProp3D()

        ac = np.array(centroid_actors)
        index = np.where(ac == prop)[0]

        if len(index) > 0:
            try:
                bundle = picked_actors[prop]
                ren.rm(bundle)
                del picked_actors[prop]
            except:
                bundle = actor.line(clusters[visible_cluster_id[index]],
                                    lod=False)
                picked_actors[prop] = bundle
                ren.add(bundle)

        if prop in picked_actors.values():
            ren.rm(prop)

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

            if data is not None:
                slider.place(ren)
            size = obj.GetSize()

    global centroid_visibility
    centroid_visibility = True

    def key_press(obj, event):
        global centroid_visibility
        key = obj.GetKeySym()
        if key == 'h' or key == 'H':
            if cluster:
                if centroid_visibility is True:
                    for ca in centroid_actors:
                        ca.VisibilityOff()
                    centroid_visibility = False
                else:
                    for ca in centroid_actors:
                        ca.VisibilityOn()
                    centroid_visibility = True
                show_m.render()

    show_m.initialize()
    show_m.iren.AddObserver('KeyPressEvent', key_press)
    show_m.add_window_callback(win_callback)
    #show_m.add_picker_callback(pick_callback)
    show_m.render()
    show_m.start()
def show_results(data,
                 streamlines,
                 vol,
                 affine,
                 world_coords=True,
                 opacity=0.6):

    from dipy.viz import actor, window, widget

    shape = data.shape

    if not world_coords:
        from dipy.tracking.streamline import transform_streamlines
        streamlines = transform_streamlines(streamlines, np.linalg.inv(affine))

    ren = window.Renderer()
    if streamlines is not None:
        stream_actor = actor.line(streamlines)

    if not world_coords:
        image_actor = actor.slicer(vol, affine=np.eye(4))
    else:
        image_actor = actor.slicer(vol, affine)

    slicer_opacity = opacity  #.6
    image_actor.opacity(slicer_opacity)

    if streamlines is not None:
        ren.add(stream_actor)
    ren.add(image_actor)

    show_m = window.ShowManager(ren, size=(1200, 900))
    show_m.initialize()

    def change_slice(obj, event):
        z = int(np.round(obj.get_value()))
        image_actor.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)

    slider = widget.slider(show_m.iren,
                           show_m.ren,
                           callback=change_slice,
                           min_value=0,
                           max_value=shape[2] - 1,
                           value=shape[2] / 2,
                           label="Move slice",
                           right_normalized_pos=(.98, 0.6),
                           size=(120, 0),
                           label_format="%0.lf",
                           color=(1., 1., 1.),
                           selected_color=(0.86, 0.33, 1.))

    global size
    size = ren.GetSize()

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

            slider.place(ren)
            size = obj.GetSize()

    show_m.initialize()

    show_m.add_window_callback(win_callback)
    show_m.render()
    show_m.start()

    # ren.zoom(1.5)
    # ren.reset_clipping_range()

    # window.record(ren, out_path='bundles_and_a_slice.png', size=(1200, 900),
    #               reset_camera=False)

    del show_m
Пример #40
0
        snapshot_fname = "_".join(bundles) + ".png"
        print("Saving {}".format(snapshot_fname))
        window.snapshot(ren,
                        fname=snapshot_fname,
                        size=resolution,
                        offscreen=True,
                        order_transparent=False)
        return snapshot_fname

    # Prepare VTK scene
    resolution = (800, 600)
    ren = window.Renderer()

    # Load anatomy
    anat = nib.load(anat)
    slicer = actor.slicer(anat.get_data(), affine=anat.affine)

    ########################################
    # Generate all subfigures sequentially #
    ########################################
    snapshots = []

    ###
    # Make subfigure (a) UF, ILF, SLF
    ###
    bundles = ["UF", "ILF", "SLF"]
    ren.clear()
    add_actors(ren, bundles)

    # Select slice to display.
    slicer.display(x=anat.shape[0] - 109)
Пример #41
0
=================================================

The T1 has usually a higher range of values than what can be visualized in an
image. We can set the range that we would like to see.
"""

mean, std = data[data > 0].mean(), data[data > 0].std()
value_range = (mean - 0.5 * std, mean + 1.5 * std)

"""
The ``slice`` function will read data and resample the data using an affine
transformation matrix. The default behavior of this function is to show the
middle slice of the last dimension of the resampled data.
"""

slice_actor = actor.slicer(data, affine, value_range)

"""
The ``slice_actor`` contains an axial slice.
"""

renderer.add(slice_actor)

"""
The same actor can show any different slice from the given data using its
``display`` function. However, if we want to show multiple slices we need to
copy the actor first.
"""

slice_actor2 = slice_actor.copy()
Пример #42
0
def visualize_volume(volume,
                     x=None,
                     y=None,
                     z=None,
                     figure=None,
                     flip_axes=None,
                     opacity=0.6,
                     inline=True,
                     interact=False):
    """
    Visualize a volume

    Parameters
    ----------
    volume : ndarray or str
        3d volume to visualize.

    figure : fury Scene object, optional
        If provided, the visualization will be added to this Scene. Default:
        Initialize a new Scene.

    flip_axes : None
        This parameter is to conform fury and plotly APIs.

    opacity : float, optional
        Initial opacity of slices.
        Default: 0.6

    interact : bool
        Whether to provide an interactive VTK window for interaction.
        Default: False

    inline : bool
        Whether to embed the visualization inline in a notebook. Only works
        in the notebook context. Default: False.

    Returns
    -------
    Fury Scene object
    """
    volume = vut.load_volume(volume)

    if figure is None:
        figure = window.Scene()

    shape = volume.shape
    image_actor_z = actor.slicer(volume)
    slicer_opacity = opacity
    image_actor_z.opacity(slicer_opacity)

    image_actor_x = image_actor_z.copy()
    if x is None:
        x = int(np.round(shape[0] / 2))
    image_actor_x.display_extent(x, x, 0, shape[1] - 1, 0, shape[2] - 1)

    image_actor_y = image_actor_z.copy()

    if y is None:
        y = int(np.round(shape[1] / 2))
    image_actor_y.display_extent(0, shape[0] - 1, y, y, 0, shape[2] - 1)

    figure.add(image_actor_z)
    figure.add(image_actor_x)
    figure.add(image_actor_y)

    show_m = window.ShowManager(figure, size=(1200, 900))
    show_m.initialize()

    if interact:
        line_slider_z = ui.LineSlider2D(min_value=0,
                                        max_value=shape[2] - 1,
                                        initial_value=shape[2] / 2,
                                        text_template="{value:.0f}",
                                        length=140)

        line_slider_x = ui.LineSlider2D(min_value=0,
                                        max_value=shape[0] - 1,
                                        initial_value=shape[0] / 2,
                                        text_template="{value:.0f}",
                                        length=140)

        line_slider_y = ui.LineSlider2D(min_value=0,
                                        max_value=shape[1] - 1,
                                        initial_value=shape[1] / 2,
                                        text_template="{value:.0f}",
                                        length=140)

        opacity_slider = ui.LineSlider2D(min_value=0.0,
                                         max_value=1.0,
                                         initial_value=slicer_opacity,
                                         length=140)

        def change_slice_z(slider):
            z = int(np.round(slider.value))
            image_actor_z.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z,
                                         z)

        def change_slice_x(slider):
            x = int(np.round(slider.value))
            image_actor_x.display_extent(x, x, 0, shape[1] - 1, 0,
                                         shape[2] - 1)

        def change_slice_y(slider):
            y = int(np.round(slider.value))
            image_actor_y.display_extent(0, shape[0] - 1, y, y, 0,
                                         shape[2] - 1)

        def change_opacity(slider):
            slicer_opacity = slider.value
            image_actor_z.opacity(slicer_opacity)
            image_actor_x.opacity(slicer_opacity)
            image_actor_y.opacity(slicer_opacity)

        line_slider_z.on_change = change_slice_z
        line_slider_x.on_change = change_slice_x
        line_slider_y.on_change = change_slice_y
        opacity_slider.on_change = change_opacity

        def build_label(text):
            label = ui.TextBlock2D()
            label.message = text
            label.font_size = 18
            label.font_family = 'Arial'
            label.justification = 'left'
            label.bold = False
            label.italic = False
            label.shadow = False
            label.background = (0, 0, 0)
            label.color = (1, 1, 1)

            return label

        line_slider_label_z = build_label(text="Z Slice")
        line_slider_label_x = build_label(text="X Slice")
        line_slider_label_y = build_label(text="Y Slice")
        opacity_slider_label = build_label(text="Opacity")

        panel = ui.Panel2D(size=(300, 200),
                           color=(1, 1, 1),
                           opacity=0.1,
                           align="right")
        panel.center = (1030, 120)

        panel.add_element(line_slider_label_x, (0.1, 0.75))
        panel.add_element(line_slider_x, (0.38, 0.75))
        panel.add_element(line_slider_label_y, (0.1, 0.55))
        panel.add_element(line_slider_y, (0.38, 0.55))
        panel.add_element(line_slider_label_z, (0.1, 0.35))
        panel.add_element(line_slider_z, (0.38, 0.35))
        panel.add_element(opacity_slider_label, (0.1, 0.15))
        panel.add_element(opacity_slider, (0.38, 0.15))

        show_m.scene.add(panel)

        global size
        size = figure.GetSize()

        def win_callback(obj, event):
            global size
            if size != obj.GetSize():
                size_old = size
                size = obj.GetSize()
                size_change = [size[0] - size_old[0], 0]
                panel.re_align(size_change)

    show_m.initialize()

    figure.zoom(1.5)
    figure.reset_clipping_range()

    if interact:
        show_m.add_window_callback(win_callback)
        show_m.render()
        show_m.start()

    return _inline_interact(figure, inline, interact)
Пример #43
0
"""
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:
    window.show(ren)

"""
Пример #44
0
def slicer_panel(renderer,
                 iren,
                 data=None,
                 affine=None,
                 world_coords=False,
                 pam=None,
                 mask=None):
    """ Slicer panel with slicer included

    Parameters
    ----------
    renderer : Renderer
    iren : Interactor
    data : 3d ndarray
    affine : 4x4 ndarray
    world_coords : bool
        If True then the affine is applied.

    peaks : PeaksAndMetrics
        Default None

    Returns
    -------
    panel : Panel

    """

    orig_shape = data.shape
    print('Original shape', orig_shape)
    ndim = data.ndim
    tmp = data
    if ndim == 4:
        if orig_shape[-1] > 3:
            tmp = data[..., 0]
            orig_shape = orig_shape[:3]
            value_range = np.percentile(data[..., 0], q=[2, 98])
        if orig_shape[-1] == 3:
            value_range = (0, 1.)
            HORIMEM.slicer_rgb = True
    if ndim == 3:
        value_range = np.percentile(tmp, q=[2, 98])

    if not world_coords:
        affine = np.eye(4)

    image_actor_z = actor.slicer(tmp,
                                 affine=affine,
                                 value_range=value_range,
                                 interpolation='nearest',
                                 picking_tol=0.025)

    tmp_new = image_actor_z.resliced_array()

    if len(data.shape) == 4:
        if data.shape[-1] == 3:
            print('Resized to RAS shape ', tmp_new.shape)
        else:
            print('Resized to RAS shape ', tmp_new.shape + (data.shape[-1], ))
    else:
        print('Resized to RAS shape ', tmp_new.shape)

    shape = tmp_new.shape

    if pam is not None:

        peaks_actor_z = actor.peak_slicer(pam.peak_dirs,
                                          None,
                                          mask=mask,
                                          affine=affine,
                                          colors=None)

    slicer_opacity = 1.
    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)

    renderer.add(image_actor_z)
    renderer.add(image_actor_x)
    renderer.add(image_actor_y)

    if pam is not None:
        renderer.add(peaks_actor_z)

    line_slider_z = ui.LineSlider2D(min_value=0,
                                    max_value=shape[2] - 1,
                                    initial_value=shape[2] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    _color_slider(line_slider_z)

    button = ui.Button2D(icon_fnames, size=(20, 30))

    def change_slice_z(slider):
        z = int(np.round(slider.value))
        HORIMEM.slicer_curr_actor_z.display_extent(0, shape[0] - 1, 0,
                                                   shape[1] - 1, z, z)
        if pam is not None:
            HORIMEM.slicer_peaks_actor_z.display_extent(
                0, shape[0] - 1, 0, shape[1] - 1, z, z)
        HORIMEM.slicer_curr_z = z

    line_slider_x = ui.LineSlider2D(min_value=0,
                                    max_value=shape[0] - 1,
                                    initial_value=shape[0] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    _color_slider(line_slider_x)

    def change_slice_x(slider):
        x = int(np.round(slider.value))
        HORIMEM.slicer_curr_actor_x.display_extent(x, x, 0, shape[1] - 1, 0,
                                                   shape[2] - 1)
        HORIMEM.slicer_curr_x = x
        HORIMEM.window_timer_cnt += 100

    line_slider_y = ui.LineSlider2D(min_value=0,
                                    max_value=shape[1] - 1,
                                    initial_value=shape[1] / 2,
                                    text_template="{value:.0f}",
                                    length=140)

    _color_slider(line_slider_y)

    def change_slice_y(slider):
        y = int(np.round(slider.value))

        HORIMEM.slicer_curr_actor_y.display_extent(0, shape[0] - 1, y, y, 0,
                                                   shape[2] - 1)
        HORIMEM.slicer_curr_y = y

    double_slider = ui.LineDoubleSlider2D(length=140,
                                          initial_values=value_range,
                                          min_value=tmp.min(),
                                          max_value=tmp.max(),
                                          shape='square')

    _color_dslider(double_slider)

    def apply_colormap(r1, r2):
        if HORIMEM.slicer_rgb:
            return

        if HORIMEM.slicer_colormap == 'disting':
            # use distinguishable colors
            rgb = colormap.distinguishable_colormap(nb_colors=256)
            rgb = np.asarray(rgb)
        else:
            # use matplotlib colormaps
            rgb = colormap.create_colormap(np.linspace(r1, r2, 256),
                                           name=HORIMEM.slicer_colormap,
                                           auto=True)
        N = rgb.shape[0]

        lut = colormap.vtk.vtkLookupTable()
        lut.SetNumberOfTableValues(N)
        lut.SetRange(r1, r2)
        for i in range(N):
            r, g, b = rgb[i]
            lut.SetTableValue(i, r, g, b)
        lut.SetRampToLinear()
        lut.Build()

        HORIMEM.slicer_curr_actor_z.output.SetLookupTable(lut)
        HORIMEM.slicer_curr_actor_z.output.Update()

    def on_change_ds(slider):

        values = slider._values
        r1, r2 = values
        apply_colormap(r1, r2)

    double_slider.on_change = on_change_ds

    opacity_slider = ui.LineSlider2D(min_value=0.0,
                                     max_value=1.0,
                                     initial_value=slicer_opacity,
                                     length=140,
                                     text_template="{ratio:.0%}")

    _color_slider(opacity_slider)

    def change_opacity(slider):
        slicer_opacity = slider.value
        HORIMEM.slicer_curr_actor_x.opacity(slicer_opacity)
        HORIMEM.slicer_curr_actor_y.opacity(slicer_opacity)
        HORIMEM.slicer_curr_actor_z.opacity(slicer_opacity)

    volume_slider = ui.LineSlider2D(min_value=0,
                                    max_value=data.shape[-1] - 1,
                                    initial_value=0,
                                    length=140,
                                    text_template="{value:.0f}",
                                    shape='square')

    _color_slider(volume_slider)

    def change_volume(istyle, obj, slider):
        vol_idx = int(np.round(slider.value))
        HORIMEM.slicer_vol_idx = vol_idx

        renderer.rm(HORIMEM.slicer_curr_actor_x)
        renderer.rm(HORIMEM.slicer_curr_actor_y)
        renderer.rm(HORIMEM.slicer_curr_actor_z)

        tmp = data[..., vol_idx]
        image_actor_z = actor.slicer(tmp,
                                     affine=affine,
                                     value_range=value_range,
                                     interpolation='nearest',
                                     picking_tol=0.025)

        tmp_new = image_actor_z.resliced_array()
        HORIMEM.slicer_vol = tmp_new

        z = HORIMEM.slicer_curr_z
        image_actor_z.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z)

        HORIMEM.slicer_curr_actor_z = image_actor_z
        HORIMEM.slicer_curr_actor_x = image_actor_z.copy()

        if pam is not None:
            HORIMEM.slicer_peaks_actor_z = peaks_actor_z

        x = HORIMEM.slicer_curr_x
        HORIMEM.slicer_curr_actor_x.display_extent(x, x, 0, shape[1] - 1, 0,
                                                   shape[2] - 1)

        HORIMEM.slicer_curr_actor_y = image_actor_z.copy()
        y = HORIMEM.slicer_curr_y
        HORIMEM.slicer_curr_actor_y.display_extent(0, shape[0] - 1, y, y, 0,
                                                   shape[2] - 1)

        HORIMEM.slicer_curr_actor_z.AddObserver('LeftButtonPressEvent',
                                                left_click_picker_callback,
                                                1.0)
        HORIMEM.slicer_curr_actor_x.AddObserver('LeftButtonPressEvent',
                                                left_click_picker_callback,
                                                1.0)
        HORIMEM.slicer_curr_actor_y.AddObserver('LeftButtonPressEvent',
                                                left_click_picker_callback,
                                                1.0)
        renderer.add(HORIMEM.slicer_curr_actor_z)
        renderer.add(HORIMEM.slicer_curr_actor_x)
        renderer.add(HORIMEM.slicer_curr_actor_y)

        if pam is not None:
            renderer.add(HORIMEM.slicer_peaks_actor_z)

        r1, r2 = double_slider._values
        apply_colormap(r1, r2)

        istyle.force_render()

    def left_click_picker_callback(obj, ev):
        ''' Get the value of the clicked voxel and show it in the panel.'''

        event_pos = iren.GetEventPosition()

        obj.picker.Pick(event_pos[0], event_pos[1], 0, renderer)

        i, j, k = obj.picker.GetPointIJK()
        res = HORIMEM.slicer_vol[i, j, k]

        # generate figure
        cc_vox = data[i, j, k]
        print(cc_vox)
        plt.plot([cc_vox])
        plt.savefig('test.png')
        icon_fnames = [('square', 'test.png'), ('square1', 'test.png')]
        # connect to button
        button = ui.Button2D(icon_fnames, size=(20, 30))
        panel.add_element(button, coords=(0., 0.))
        # make button visible

        try:
            message = '%.3f' % res
        except TypeError:
            message = '%.3f %.3f %.3f' % (res[0], res[1], res[2])
        picker_label.message = '({}, {}, {})'.format(str(i), str(j), str(k)) \
            + ' ' + message

    HORIMEM.slicer_vol_idx = 0
    HORIMEM.slicer_vol = tmp_new
    HORIMEM.slicer_curr_actor_x = image_actor_x
    HORIMEM.slicer_curr_actor_y = image_actor_y
    HORIMEM.slicer_curr_actor_z = image_actor_z

    if pam is not None:
        # change_volume.peaks_actor_z = peaks_actor_z
        HORIMEM.slicer_peaks_actor_z = peaks_actor_z

    HORIMEM.slicer_curr_actor_x.AddObserver('LeftButtonPressEvent',
                                            left_click_picker_callback, 1.0)
    HORIMEM.slicer_curr_actor_y.AddObserver('LeftButtonPressEvent',
                                            left_click_picker_callback, 1.0)
    HORIMEM.slicer_curr_actor_z.AddObserver('LeftButtonPressEvent',
                                            left_click_picker_callback, 1.0)

    if pam is not None:
        HORIMEM.slicer_peaks_actor_z.AddObserver('LeftButtonPressEvent',
                                                 left_click_picker_callback,
                                                 1.0)

    HORIMEM.slicer_curr_x = int(np.round(shape[0] / 2))
    HORIMEM.slicer_curr_y = int(np.round(shape[1] / 2))
    HORIMEM.slicer_curr_z = int(np.round(shape[2] / 2))

    line_slider_x.on_change = change_slice_x
    line_slider_y.on_change = change_slice_y
    line_slider_z.on_change = change_slice_z

    double_slider.on_change = on_change_ds

    opacity_slider.on_change = change_opacity

    volume_slider.handle_events(volume_slider.handle.actor)
    volume_slider.on_left_mouse_button_released = change_volume

    # volume_slider.on_right_mouse_button_released = change_volume2

    line_slider_label_x = build_label(text="X Slice")
    line_slider_label_x.visibility = True
    x_counter = itertools.count()

    def label_callback_x(obj, event):
        line_slider_label_x.visibility = not line_slider_label_x.visibility
        line_slider_x.set_visibility(line_slider_label_x.visibility)
        cnt = next(x_counter)
        if line_slider_label_x.visibility and cnt > 0:
            renderer.add(HORIMEM.slicer_curr_actor_x)
        else:
            renderer.rm(HORIMEM.slicer_curr_actor_x)
        iren.Render()

    line_slider_label_x.actor.AddObserver('LeftButtonPressEvent',
                                          label_callback_x, 1.0)

    line_slider_label_y = build_label(text="Y Slice")
    line_slider_label_y.visibility = True
    y_counter = itertools.count()

    def label_callback_y(obj, event):
        line_slider_label_y.visibility = not line_slider_label_y.visibility
        line_slider_y.set_visibility(line_slider_label_y.visibility)
        cnt = next(y_counter)
        if line_slider_label_y.visibility and cnt > 0:
            renderer.add(HORIMEM.slicer_curr_actor_y)
        else:
            renderer.rm(HORIMEM.slicer_curr_actor_y)
        iren.Render()

    line_slider_label_y.actor.AddObserver('LeftButtonPressEvent',
                                          label_callback_y, 1.0)

    line_slider_label_z = build_label(text="Z Slice")
    line_slider_label_z.visibility = True
    z_counter = itertools.count()

    def label_callback_z(obj, event):
        line_slider_label_z.visibility = not line_slider_label_z.visibility
        line_slider_z.set_visibility(line_slider_label_z.visibility)
        cnt = next(z_counter)
        if line_slider_label_z.visibility and cnt > 0:
            renderer.add(HORIMEM.slicer_curr_actor_z)
        else:
            renderer.rm(HORIMEM.slicer_curr_actor_z)

        iren.Render()

    line_slider_label_z.actor.AddObserver('LeftButtonPressEvent',
                                          label_callback_z, 1.0)

    opacity_slider_label = build_label(text="Opacity")
    volume_slider_label = build_label(text="Volume")
    picker_label = build_label(text='')
    double_slider_label = build_label(text='Colormap')

    def label_colormap_callback(obj, event):

        if HORIMEM.slicer_colormap_cnt == len(HORIMEM.slicer_colormaps) - 1:
            HORIMEM.slicer_colormap_cnt = 0
        else:
            HORIMEM.slicer_colormap_cnt += 1

        cnt = HORIMEM.slicer_colormap_cnt
        HORIMEM.slicer_colormap = HORIMEM.slicer_colormaps[cnt]
        double_slider_label.message = HORIMEM.slicer_colormap
        values = double_slider._values
        r1, r2 = values
        apply_colormap(r1, r2)
        iren.Render()

    double_slider_label.actor.AddObserver('LeftButtonPressEvent',
                                          label_colormap_callback, 1.0)

    if data.ndim == 4:
        panel_size = (400, 400 + 100)
    if data.ndim == 3:
        panel_size = (400, 300 + 100)

    panel = ui.Panel2D(size=panel_size,
                       position=(850, 110),
                       color=(1, 1, 1),
                       opacity=0.1,
                       align="right")

    ys = np.linspace(0, 1, 10)

    panel.add_element(line_slider_z, coords=(0.4, ys[1]))
    panel.add_element(line_slider_y, coords=(0.4, ys[2]))
    panel.add_element(line_slider_x, coords=(0.4, ys[3]))
    panel.add_element(opacity_slider, coords=(0.4, ys[4]))
    panel.add_element(double_slider, coords=(0.4, (ys[7] + ys[8]) / 2.))

    if data.ndim == 4:
        if data.shape[-1] > 3:
            panel.add_element(volume_slider, coords=(0.4, ys[6]))

    panel.add_element(line_slider_label_z, coords=(0.1, ys[1]))
    panel.add_element(line_slider_label_y, coords=(0.1, ys[2]))
    panel.add_element(line_slider_label_x, coords=(0.1, ys[3]))
    panel.add_element(opacity_slider_label, coords=(0.1, ys[4]))
    panel.add_element(double_slider_label, coords=(0.1, (ys[7] + ys[8]) / 2.))

    if data.ndim == 4:
        if data.shape[-1] > 3:
            panel.add_element(volume_slider_label, coords=(0.1, ys[6]))

    panel.add_element(picker_label, coords=(0.2, ys[5]))

    renderer.add(panel)

    # initialize colormap
    r1, r2 = value_range
    apply_colormap(r1, r2)

    return panel
def show_results(streamlines, vol, affine, world_coords=True, opacity=0.6):

    from dipy.viz import actor, window, widget
    import numpy as np
    shape = vol.shape

    if not world_coords:
        from dipy.tracking.streamline import transform_streamlines
        streamlines = transform_streamlines(streamlines, np.linalg.inv(affine))

    ren = window.Renderer()
    if streamlines is not None:
        stream_actor = actor.line(streamlines)

    if not world_coords:
        image_actor = actor.slicer(vol, affine=np.eye(4))
    else:
        image_actor = actor.slicer(vol, affine)

    slicer_opacity = opacity #.6
    image_actor.opacity(slicer_opacity)

    if streamlines is not None:
        ren.add(stream_actor)
    ren.add(image_actor)

    show_m = window.ShowManager(ren, size=(1200, 900))
    show_m.initialize()

    def change_slice(obj, event):
        z = int(np.round(obj.get_value()))
        image_actor.display_extent(0, shape[0] - 1,
                                   0, shape[1] - 1, z, z)

    slider = widget.slider(show_m.iren, show_m.ren,
                           callback=change_slice,
                           min_value=0,
                           max_value=shape[2] - 1,
                           value=shape[2] / 2,
                           label="Move slice",
                           right_normalized_pos=(.98, 0.6),
                           size=(120, 0), label_format="%0.lf",
                           color=(1., 1., 1.),
                           selected_color=(0.86, 0.33, 1.))

    global size
    size = ren.GetSize()

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

            slider.place(ren)
            size = obj.GetSize()

    show_m.initialize()

    show_m.add_window_callback(win_callback)
    show_m.render()
    show_m.start()

    # ren.zoom(1.5)
    # ren.reset_clipping_range()

    # window.record(ren, out_path='bundles_and_a_slice.png', size=(1200, 900),
    #               reset_camera=False)

    del show_m
Пример #46
0
def show_mosaic(data):

    renderer = window.Renderer()
    renderer.background((0.5, 0.5, 0.5))

    slice_actor = actor.slicer(data)

    show_m = window.ShowManager(renderer, size=(1200, 900))
    show_m.initialize()

    label_position = ui.TextBlock2D(text='Position:')
    label_value = ui.TextBlock2D(text='Value:')

    result_position = ui.TextBlock2D(text='')
    result_value = ui.TextBlock2D(text='')

    panel_picking = ui.Panel2D(center=(200, 120),
                               size=(250, 125),
                               color=(0, 0, 0),
                               opacity=0.75,
                               align="left")

    panel_picking.add_element(label_position, 'relative', (0.1, 0.55))
    panel_picking.add_element(label_value, 'relative', (0.1, 0.25))

    panel_picking.add_element(result_position, 'relative', (0.45, 0.55))
    panel_picking.add_element(result_value, 'relative', (0.45, 0.25))

    show_m.ren.add(panel_picking)
    """
    Add a left-click callback to the slicer. Also disable interpolation so you can
    see what you are picking.
    """

    renderer.clear()
    renderer.projection('parallel')

    result_position.message = ''
    result_value.message = ''

    show_m_mosaic = window.ShowManager(renderer, size=(1200, 900))
    show_m_mosaic.initialize()

    def left_click_callback_mosaic(obj, ev):
        """Get the value of the clicked voxel and show it in the panel."""
        event_pos = show_m_mosaic.iren.GetEventPosition()

        obj.picker.Pick(event_pos[0], event_pos[1], 0, show_m_mosaic.ren)

        i, j, k = obj.picker.GetPointIJK()
        result_position.message = '({}, {}, {})'.format(str(i), str(j), str(k))
        result_value.message = '%.8f' % data[i, j, k]

    cnt = 0

    X, Y, Z = slice_actor.shape[:3]

    rows = 10
    cols = 15
    border = 10

    for j in range(rows):
        for i in range(cols):
            slice_mosaic = slice_actor.copy()
            slice_mosaic.display(None, None, cnt)
            slice_mosaic.SetPosition(
                (X + border) * i, 0.5 * cols * (Y + border) - (Y + border) * j,
                0)
            slice_mosaic.SetInterpolate(False)
            slice_mosaic.AddObserver('LeftButtonPressEvent',
                                     left_click_callback_mosaic, 1.0)
            renderer.add(slice_mosaic)
            cnt += 1
            if cnt > Z:
                break
        if cnt > Z:
            break

    renderer.reset_camera()
    renderer.zoom(1.6)

    show_m_mosaic.ren.add(panel_picking)
    show_m_mosaic.start()