Ejemplo n.º 1
0
def test_ui_line_double_slider_2d(interactive=False):
    line_double_slider_2d_test = ui.LineDoubleSlider2D(center=(300, 300),
                                                       shape="disk",
                                                       outer_radius=15,
                                                       min_value=-10,
                                                       max_value=10,
                                                       initial_values=(-10,
                                                                       10))
    npt.assert_equal(line_double_slider_2d_test.handles[0].size, (30, 30))
    npt.assert_equal(line_double_slider_2d_test.left_disk_value, -10)
    npt.assert_equal(line_double_slider_2d_test.right_disk_value, 10)

    if interactive:
        show_manager = window.ShowManager(size=(600, 600),
                                          title="DIPY Line Double Slider")
        show_manager.ren.add(line_double_slider_2d_test)
        show_manager.start()

    line_double_slider_2d_test = ui.LineDoubleSlider2D(center=(300, 300),
                                                       shape="square",
                                                       handle_side=5,
                                                       initial_values=(50, 40))
    npt.assert_equal(line_double_slider_2d_test.handles[0].size, (5, 5))
    npt.assert_equal(line_double_slider_2d_test._values[0], 39)
    npt.assert_equal(line_double_slider_2d_test.right_disk_value, 40)

    if interactive:
        show_manager = window.ShowManager(size=(600, 600),
                                          title="DIPY Line Double Slider")
        show_manager.ren.add(line_double_slider_2d_test)
        show_manager.start()
Ejemplo n.º 2
0
def test_ui_textbox(recording=False):
    filename = "test_ui_textbox"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")

    # TextBox
    textbox_test = ui.TextBox2D(height=3, width=10, text="Text")

    another_textbox_test = ui.TextBox2D(height=3, width=10, text="Enter Text")
    another_textbox_test.set_message("Enter Text")
    npt.assert_raises(NotImplementedError, setattr, another_textbox_test,
                      "center", (10, 100))

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(textbox_test)

    current_size = (600, 600)
    show_manager = window.ShowManager(size=current_size, title="DIPY TextBox")

    show_manager.ren.add(textbox_test)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)
Ejemplo n.º 3
0
def test_text_widget():

    interactive = False

    renderer = window.Renderer()
    axes = actor.axes()
    window.add(renderer, axes)
    renderer.ResetCamera()

    show_manager = window.ShowManager(renderer, size=(900, 900))

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

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

    def button_callback(obj, event):
        print('Button Pressed')

    button = widget.button(show_manager.iren, show_manager.ren,
                           button_callback, button_png, (.8, 1.2), (100, 100))

    global rulez
    rulez = True

    def text_callback(obj, event):

        global rulez
        print('Text selected')
        if rulez:
            obj.GetTextActor().SetInput("Diffusion Imaging Rulez!!")
            rulez = False
        else:
            obj.GetTextActor().SetInput("Diffusion Imaging in Python")
            rulez = True
        show_manager.render()

    text = widget.text(show_manager.iren,
                       show_manager.ren,
                       text_callback,
                       message="Diffusion Imaging in Python",
                       left_down_pos=(0., 0.),
                       right_top_pos=(0.4, 0.05),
                       opacity=1.,
                       border=False)

    if not interactive:
        button.Off()
        text.Off()
        pass

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

    arr = window.snapshot(renderer, size=(900, 900))
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 3)
Ejemplo n.º 4
0
def test_ui_line_slider_2d(recording=False):
    filename = "test_ui_line_slider_2d"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")

    line_slider_2d_test = ui.LineSlider2D(initial_value=-2,
                                          min_value=-5,
                                          max_value=5)
    line_slider_2d_test.center = (300, 300)

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(line_slider_2d_test)

    current_size = (600, 600)
    show_manager = window.ShowManager(size=current_size,
                                      title="DIPY Line Slider")

    show_manager.ren.add(line_slider_2d_test)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)
