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)
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()
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()
def test_text_widget(): interactive = False renderer = window.Renderer() axes = fvtk.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)
cube_actor_1 = cube_maker((1, 0, 0), (50, 50, 50), center=(0, 0, 0)) cube_actor_2 = cube_maker((0, 1, 0), (10, 10, 10), center=(100, 0, 0)) """ Buttons ======= We first fetch the icons required for making the buttons. """ fetch_viz_icons() """ Add the icon filenames to a dict. """ icon_files = [('stop', read_viz_icons(fname='stop2.png')), ('play', read_viz_icons(fname='play3.png')), ('plus', read_viz_icons(fname='plus.png')), ('cross', read_viz_icons(fname='cross.png'))] """ Create a button through our API. """ button_example = ui.Button2D(icon_fnames=icon_files) """ We now add some click listeners. """ def left_mouse_button_click(i_ren, obj, button): print("Left Button Clicked")
cube_actor_1 = cube_maker((1, 0, 0), (50, 50, 50), center=(0, 0, 0)) cube_actor_2 = cube_maker((0, 1, 0), (10, 10, 10), center=(100, 0, 0)) """ Buttons ======= We first fetch the icons required for making the buttons. """ fetch_viz_icons() """ Add the icon filenames to a dict. """ icon_files = dict() icon_files['stop'] = read_viz_icons(fname='stop2.png') icon_files['play'] = read_viz_icons(fname='play3.png') icon_files['plus'] = read_viz_icons(fname='plus.png') icon_files['cross'] = read_viz_icons(fname='cross.png') """ Create a button through our API. """ button_example = ui.Button2D(icon_fnames=icon_files) """ We now add some click listeners. """ def left_mouse_button_click(i_ren, obj, button): print("Left Button Clicked")
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)) rectangle_test.get_actors() another_rectangle_test = ui.Rectangle2D(size=(1, 1)) # /Rectangle # Button fetch_viz_icons() icon_files = dict() icon_files['stop'] = read_viz_icons(fname='stop2.png') icon_files['play'] = read_viz_icons(fname='play3.png') button_test = ui.Button2D(icon_fnames=icon_files) button_test.set_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 # /Button # Panel panel = ui.Panel2D(center=(440, 90), size=(300, 150), color=(1, 1, 1), align="right") panel.add_element(rectangle_test, 'absolute', (580, 150)) panel.add_element(button_test, 'relative', (0.2, 0.2)) npt.assert_raises(ValueError, panel.add_element, another_rectangle_test, 'error_string', (1, 2)) # /Panel # Assign the counter callback to every possible event. event_counter = EventCounter() event_counter.monitor(button_test) event_counter.monitor(panel) 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)
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)
def button_minus_callback(obj, event): print('- pressed') opacity = stream_actor.GetProperty().GetOpacity() if opacity > 0: stream_actor.GetProperty().SetOpacity(opacity - 0.1) """ We need to download some icons to create a face for our buttons. We provide some simple icons in this tutorial. But you of course you can use any PNG icon you may want. """ fetch_viz_icons() 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 move_lines(obj, event): stream_actor.SetPosition((obj.get_value(), 0, 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)
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)
""" Image ===== Now let's display an image. First we need to fetch some icons that are included in DIPY. """ fetch_viz_icons() """ Now we can create an image container. """ img = ui.ImageContainer2D(img_path=read_viz_icons(fname='home3.png'), position=(450, 350)) """ Panel with buttons and text =========================== Let's create some buttons and text and put them in a panel. First we'll make the panel. """ panel = ui.Panel2D(size=(300, 150), color=(1, 1, 1), align="right") panel.center = (500, 400) """ Then we'll make two text labels and place them on the panel.
def test_button_and_slider_widgets(): interactive = False renderer = window.Renderer() # create some minimalistic streamlines lines = [np.array([[-1, 0, 0.], [1, 0, 0.]]), np.array([[-1, 1, 0.], [1, 1, 0.]])] colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]]) stream_actor = actor.streamtube(lines, colors) renderer.add(stream_actor) # the show manager allows to break the rendering process # in steps so that the widgets can be added properly show_manager = window.ShowManager(renderer, size=(800, 800)) if interactive: show_manager.initialize() show_manager.render() def button_callback(obj, event): print('Camera pressed') def button_plus_callback(obj, event): print('+ pressed') def button_minus_callback(obj, event): print('- pressed') fetch_viz_icons() button_png = read_viz_icons(fname='camera.png') button = widget.button(show_manager.iren, show_manager.ren, button_callback, button_png, (.98, 1.), (80, 50)) button_png_plus = read_viz_icons(fname='plus.png') button_plus = widget.button(show_manager.iren, show_manager.ren, button_plus_callback, button_png_plus, (.98, .9), (120, 50)) button_png_minus = read_viz_icons(fname='minus.png') button_minus = widget.button(show_manager.iren, show_manager.ren, button_minus_callback, button_png_minus, (.98, .9), (50, 50)) def print_status(obj, event): rep = obj.GetRepresentation() stream_actor.SetPosition((rep.GetValue(), 0, 0)) slider = widget.slider(show_manager.iren, show_manager.ren, callback=print_status, min_value=-1, max_value=1, value=0., label="X", right_normalized_pos=(.98, 0.6), size=(120, 0), label_format="%0.2lf") # This callback is used to update the buttons/sliders' position # so they can stay on the right side of the window when the window # is being resized. global size size = renderer.GetSize() def win_callback(obj, event): global size if size != obj.GetSize(): button.place(renderer) button_plus.place(renderer) button_minus.place(renderer) slider.place(renderer) size = obj.GetSize() if interactive: # show_manager.add_window_callback(win_callback) # you can also register any callback in a vtk way like this # show_manager.window.AddObserver(vtk.vtkCommand.ModifiedEvent, # win_callback) show_manager.render() show_manager.start() if not interactive: button.Off() slider.Off() # Uncomment below to test the slider and button with analyze # button.place(renderer) # slider.place(renderer) arr = window.snapshot(renderer, size=(800, 800)) report = window.analyze_snapshot(arr) npt.assert_equal(report.objects, 2) # imshow(report.labels, origin='lower') report = window.analyze_renderer(renderer) npt.assert_equal(report.actors, 1)
###################################### ###################################### """ Buttons ======= We first fetch the icons required for making the buttons. """ fetch_viz_icons() """ Add the icon filenames to a dict. """ icon_file = dict() icon_file['save'] = read_viz_icons(fname='floppy-disk.png') icon_file['savefinish'] = read_viz_icons(fname='checkmark.png') """ Create a button through our API. """ button_example = ui.Button2D(icon_fnames=icon_file) """ We now add some click listeners. """ # def left_mouse_button_click(i_ren, obj, button): # print("Left Button Clicked") # # # def left_mouse_button_drag(i_ren, obj, button):
center=(500, 300), color=(0, 1, 1)) """ Image ===== Now let's display an image. First we need to fetch some icons that are included in DIPY. """ fetch_viz_icons() """ Now we can create an image container. """ img = ui.ImageContainer2D(img_path=read_viz_icons(fname='home3.png'), position=(450, 350)) """ Panel with buttons and text =========================== Let's create some buttons and text and put them in a panel. First we'll make the panel. """ panel = ui.Panel2D(size=(300, 150), color=(1, 1, 1), align="right") panel.center = (500, 400) """ Then we'll make two text labels and place them on the panel. Note that we specifiy the position with integer numbers of pixels. """
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)
def test_ui(recording=False): print("Using VTK {}".format(vtk.vtkVersion.GetVTKVersion())) filename = "test_ui.log.gz" recording_filename = pjoin(DATA_DIR, filename) # Define some counter callback. states = defaultdict(lambda: 0) # Broken UI Element class BrokenUI(UI): def __init__(self): self.actor = vtk.vtkActor() super(BrokenUI, self).__init__() def add_callback(self, event_type, callback): """ Adds events to an actor. Parameters ---------- event_type : string event code callback : function callback function """ super(BrokenUI, self).add_callback(self.actor, event_type, callback) broken_ui = BrokenUI() npt.assert_raises(NotImplementedError, broken_ui.get_actors) npt.assert_raises(NotImplementedError, broken_ui.set_center, (1, 2)) # /Broken UI Element # Rectangle rectangle_test = ui.Rectangle2D(size=(10, 10)) rectangle_test.get_actors() another_rectangle_test = ui.Rectangle2D(size=(1, 1)) # /Rectangle # Button fetch_viz_icons() icon_files = dict() icon_files['stop'] = read_viz_icons(fname='stop2.png') icon_files['play'] = read_viz_icons(fname='play3.png') button_test = ui.Button2D(icon_fnames=icon_files) button_test.set_center((20, 20)) def counter(i_ren, obj, button): states[i_ren.event.name] += 1 # Assign the counter callback to every possible event. for event in ["CharEvent", "MouseMoveEvent", "KeyPressEvent", "KeyReleaseEvent", "LeftButtonPressEvent", "LeftButtonReleaseEvent", "RightButtonPressEvent", "RightButtonReleaseEvent", "MiddleButtonPressEvent", "MiddleButtonReleaseEvent"]: button_test.add_callback(event, counter) 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 # /Button # Panel panel = ui.Panel2D(center=(440, 90), size=(300, 150), color=(1, 1, 1), align="right") panel.add_element(rectangle_test, 'absolute', (580, 150)) panel.add_element(button_test, 'relative', (0.2, 0.2)) npt.assert_raises(ValueError, panel.add_element, another_rectangle_test, 'error_string', (1, 2)) # /Panel current_size = (600, 600) show_manager = window.ShowManager(size=current_size, title="DIPY UI Example") show_manager.ren.add(panel) 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', 0), ('KeyPressEvent', 0), ('KeyReleaseEvent', 0), ('MouseMoveEvent', 161), ('LeftButtonPressEvent', 12), ('RightButtonPressEvent', 3), ('MiddleButtonPressEvent', 0), ('LeftButtonReleaseEvent', 12), ('MouseWheelForwardEvent', 0), ('MouseWheelBackwardEvent', 0), ('MiddleButtonReleaseEvent', 0), ('RightButtonReleaseEvent', 3)] # 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)) # Dummy Show Manager dummy_renderer = window.Renderer() dummy_show_manager = window.ShowManager(dummy_renderer, size=(800, 800), reset_camera=False, interactor_style='trackball') npt.assert_raises(TypeError, button_test.add_to_renderer, dummy_renderer)
cube.SetCenter(*center) cube_mapper = vtk.vtkPolyDataMapper() cube_mapper.SetInputConnection(cube.GetOutputPort()) cube_actor = vtk.vtkActor() cube_actor.SetMapper(cube_mapper) if color is not None: cube_actor.GetProperty().SetColor(color) return cube_actor cube_actor_1 = cube_maker((1, 0, 0), (50, 50, 50), center=(0, 0, 0)) cube_actor_2 = cube_maker((0, 1, 0), (10, 10, 10), center=(100, 0, 0)) # /Cube Actors # Buttons icon_files = dict() icon_files['stop'] = read_viz_icons(fname='stop2.png') icon_files['play'] = read_viz_icons(fname='play3.png') icon_files['plus'] = read_viz_icons(fname='plus.png') icon_files['cross'] = read_viz_icons(fname='cross.png') button_example = ui.Button2D(icon_fnames=icon_files) def left_mouse_button_click(i_ren, obj, button): print("Left Button Clicked") def left_mouse_button_drag(i_ren, obj, button): print ("Left Button Dragged") button_example.on_left_mouse_button_drag = left_mouse_button_drag
def test_button_and_slider_widgets(): interactive = False renderer = window.Renderer() # create some minimalistic streamlines lines = [ np.array([[-1, 0, 0.], [1, 0, 0.]]), np.array([[-1, 1, 0.], [1, 1, 0.]]) ] colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]]) stream_actor = actor.streamtube(lines, colors) renderer.add(stream_actor) # the show manager allows to break the rendering process # in steps so that the widgets can be added properly show_manager = window.ShowManager(renderer, size=(800, 800)) if interactive: show_manager.initialize() show_manager.render() def button_callback(obj, event): print('Camera pressed') def button_plus_callback(obj, event): print('+ pressed') def button_minus_callback(obj, event): print('- pressed') fetch_viz_icons() button_png = read_viz_icons(fname='camera.png') button = widget.button(show_manager.iren, show_manager.ren, button_callback, button_png, (.98, 1.), (80, 50)) button_png_plus = read_viz_icons(fname='plus.png') button_plus = widget.button(show_manager.iren, show_manager.ren, button_plus_callback, button_png_plus, (.98, .9), (120, 50)) button_png_minus = read_viz_icons(fname='minus.png') button_minus = widget.button(show_manager.iren, show_manager.ren, button_minus_callback, button_png_minus, (.98, .9), (50, 50)) def print_status(obj, event): rep = obj.GetRepresentation() stream_actor.SetPosition((rep.GetValue(), 0, 0)) slider = widget.slider(show_manager.iren, show_manager.ren, callback=print_status, min_value=-1, max_value=1, value=0., label="X", right_normalized_pos=(.98, 0.6), size=(120, 0), label_format="%0.2lf") # This callback is used to update the buttons/sliders' position # so they can stay on the right side of the window when the window # is being resized. global size size = renderer.GetSize() def win_callback(obj, event): global size if size != obj.GetSize(): button.place(renderer) button_plus.place(renderer) button_minus.place(renderer) slider.place(renderer) size = obj.GetSize() if interactive: # show_manager.add_window_callback(win_callback) # you can also register any callback in a vtk way like this # show_manager.window.AddObserver(vtk.vtkCommand.ModifiedEvent, # win_callback) show_manager.render() show_manager.start() if not interactive: button.Off() slider.Off() # Uncomment below to test the slider and button with analyze # button.place(renderer) # slider.place(renderer) arr = window.snapshot(renderer, size=(800, 800)) report = window.analyze_snapshot(arr) npt.assert_equal(report.objects, 2) # imshow(report.labels, origin='lower') report = window.analyze_renderer(renderer) npt.assert_equal(report.actors, 1)
def _make_clustering_panel(self): # Panel size = (self.screen_size[0], self.screen_size[1] // 10) center = tuple(np.array(size) / 2.) # Lower left corner of the screen. panel = gui_2d.Panel2D(center=center, size=size, color=(1, 1, 1), align="left") # Nb. clusters label label = gui_2d.Text2D("# clusters") panel.add_element(label, (0.01, 0.2)) # "Apply" button def apply_button_callback(iren, obj, button): # iren: CustomInteractorStyle # obj: vtkActor picked # button: Button2D bundles = self.bundles[ self.selected_bundle].get_cluster_as_bundles() print("Preparing the new {} clusters...".format(len(bundles))) # Create new actors, one for each new bundle. # Sort bundle in decreasing size. for i, bundle in enumerate(bundles): bundle_name = "{}{}/".format(self.selected_bundle, i) self.add_bundle(bundle_name, bundle) self._add_bundle_right_click_callback(bundle, bundle_name) # Remove original bundle. self.remove_bundle(self.selected_bundle) self.select(None) # TODO: apply clustering if needed, close panel, add command to history, re-enable bundles context-menu. button.color = (0, 1, 0) # Restore color. print("Done.") iren.force_render() iren.event.abort() # Stop propagating the event. button = gui_2d.Button2D( icon_fnames={'apply': read_viz_icons(fname='checkmark_neg.png')}) button.color = (0, 1, 0) button.add_callback("LeftButtonPressEvent", animate_button_callback) button.add_callback("LeftButtonReleaseEvent", apply_button_callback) panel.add_element(button, (0.98, 0.2)) # "Hide" button def toggle_other_bundles_visibility(iren, *args): # iren: CustomInteractorStyle # obj: vtkActor picked # button: Button2D if self.last_bundles_visibility_state == "dimmed": self.last_bundles_visibility_state = "hidden" self._set_bundles_visibility( "hidden", exclude=[self.bundles[self.selected_bundle]]) elif self.last_bundles_visibility_state == "hidden": self.last_bundles_visibility_state = "dimmed" self._set_bundles_visibility( "dimmed", exclude=[self.bundles[self.selected_bundle]]) iren.force_render() iren.event.abort() # Stop propagating the event. self.show_dim_hide_button = gui_2d.Button2D( icon_fnames={ 'show_dim_hide': read_viz_icons(fname='infinite_neg.png') }) self.show_dim_hide_button.add_callback( "LeftButtonPressEvent", toggle_other_bundles_visibility) panel.add_element(self.show_dim_hide_button, (0.02, 0.88)) # Threshold slider def disk_press_callback(iren, obj, slider): # iren: CustomInteractorStyle # obj: vtkActor picked # slider: LineSlider2D # Only need to grab the focus. iren.event.abort() # Stop propagating the event. def disk_move_callback(iren, obj, slider): # iren: CustomInteractorStyle # obj: vtkActor picked # slider: LineSlider2D # Reset textbox textbox = slider.textbox.actor if textbox in iren.active_props: iren.remove_active_prop(textbox) position = iren.event.position slider.set_position(position) threshold = slider.value if self.last_threshold != threshold: nb_bundles = self.bundles[self.selected_bundle].preview( threshold) self.last_threshold = threshold label.set_message("{} clusters".format(nb_bundles)) iren.force_render() iren.event.abort() # Stop propagating the event. # Slider textbox def slider_textbox_select_callback(iren, obj, slider): # iren: CustomInteractorStyle # obj: vtkActor picked # slider: LineSlider2D iren.add_active_prop(slider.textbox.actor) slider.textbox.set_message("") slider.textbox.caret_pos = 0 slider.textbox.render_text(show_caret=True) iren.force_render() def slider_textbox_keypress_callback(iren, obj, slider): # iren: CustomInteractorStyle # obj: vtkActor picked # slider: LineSlider2D key = iren.event.key.lower() textbox = slider.textbox if key not in [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "period", "backspace", "return", "kp_enter" ]: # Unauthorized key pass elif len(textbox.text) == 0 and key in ["return", "kp_enter"]: # User pressed "enter" on empty field; reset textbox iren.remove_active_prop(textbox.actor) textbox.set_message(slider.format_text()) elif len(textbox.text) >= 4 and key not in [ "backspace", "return", "kp_enter" ]: # Textbox is filled to max length pass else: # Switch for period character key = '.' if key == "period" else key # Process keypress is_done = textbox.handle_character(key) if is_done: iren.remove_active_prop(textbox.actor) try: threshold = float(textbox.text) if threshold > slider.max_value: # Invalid value, reset textbox textbox.set_message(slider.format_text()) elif self.last_threshold != threshold: slider.set_value(threshold) nb_bundles = self.bundles[ self.selected_bundle].preview(threshold) self.last_threshold = threshold label.set_message("{} clusters".format(nb_bundles)) except ValueError: # Invalid value, reset textbox textbox.set_message(slider.format_text()) iren.force_render() iren.event.abort() # Stop propagating the event. slider = gui_2d.LineSlider2D(length=1000, text_template="{value:.1f}mm") slider.add_callback("LeftButtonPressEvent", disk_move_callback, slider.slider_line) slider.add_callback("LeftButtonPressEvent", disk_press_callback, slider.slider_disk) slider.add_callback("MouseMoveEvent", disk_move_callback, slider.slider_disk) slider.add_callback("MouseMoveEvent", disk_move_callback, slider.slider_line) slider.add_callback("KeyPressEvent", slider_textbox_keypress_callback, slider.text) slider.add_callback("LeftButtonPressEvent", slider_textbox_select_callback, slider.text) panel.add_element(slider, (0.5, 0.5)) panel.slider = slider # Add shortcut keys. def toggle_visibility_onchar_callback(iren, evt_name): if self.selected_bundle is None: return if iren.event.key.lower() == "space": toggle_other_bundles_visibility(iren) self.iren.AddObserver("CharEvent", toggle_visibility_onchar_callback) return panel
""" Buttons ======= We first fetch the icons required for making the buttons. """ fetch_viz_icons() """ Add the icon filenames to a dict. """ icon_files = [] icon_files.append(('stop', read_viz_icons(fname='stop2.png'))) icon_files.append(('play', read_viz_icons(fname='play3.png'))) icon_files.append(('plus', read_viz_icons(fname='plus.png'))) icon_files.append(('cross', read_viz_icons(fname='cross.png'))) """ Create a button through our API. """ button_example = ui.Button2D(icon_fnames=icon_files) """ We now add some click listeners. """