Ejemplo n.º 5
0
def test_rectangle_2d():
    window_size = (700, 700)
    show_manager = window.ShowManager(size=window_size)

    rect = ui.Rectangle2D(size=(100, 50))
    rect.set_position((50, 80))
    npt.assert_equal(rect.position, (50, 80))

    rect.color = (1, 0.5, 0)
    npt.assert_equal(rect.color, (1, 0.5, 0))

    rect.opacity = 0.5
    npt.assert_equal(rect.opacity, 0.5)

    # Check the rectangle is drawn at right place.
    show_manager.ren.add(rect)
    # Uncomment this to start the visualisation
    # show_manager.start()

    colors = [rect.color]
    arr = window.snapshot(show_manager.ren, size=window_size, offscreen=True)
    report = window.analyze_snapshot(arr, colors=colors)
    assert report.objects == 1
    assert report.colors_found

    # Test visibility off.
    rect.set_visibility(False)
    arr = window.snapshot(show_manager.ren, size=window_size, offscreen=True)
    report = window.analyze_snapshot(arr)
    assert report.objects == 0
Ejemplo n.º 6
0
def test_ui_ring_slider_2d(recording=False):
    filename = "test_ui_ring_slider_2d"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")

    ring_slider_2d_test = ui.RingSlider2D()
    ring_slider_2d_test.center = (300, 300)
    ring_slider_2d_test.value = 90

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(ring_slider_2d_test)

    current_size = (600, 600)
    show_manager = window.ShowManager(size=current_size,
                                      title="DIPY Ring Slider")

    show_manager.ren.add(ring_slider_2d_test)

    if recording:
        # Record the following events
        # 1. Left Click on the handle and hold it
        # 2. Move to the left the handle and make 1.5 tour
        # 3. Release the handle
        # 4. Left Click on the handle and hold it
        # 5. Move to the right the handle and make 1 tour
        # 6. Release the handle
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)
Ejemplo n.º 7
0
def test_ui_disk_slider_2d(recording=False):
    filename = "test_ui_disk_slider_2d"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")

    disk_slider_2d_test = ui.DiskSlider2D()
    disk_slider_2d_test.set_center((300, 300))
    disk_slider_2d_test.value = 90

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(disk_slider_2d_test)

    current_size = (600, 600)
    show_manager = window.ShowManager(size=current_size,
                                      title="DIPY Disk Slider")

    show_manager.ren.add(disk_slider_2d_test)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)
Ejemplo n.º 8
0
def test_ui_disk_2d():
    window_size = (700, 700)
    show_manager = window.ShowManager(size=window_size)

    disk = ui.Disk2D(outer_radius=20, inner_radius=5)
    disk.position = (50, 80)
    npt.assert_equal(disk.position, (50, 80))

    disk.color = (1, 0.5, 0)
    npt.assert_equal(disk.color, (1, 0.5, 0))

    disk.opacity = 0.5
    npt.assert_equal(disk.opacity, 0.5)

    # Check the rectangle is drawn at right place.
    show_manager.ren.add(disk)
    # Uncomment this to start the visualisation
    # show_manager.start()

    colors = [disk.color]
    arr = window.snapshot(show_manager.ren, size=window_size, offscreen=True)
    report = window.analyze_snapshot(arr, colors=colors)
    assert report.objects == 1
    assert report.colors_found

    # Test visibility off.
    disk.set_visibility(False)
    arr = window.snapshot(show_manager.ren, size=window_size, offscreen=True)
    report = window.analyze_snapshot(arr)
    assert report.objects == 0
Ejemplo n.º 9
0
def test_ui_range_slider(interactive=False):
    range_slider_test = ui.RangeSlider(shape="square")

    if interactive:
        show_manager = window.ShowManager(size=(600, 600),
                                          title="DIPY Line Double Slider")
        show_manager.ren.add(range_slider_test)
        show_manager.start()
Ejemplo n.º 10
0
def test_ui_option(interactive=False):
    option_test = ui.Option(label="option 1", position=(10, 10))

    npt.assert_equal(option_test.checked, False)

    if interactive:
        showm = window.ShowManager(size=(600, 600))
        showm.ren.add(option_test)
        showm.start()
Ejemplo n.º 11
0
def test_timer():
    """ Testing add a timer and exit window and app from inside timer.
    """

    xyzr = np.array([[0, 0, 0, 10], [100, 0, 0, 50], [300, 0, 0, 100]])
    xyzr2 = np.array([[0, 200, 0, 30], [100, 200, 0, 50], [300, 200, 0, 100]])
    colors = np.array([[1, 0, 0, 0.3], [0, 1, 0, 0.4], [0, 0, 1., 0.45]])

    renderer = window.Renderer()
    global sphere_actor, tb, cnt
    sphere_actor = actor.sphere(centers=xyzr[:, :3], colors=colors[:],
                                radii=xyzr[:, 3])

    sphere = get_sphere('repulsion724')

    sphere_actor2 = actor.sphere(centers=xyzr2[:, :3], colors=colors[:],
                                 radii=xyzr2[:, 3], vertices=sphere.vertices,
                                 faces=sphere.faces.astype('i8'))

    renderer.add(sphere_actor)
    renderer.add(sphere_actor2)

    tb = ui.TextBlock2D()

    cnt = 0
    global showm
    showm = window.ShowManager(renderer,
                               size=(1024, 768), reset_camera=False,
                               order_transparent=True)

    showm.initialize()

    def timer_callback(obj, event):
        global cnt, sphere_actor, showm, tb

        cnt += 1
        tb.message = "Let's count to 10 and exit :" + str(cnt)
        showm.render()
        if cnt > 9:
            showm.exit()

    renderer.add(tb)

    # Run every 200 milliseconds
    showm.add_timer_callback(True, 200, timer_callback)
    showm.start()

    arr = window.snapshot(renderer)

    npt.assert_(np.sum(arr) > 0)
Ejemplo n.º 12
0
def test_ui_file_select_menu_2d(recording=False):
    filename = "test_ui_file_select_menu_2d"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")
    with InTemporaryDirectory() as tmpdir:
        for i in range(10):
            _ = open("test" + str(i) + ".txt", 'wt').write('some text')

        file_select_menu = ui.FileSelectMenu2D(size=(500, 500),
                                               position=(300, 300),
                                               font_size=16,
                                               extensions=["txt"],
                                               directory_path=os.getcwd(),
                                               parent=None)
        file_select_menu.set_center((300, 300))

        npt.assert_equal(file_select_menu.text_item_list[1].file_name[:4],
                         "test")
        npt.assert_equal(file_select_menu.text_item_list[5].file_name[:4],
                         "test")

        event_counter = EventCounter()
        for event in event_counter.events_counts:
            file_select_menu.add_callback(file_select_menu.buttons["up"].actor,
                                          event, event_counter.count)
            file_select_menu.add_callback(
                file_select_menu.buttons["down"].actor, event,
                event_counter.count)
            file_select_menu.menu.add_callback(
                file_select_menu.menu.panel.actor, event, event_counter.count)
            for text_ui in file_select_menu.text_item_list:
                file_select_menu.add_callback(
                    text_ui.text_actor.get_actors()[0], event,
                    event_counter.count)

        current_size = (600, 600)
        show_manager = window.ShowManager(size=current_size,
                                          title="DIPY File Select Menu")
        show_manager.ren.add(file_select_menu)

        if recording:
            show_manager.record_events_to_file(recording_filename)
            print(list(event_counter.events_counts.items()))
            event_counter.save(expected_events_counts_filename)

        else:
            show_manager.play_events_from_file(recording_filename)
            expected = EventCounter.load(expected_events_counts_filename)
            event_counter.check_counts(expected)
Ejemplo n.º 13
0
def test_ui_image_container_2d(interactive=False):
    fetch_viz_icons()
    image_test = ui.ImageContainer2D(img_path=read_viz_icons(
        fname='home3.png'))

    image_test.center = (300, 300)
    npt.assert_equal(image_test.size, (100, 100))

    image_test.scale((2, 2))
    npt.assert_equal(image_test.size, (200, 200))

    current_size = (600, 600)
    show_manager = window.ShowManager(size=current_size, title="DIPY Button")
    show_manager.ren.add(image_test)
    if interactive:
        show_manager.start()
Ejemplo n.º 14
0
    def take_snapshot(bundles, interact_with=False):
        if interact_with:
            showm = window.ShowManager(ren,
                                       size=resolution,
                                       reset_camera=False)
            showm.start()
            ren.camera_info()

        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
Ejemplo n.º 15
0
    def display(self):
        ren = window.Renderer()

        ren.add(self.volume_image)
        ren.add(self.fod)

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

        interactive = True

        ren.zoom(1.5)
        ren.reset_clipping_range()

        if interactive:

            show_m.render()
            show_m.start()

        path = self.patient_num + ".png"

        window.record(ren, out_path=path, size=(1200, 900), reset_camera=False)
        del show_m
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
Ejemplo n.º 17
0
def test_custom_interactor_style_events(recording=False):
    print("Using VTK {}".format(vtk.vtkVersion.GetVTKVersion()))
    filename = "test_custom_interactor_style_events.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)
    renderer = window.Renderer()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        for event, count in expected:
            npt.assert_equal(states[event], count, err_msg=msg.format(event))
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
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)
ren.add(image_actor_z)
ren.add(image_actor_x)
ren.add(image_actor_y)
show_m = window.ShowManager(ren, size=(1200, 900))
# A Sphere widget
sphereWidget = vtk.vtkSphereWidget()
sphereWidget.SetRadius(5)
sphereWidget.SetInteractor(show_m.iren)
sphereWidget.SetRepresentationToSurface()
sphereWidget.On()
# Connect the event to a function
sphereWidget.AddObserver("InteractionEvent", sphereCallback)
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}",
def plotAllSubjectLandmarks(subjlist,
                            fixedLandmarkDict,
                            curveLandmarkDict,
                            treatfixedascurve=False,
                            sphereradius=1,
                            group=[]):
    #show landmarks for all subjects, uses different color for each subject
    import vtk
    from dipy.viz import window
    import numpy as np

    def markcurve(x, y, z, landnum, curve, color):
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(sphereradius)
        res = 20
        sphere.SetThetaResolution(res)
        sphere.SetPhiResolution(res)
        sphere.SetCenter(x, y, z)
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphere.GetOutputPort())

        marker = vtk.vtkActor()
        marker.SetMapper(mapper)
        renderer.AddActor(marker)
        marker.GetProperty().SetColor(color)

        #add line
        if landnum > 0:
            lineSource = vtk.vtkLineSource()
            lineSource.SetPoint1(curve[landnum - 1])
            lineSource.SetPoint2([x, y, z])
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(lineSource.GetOutputPort())
            lineActor = vtk.vtkActor()
            lineActor.SetMapper(mapper)
            lineActor.GetProperty().SetLineWidth(4)
            lineActor.GetProperty().SetColor(color)
            renderer.AddActor(lineActor)

        show_m.iren.Render()

    def markfixed(x, y, z, color):
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(sphereradius)
        res = 20
        sphere.SetThetaResolution(res)
        sphere.SetPhiResolution(res)
        sphere.SetCenter(x, y, z)
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphere.GetOutputPort())

        marker = vtk.vtkActor()
        marker.SetMapper(mapper)
        renderer.AddActor(marker)
        marker.GetProperty().SetColor(color)

        show_m.iren.Render()

    renderer = window.Renderer()
    show_m = window.ShowManager(renderer, size=(800, 800))

    colorlist = []
    if group:
        ngroups = len(np.unique(group))
        grpcolors = []
        for i in range(ngroups):
            grpcolors.append(list(np.random.choice(range(256), size=3) / 256.))
        for i in range(len(group)):
            colorlist.append(grpcolors[list(np.unique(group)).index(group[i])])
    else:
        for i in range(len(subjlist)):
            colorlist.append(list(np.random.choice(range(256), size=3) / 256.))

    for subj in range(len(subjlist)):

        color = colorlist[subj]

        if type(fixedLandmarkDict) is dict:
            if treatfixedascurve:
                for lnum in range(len(fixedLandmarkDict[subjlist[subj]])):
                    lm = fixedLandmarkDict[subjlist[subj]][lnum]
                    markcurve(lm[0], lm[1], lm[2], lnum,
                              fixedLandmarkDict[subjlist[subj]], color)
            else:
                for lnum in range(len(fixedLandmarkDict[subjlist[subj]])):
                    lm = fixedLandmarkDict[subjlist[subj]][lnum]
                    markfixed(lm[0], lm[1], lm[2], color)
        if type(curveLandmarkDict) is dict:
            for c in curveLandmarkDict[subjlist[subj]]:
                for lnum in range(len(c)):
                    lm = c[lnum]
                    markcurve(lm[0], lm[1], lm[2], lnum, c, color)

    show_m.initialize()
    show_m.render()
    show_m.start()
Ejemplo n.º 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)
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
def test_ui_listbox_2d(recording=False):
    filename = "test_ui_listbox_2d"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")

    # Values that will be displayed by the listbox.
    values = list(range(1, 42 + 1))
    listbox = ui.ListBox2D(values=values,
                           size=(500, 500),
                           multiselection=True,
                           reverse_scrolling=False)
    listbox.center = (300, 300)

    # We will collect the sequence of values that have been selected.
    selected_values = []

    def _on_change():
        selected_values.append(list(listbox.selected))

    # Set up a callback when selection changes.
    listbox.on_change = _on_change

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(listbox)

    # Create a show manager and record/play events.
    show_manager = window.ShowManager(size=(600, 600), title="DIPY ListBox")
    show_manager.ren.add(listbox)

    if recording:
        # Record the following events:
        #  1. Click on 1
        #  2. Ctrl + click on 2,
        #  3. Ctrl + click on 2.
        #  4. Click on down arrow (4 times).
        #  5. Click on 21.
        #  6. Click on up arrow (5 times).
        #  7. Click on 1
        #  8. Use mouse wheel to scroll down.
        #  9. Shift + click on 42.
        # 10. Use mouse wheel to scroll back up.
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)

    # Check if the right values were selected.
    expected = [[1], [1, 2], [1], [21], [1], values]
    assert len(selected_values) == len(expected)
    assert_arrays_equal(selected_values, expected)

    # Test without multiselection enabled.
    listbox.multiselection = False
    del selected_values[:]  # Clear the list.
    show_manager.play_events_from_file(recording_filename)

    # Check if the right values were selected.
    expected = [[1], [2], [2], [21], [1], [42]]
    assert len(selected_values) == len(expected)
    assert_arrays_equal(selected_values, expected)
Ejemplo n.º 24
0
"""
Image Container
======
"""

img = ui.ImageContainer2D(img_path=read_viz_icons(fname='home3.png'))
"""
Adding Elements to the ShowManager
==================================

Once all elements have been initialised, they have
to be added to the show manager in the following manner.
"""

current_size = (600, 600)
show_manager = window.ShowManager(size=current_size, title="DIPY UI Example")

show_manager.ren.add(cube_actor_1)
show_manager.ren.add(cube_actor_2)
show_manager.ren.add(panel)
show_manager.ren.add(text)
show_manager.ren.add(line_slider)
show_manager.ren.add(ring_slider)
show_manager.ren.add(listbox)
show_manager.ren.add(img)
show_manager.ren.reset_camera()
show_manager.ren.reset_clipping_range()
show_manager.ren.azimuth(30)

# Uncomment this to start the visualisation
# show_manager.start()

def change_axis_length(i_ren, obj, slider):
    # A function to change the semi-major axis length
    # using the slider callback
    global a, show_manager, sphere_actor
    a = slider.value
    print(a)
    show_manager.ren.rm(sphere_actor)
    sphere_actor = vertices_triangles(a, 1., 1.)
    show_manager.ren.add(sphere_actor)
    show_manager.render()


#Relevant callbacks
line_slider = ui.LineSlider2D(initial_value=1, min_value=0, max_value=1)

line_slider.add_callback(line_slider.slider_disk, "MouseMoveEvent",
                         change_axis_length)

line_slider.add_callback(line_slider.slider_line, "LeftButtonPressEvent",
                         change_axis_length)

global show_manager
# renderer and scene
show_manager = window.ShowManager(size=(600, 600), title="Ellipsoid")
show_manager.initialize()
show_manager.ren.add(sphere_actor)
show_manager.ren.add(line_slider)
show_manager.start()
Ejemplo n.º 26
0
import numpy as np
from dipy.viz import window, actor, ui
import itertools

xyz = 10 * np.random.rand(100, 3)
colors = np.random.rand(100, 4)
radii = np.random.rand(100) + 0.5

renderer = window.Renderer()

sphere_actor = actor.sphere(centers=xyz, colors=colors, radii=radii)

renderer.add(sphere_actor)

showm = window.ShowManager(renderer,
                           size=(900, 768),
                           reset_camera=False,
                           order_transparent=True)

showm.initialize()

tb = ui.TextBlock2D(bold=True)

# use itertools to avoid global variables
counter = itertools.count()


def timer_callback(obj, event):
    cnt = next(counter)
    tb.message = "Let's count up to 100 and exit :" + str(cnt)
    renderer.azimuth(0.05 * cnt)
    sphere_actor.GetProperty().SetOpacity(cnt / 100.)
Ejemplo n.º 27
0
def test_text_block_2d_justification():
    window_size = (700, 700)
    show_manager = window.ShowManager(size=window_size)

    # To help visualize the text positions.
    grid_size = (500, 500)
    bottom, middle, top = 50, 300, 550
    left, center, right = 50, 300, 550
    line_color = (1, 0, 0)

    grid_top = (center, top), (grid_size[0], 1)
    grid_bottom = (center, bottom), (grid_size[0], 1)
    grid_left = (left, middle), (1, grid_size[1])
    grid_right = (right, middle), (1, grid_size[1])
    grid_middle = (center, middle), (grid_size[0], 1)
    grid_center = (center, middle), (1, grid_size[1])
    grid_specs = [
        grid_top, grid_bottom, grid_left, grid_right, grid_middle, grid_center
    ]
    for spec in grid_specs:
        line = ui.Rectangle2D(size=spec[1], color=line_color)
        line.center = spec[0]
        show_manager.ren.add(line)

    font_size = 60
    bg_color = (1, 1, 1)
    texts = []
    texts += [
        ui.TextBlock2D("HH",
                       position=(left, top),
                       font_size=font_size,
                       color=(1, 0, 0),
                       bg_color=bg_color,
                       justification="left",
                       vertical_justification="top")
    ]
    texts += [
        ui.TextBlock2D("HH",
                       position=(center, top),
                       font_size=font_size,
                       color=(0, 1, 0),
                       bg_color=bg_color,
                       justification="center",
                       vertical_justification="top")
    ]
    texts += [
        ui.TextBlock2D("HH",
                       position=(right, top),
                       font_size=font_size,
                       color=(0, 0, 1),
                       bg_color=bg_color,
                       justification="right",
                       vertical_justification="top")
    ]

    texts += [
        ui.TextBlock2D("HH",
                       position=(left, middle),
                       font_size=font_size,
                       color=(1, 1, 0),
                       bg_color=bg_color,
                       justification="left",
                       vertical_justification="middle")
    ]
    texts += [
        ui.TextBlock2D("HH",
                       position=(center, middle),
                       font_size=font_size,
                       color=(0, 1, 1),
                       bg_color=bg_color,
                       justification="center",
                       vertical_justification="middle")
    ]
    texts += [
        ui.TextBlock2D("HH",
                       position=(right, middle),
                       font_size=font_size,
                       color=(1, 0, 1),
                       bg_color=bg_color,
                       justification="right",
                       vertical_justification="middle")
    ]

    texts += [
        ui.TextBlock2D("HH",
                       position=(left, bottom),
                       font_size=font_size,
                       color=(0.5, 0, 1),
                       bg_color=bg_color,
                       justification="left",
                       vertical_justification="bottom")
    ]
    texts += [
        ui.TextBlock2D("HH",
                       position=(center, bottom),
                       font_size=font_size,
                       color=(1, 0.5, 0),
                       bg_color=bg_color,
                       justification="center",
                       vertical_justification="bottom")
    ]
    texts += [
        ui.TextBlock2D("HH",
                       position=(right, bottom),
                       font_size=font_size,
                       color=(0, 1, 0.5),
                       bg_color=bg_color,
                       justification="right",
                       vertical_justification="bottom")
    ]

    show_manager.ren.add(*texts)

    # Uncomment this to start the visualisation
    # show_manager.start()

    arr = window.snapshot(show_manager.ren, size=window_size, offscreen=True)
    if vtk.vtkVersion.GetVTKVersion() == "6.0.0":
        expected = np.load(pjoin(DATA_DIR, "test_ui_text_block.npz"))
        npt.assert_array_almost_equal(arr, expected["arr_0"])
Ejemplo n.º 28
0
def test_button_and_slider_widgets():
    recording = False
    filename = "test_button_and_slider_widgets.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)
    renderer = window.Renderer()

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

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

    renderer.add(stream_actor)

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

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

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

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

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

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

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

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

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

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

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

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

    global size
    size = renderer.GetSize()

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

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

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

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors, 1)
Ejemplo n.º 29
0
def test_ui_button_panel(recording=False):
    filename = "test_ui_button_panel"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")

    # Rectangle
    rectangle_test = ui.Rectangle2D(size=(10, 10))
    another_rectangle_test = ui.Rectangle2D(size=(1, 1))

    # Button
    fetch_viz_icons()

    icon_files = []
    icon_files.append(('stop', read_viz_icons(fname='stop2.png')))
    icon_files.append(('play', read_viz_icons(fname='play3.png')))

    button_test = ui.Button2D(icon_fnames=icon_files)
    button_test.center = (20, 20)

    def make_invisible(i_ren, obj, button):
        # i_ren: CustomInteractorStyle
        # obj: vtkActor picked
        # button: Button2D
        button.set_visibility(False)
        i_ren.force_render()
        i_ren.event.abort()

    def modify_button_callback(i_ren, obj, button):
        # i_ren: CustomInteractorStyle
        # obj: vtkActor picked
        # button: Button2D
        button.next_icon()
        i_ren.force_render()

    button_test.on_right_mouse_button_pressed = make_invisible
    button_test.on_left_mouse_button_pressed = modify_button_callback

    button_test.scale((2, 2))
    button_color = button_test.color
    button_test.color = button_color

    # TextBlock
    text_block_test = ui.TextBlock2D()
    text_block_test.message = 'TextBlock'
    text_block_test.color = (0, 0, 0)

    # Panel
    panel = ui.Panel2D(size=(300, 150),
                       position=(290, 15),
                       color=(1, 1, 1),
                       align="right")
    panel.add_element(rectangle_test, (290, 135))
    panel.add_element(button_test, (0.1, 0.1))
    panel.add_element(text_block_test, (0.7, 0.7))
    npt.assert_raises(ValueError, panel.add_element, another_rectangle_test,
                      (10., 0.5))
    npt.assert_raises(ValueError, panel.add_element, another_rectangle_test,
                      (-0.5, 0.5))

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(button_test)
    event_counter.monitor(panel.background)

    current_size = (600, 600)
    show_manager = window.ShowManager(size=current_size, title="DIPY Button")

    show_manager.ren.add(panel)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)
Ejemplo n.º 30
0
def test_wrong_interactor_style():
    panel = ui.Panel2D(size=(300, 150))
    dummy_renderer = window.Renderer()
    dummy_show_manager = window.ShowManager(dummy_renderer,
                                            interactor_style='trackball')
    npt.assert_raises(TypeError, panel.add_to_renderer, dummy_renderer)