def build_label(text, font_size=18, bold=False): """ Simple utility function to build labels Parameters ---------- text : str font_size : int bold : bool Returns ------- label : TextBlock2D """ label = ui.TextBlock2D() label.message = text label.font_size = font_size label.font_family = 'Arial' label.justification = 'left' label.bold = bold label.italic = False label.shadow = False label.actor.GetTextProperty().SetBackgroundColor(0, 0, 0) label.actor.GetTextProperty().SetBackgroundOpacity(0.0) label.color = (1, 1, 1) return label
def test_text_block_2d(): # TextBlock2D text_block = ui.TextBlock2D() text_block.message = "Hello World!" npt.assert_equal("Hello World!", text_block.message) text_block.font_size = 18 npt.assert_equal("18", str(text_block.font_size)) text_block.font_family = "Arial" npt.assert_equal("Arial", text_block.font_family) with npt.assert_raises(ValueError): text_block.font_family = "Verdana" text_block.justification = "left" text_block.justification = "right" text_block.justification = "center" npt.assert_equal("Centered", text_block.justification) with npt.assert_raises(ValueError): text_block.justification = "bottom" text_block.bold = True text_block.bold = False npt.assert_equal(False, text_block.bold) text_block.italic = True text_block.italic = False npt.assert_equal(False, text_block.italic) text_block.shadow = True text_block.shadow = False npt.assert_equal(False, text_block.shadow) text_block.color = (1, 0, 0) npt.assert_equal((1, 0, 0), text_block.color) text_block.position = (2, 3) npt.assert_equal((2, 3), text_block.position)
def test_text_block_2d(): text_block = ui.TextBlock2D() def _check_property(obj, attr, values): for value in values: setattr(obj, attr, value) npt.assert_equal(getattr(obj, attr), value) _check_property(text_block, "bold", [True, False]) _check_property(text_block, "italic", [True, False]) _check_property(text_block, "shadow", [True, False]) _check_property(text_block, "font_size", range(100)) _check_property(text_block, "message", ["", "Hello World", "Line\nBreak"]) _check_property(text_block, "justification", ["left", "center", "right"]) _check_property(text_block, "position", [(350, 350), (0.5, 0.5)]) _check_property(text_block, "color", [(0., 0.5, 1.)]) _check_property(text_block, "background_color", [(0., 0.5, 1.), None]) _check_property(text_block, "vertical_justification", ["top", "middle", "bottom"]) _check_property(text_block, "font_family", ["Arial", "Courier"]) with npt.assert_raises(ValueError): text_block.font_family = "Verdana" with npt.assert_raises(ValueError): text_block.justification = "bottom" with npt.assert_raises(ValueError): text_block.vertical_justification = "left"
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
def build_label(text): label = ui.TextBlock2D() label.message = text label.font_size = 18 label.font_family = 'Arial' label.justification = 'left' label.bold = False label.italic = False label.shadow = False label.actor.GetTextProperty().SetBackgroundColor(0, 0, 0) label.actor.GetTextProperty().SetBackgroundOpacity(0.0) label.color = (1, 1, 1) return label
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)
def main(): # reads the tractography data in trk format # extracts streamlines and the file header. Streamlines should be in the same coordinate system as the FA map (used later). # input example: '/home/Example_data/tracts.trk' tractography_file = input( "Please, specify the file with tracts that you would like to analyse. File should be in the trk format. " ) streams, hdr = load_trk(tractography_file) # for old DIPY version # sft = load_trk(tractography_file, tractography_file) # streams = sft.streamlines streams_array = np.asarray(streams) print('imported tractography data:' + tractography_file) # load T1fs_conform image that operates in the same coordinates as simnibs except for the fact the center of mesh # is located at the image center # T1fs_conform image should be generated in advance during the head meshing procedure # input example: fname_T1='/home/Example_data/T1fs_conform.nii.gz' fname_T1 = input( "Please, specify the T1fs_conform image that has been generated during head meshing procedure. " ) data_T1, affine_T1 = load_nifti(fname_T1) # load FA image in the same coordinates as tracts # input example:fname_FA='/home/Example_data/DTI_FA.nii' fname_FA = input("Please, specify the FA image. ") data_FA, affine_FA = load_nifti(fname_FA) print('loaded T1fs_conform.nii and FA images') # specify the head mesh file that is used later in simnibs to simulate induced electric field # input example:'/home/Example_data/SUBJECT_MESH.msh' global mesh_path mesh_path = input("Please, specify the head mesh file. ") last_slach = max([i for i, ltr in enumerate(mesh_path) if ltr == '/']) + 1 global subject_name subject_name = mesh_path[last_slach:-4] # specify the directory where you would like to save your simulation results # input example:'/home/Example_data/Output' global out_dir out_dir = input( "Please, specify the directory where you would like to save your simulation results. " ) out_dir = out_dir + '/simulation_at_pos_' # Co-registration of T1fs_conform and FA images. Performed in 4 steps. # Step 1. Calculation of the center of mass transform. Used later as starting transform. c_of_mass = transform_centers_of_mass(data_T1, affine_T1, data_FA, affine_FA) print('calculated c_of_mass transformation') # Step 2. Calculation of a 3D translation transform. Used in the next step as starting transform. nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) level_iters = [10000, 1000, 100] sigmas = [3.0, 1.0, 0.0] factors = [4, 2, 1] affreg = AffineRegistration(metric=metric, level_iters=level_iters, sigmas=sigmas, factors=factors) transform = TranslationTransform3D() params0 = None starting_affine = c_of_mass.affine translation = affreg.optimize(data_T1, data_FA, transform, params0, affine_T1, affine_FA, starting_affine=starting_affine) print('calculated 3D translation transform') # Step 3. Calculation of a Rigid 3D transform. Used in the next step as starting transform transform = RigidTransform3D() params0 = None starting_affine = translation.affine rigid = affreg.optimize(data_T1, data_FA, transform, params0, affine_T1, affine_FA, starting_affine=starting_affine) print('calculated Rigid 3D transform') # Step 4. Calculation of an affine transform. Used for co-registration of T1 and FA images. transform = AffineTransform3D() params0 = None starting_affine = rigid.affine affine = affreg.optimize(data_T1, data_FA, transform, params0, affine_T1, affine_FA, starting_affine=starting_affine) print('calculated Affine 3D transform') identity = np.eye(4) inv_affine_FA = np.linalg.inv(affine_FA) inv_affine_T1 = np.linalg.inv(affine_T1) inv_affine = np.linalg.inv(affine.affine) # transforming streamlines to FA space new_streams_FA = streamline.transform_streamlines(streams, inv_affine_FA) new_streams_FA_array = np.asarray(new_streams_FA) T1_to_FA = np.dot(inv_affine_FA, np.dot(affine.affine, affine_T1)) FA_to_T1 = np.linalg.inv(T1_to_FA) # transforming streamlines from FA to T1 space new_streams_T1 = streamline.transform_streamlines(new_streams_FA, FA_to_T1) global new_streams_T1_array new_streams_T1_array = np.asarray(new_streams_T1) # calculating amline derivatives along the streamlines to get the local orientation of the streamlines global streams_array_derivative streams_array_derivative = copy.deepcopy(new_streams_T1_array) print('calculating amline derivatives') for stream in range(len(new_streams_T1_array)): my_steam = new_streams_T1_array[stream] for t in range(len(my_steam[:, 0])): streams_array_derivative[stream][t, 0] = my_deriv(t, my_steam[:, 0]) streams_array_derivative[stream][t, 1] = my_deriv(t, my_steam[:, 1]) streams_array_derivative[stream][t, 2] = my_deriv(t, my_steam[:, 2]) deriv_norm = np.linalg.norm(streams_array_derivative[stream][t, :]) streams_array_derivative[stream][ t, :] = streams_array_derivative[stream][t, :] / deriv_norm # to create a torus representing a coil in an interactive window torus = vtk.vtkParametricTorus() torus.SetRingRadius(5) torus.SetCrossSectionRadius(2) torusSource = vtk.vtkParametricFunctionSource() torusSource.SetParametricFunction(torus) torusSource.SetScalarModeToPhase() torusMapper = vtk.vtkPolyDataMapper() torusMapper.SetInputConnection(torusSource.GetOutputPort()) torusMapper.SetScalarRange(0, 360) torusActor = vtk.vtkActor() torusActor.SetMapper(torusMapper) torus_pos_x = 100 torus_pos_y = 129 torus_pos_z = 211 torusActor.SetPosition(torus_pos_x, torus_pos_y, torus_pos_z) list_streams_T1 = list(new_streams_T1) # adding one fictive bundle of length 1 with coordinates [0,0,0] to avoid some bugs with actor.line during visualization list_streams_T1.append(np.array([0, 0, 0])) global bundle_native bundle_native = list_streams_T1 # generating a list of colors to visualize later the stimualtion effects effect_max = 0.100 effect_min = -0.100 global colors colors = [ np.random.rand(*current_streamline.shape) for current_streamline in bundle_native ] for my_streamline in range(len(bundle_native) - 1): my_stream = copy.deepcopy(bundle_native[my_streamline]) for point in range(len(my_stream)): colors[my_streamline][point] = vtkplotter.colors.colorMap( (effect_min + effect_max) / 2, name='jet', vmin=effect_min, vmax=effect_max) colors[my_streamline + 1] = vtkplotter.colors.colorMap(effect_min, name='jet', vmin=effect_min, vmax=effect_max) # Vizualization of fibers over T1 # i_coord = 0 # j_coord = 0 # k_coord = 0 # global number_of_stimulations number_of_stimulations = 0 actor_line_list = [] scene = window.Scene() scene.clear() scene.background((0.5, 0.5, 0.5)) world_coords = False shape = data_T1.shape lut = actor.colormap_lookup_table(scale_range=(effect_min, effect_max), hue_range=(0.4, 1.), saturation_range=(1, 1.)) # # the lines below is for a non-interactive demonstration run only. # # they should remain commented unless you set "interactive" to False # lut, colors = change_TMS_effects(torus_pos_x, torus_pos_y, torus_pos_z) # bar = actor.scalar_bar(lut) # bar.SetTitle("TMS effect") # bar.SetHeight(0.3) # bar.SetWidth(0.10) # bar.SetPosition(0.85, 0.3) # scene.add(bar) actor_line_list.append( actor.line(bundle_native, colors, linewidth=5, fake_tube=True, lookup_colormap=lut)) if not world_coords: image_actor_z = actor.slicer(data_T1, identity) else: image_actor_z = actor.slicer(data_T1, identity) slicer_opacity = 0.6 image_actor_z.opacity(slicer_opacity) image_actor_x = image_actor_z.copy() x_midpoint = int(np.round(shape[0] / 2)) image_actor_x.display_extent(x_midpoint, x_midpoint, 0, shape[1] - 1, 0, shape[2] - 1) image_actor_y = image_actor_z.copy() y_midpoint = int(np.round(shape[1] / 2)) image_actor_y.display_extent(0, shape[0] - 1, y_midpoint, y_midpoint, 0, shape[2] - 1) """ Connect the actors with the scene. """ scene.add(actor_line_list[0]) scene.add(image_actor_z) scene.add(image_actor_x) scene.add(image_actor_y) show_m = window.ShowManager(scene, size=(1200, 900)) show_m.initialize() """ Create sliders to move the slices and change their opacity. """ line_slider_z = ui.LineSlider2D(min_value=0, max_value=shape[2] - 1, initial_value=shape[2] / 2, text_template="{value:.0f}", length=140) line_slider_x = ui.LineSlider2D(min_value=0, max_value=shape[0] - 1, initial_value=shape[0] / 2, text_template="{value:.0f}", length=140) line_slider_y = ui.LineSlider2D(min_value=0, max_value=shape[1] - 1, initial_value=shape[1] / 2, text_template="{value:.0f}", length=140) opacity_slider = ui.LineSlider2D(min_value=0.0, max_value=1.0, initial_value=slicer_opacity, length=140) """ Сallbacks for the sliders. """ def change_slice_z(slider): z = int(np.round(slider.value)) image_actor_z.display_extent(0, shape[0] - 1, 0, shape[1] - 1, z, z) def change_slice_x(slider): x = int(np.round(slider.value)) image_actor_x.display_extent(x, x, 0, shape[1] - 1, 0, shape[2] - 1) def change_slice_y(slider): y = int(np.round(slider.value)) image_actor_y.display_extent(0, shape[0] - 1, y, y, 0, shape[2] - 1) def change_opacity(slider): slicer_opacity = slider.value image_actor_z.opacity(slicer_opacity) image_actor_x.opacity(slicer_opacity) image_actor_y.opacity(slicer_opacity) line_slider_z.on_change = change_slice_z line_slider_x.on_change = change_slice_x line_slider_y.on_change = change_slice_y opacity_slider.on_change = change_opacity """ Сreate text labels to identify the sliders. """ def build_label(text): label = ui.TextBlock2D() label.message = text label.font_size = 18 label.font_family = 'Arial' label.justification = 'left' label.bold = False label.italic = False label.shadow = False label.background = (0, 0, 0) label.color = (1, 1, 1) return label line_slider_label_z = build_label(text="Z Slice") line_slider_label_x = build_label(text="X Slice") line_slider_label_y = build_label(text="Y Slice") opacity_slider_label = build_label(text="Opacity") """ Create a ``panel`` to contain the sliders and labels. """ panel = ui.Panel2D(size=(300, 200), color=(1, 1, 1), opacity=0.1, align="right") panel.center = (1030, 120) panel.add_element(line_slider_label_x, (0.1, 0.75)) panel.add_element(line_slider_x, (0.38, 0.75)) panel.add_element(line_slider_label_y, (0.1, 0.55)) panel.add_element(line_slider_y, (0.38, 0.55)) panel.add_element(line_slider_label_z, (0.1, 0.35)) panel.add_element(line_slider_z, (0.38, 0.35)) panel.add_element(opacity_slider_label, (0.1, 0.15)) panel.add_element(opacity_slider, (0.38, 0.15)) scene.add(panel) """ Create a ``panel`` to show the value of a picked voxel. """ label_position = ui.TextBlock2D(text='Position:') label_value = ui.TextBlock2D(text='Value:') result_position = ui.TextBlock2D(text='') result_value = ui.TextBlock2D(text='') text2 = ui.TextBlock2D(text='Calculate') panel_picking = ui.Panel2D(size=(250, 125), color=(1, 1, 1), opacity=0.1, align="left") panel_picking.center = (200, 120) panel_picking.add_element(label_position, (0.1, 0.75)) panel_picking.add_element(label_value, (0.1, 0.45)) panel_picking.add_element(result_position, (0.45, 0.75)) panel_picking.add_element(result_value, (0.45, 0.45)) panel_picking.add_element(text2, (0.1, 0.15)) icon_files = [] icon_files.append(('left', read_viz_icons(fname='circle-left.png'))) button_example = ui.Button2D(icon_fnames=icon_files, size=(100, 30)) panel_picking.add_element(button_example, (0.5, 0.1)) def change_text_callback(i_ren, obj, button): text2.message = str(i_coord) + ' ' + str(j_coord) + ' ' + str(k_coord) torusActor.SetPosition(i_coord, j_coord, k_coord) print(i_coord, j_coord, k_coord) lut, colors = change_TMS_effects(i_coord, j_coord, k_coord) scene.rm(actor_line_list[0]) actor_line_list.append( actor.line(bundle_native, colors, linewidth=5, fake_tube=True, lookup_colormap=lut)) scene.add(actor_line_list[1]) nonlocal number_of_stimulations global bar if number_of_stimulations > 0: scene.rm(bar) else: number_of_stimulations = number_of_stimulations + 1 bar = actor.scalar_bar(lut) bar.SetTitle("TMS effect") bar.SetHeight(0.3) bar.SetWidth(0.10) # the width is set first bar.SetPosition(0.85, 0.3) scene.add(bar) actor_line_list.pop(0) i_ren.force_render() button_example.on_left_mouse_button_clicked = change_text_callback scene.add(panel_picking) scene.add(torusActor) def left_click_callback(obj, ev): """Get the value of the clicked voxel and show it in the panel.""" event_pos = show_m.iren.GetEventPosition() obj.picker.Pick(event_pos[0], event_pos[1], 0, scene) global i_coord, j_coord, k_coord i_coord, j_coord, k_coord = obj.picker.GetPointIJK() print(i_coord, j_coord, k_coord) result_position.message = '({}, {}, {})'.format( str(i_coord), str(j_coord), str(k_coord)) result_value.message = '%.8f' % data_T1[i_coord, j_coord, k_coord] torusActor.SetPosition(i_coord, j_coord, k_coord) image_actor_z.AddObserver('LeftButtonPressEvent', left_click_callback, 1.0) global size size = scene.GetSize() def win_callback(obj, event): global size if size != obj.GetSize(): size_old = size size = obj.GetSize() size_change = [size[0] - size_old[0], 0] panel.re_align(size_change) show_m.initialize() """ Set the following variable to ``True`` to interact with the datasets in 3D. """ interactive = True scene.zoom(2.0) scene.reset_clipping_range() scene.set_camera(position=(-642.07, 495.40, 148.49), focal_point=(127.50, 127.50, 127.50), view_up=(0.02, -0.01, 1.00)) if interactive: show_m.add_window_callback(win_callback) show_m.render() show_m.start() else: window.record(scene, out_path=out_dir + '/bundles_and_effects.png', size=(1200, 900), reset_camera=True)
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"])
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)
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.) showm.render() if cnt == 100: showm.exit()
def show_mosaic(data): renderer = window.Renderer() renderer.background((0.5, 0.5, 0.5)) slice_actor = actor.slicer(data) show_m = window.ShowManager(renderer, size=(1200, 900)) show_m.initialize() label_position = ui.TextBlock2D(text='Position:') label_value = ui.TextBlock2D(text='Value:') result_position = ui.TextBlock2D(text='') result_value = ui.TextBlock2D(text='') panel_picking = ui.Panel2D(center=(200, 120), size=(250, 125), color=(0, 0, 0), opacity=0.75, align="left") panel_picking.add_element(label_position, 'relative', (0.1, 0.55)) panel_picking.add_element(label_value, 'relative', (0.1, 0.25)) panel_picking.add_element(result_position, 'relative', (0.45, 0.55)) panel_picking.add_element(result_value, 'relative', (0.45, 0.25)) show_m.ren.add(panel_picking) """ Add a left-click callback to the slicer. Also disable interpolation so you can see what you are picking. """ renderer.clear() renderer.projection('parallel') result_position.message = '' result_value.message = '' show_m_mosaic = window.ShowManager(renderer, size=(1200, 900)) show_m_mosaic.initialize() def left_click_callback_mosaic(obj, ev): """Get the value of the clicked voxel and show it in the panel.""" event_pos = show_m_mosaic.iren.GetEventPosition() obj.picker.Pick(event_pos[0], event_pos[1], 0, show_m_mosaic.ren) i, j, k = obj.picker.GetPointIJK() result_position.message = '({}, {}, {})'.format(str(i), str(j), str(k)) result_value.message = '%.8f' % data[i, j, k] cnt = 0 X, Y, Z = slice_actor.shape[:3] rows = 10 cols = 15 border = 10 for j in range(rows): for i in range(cols): slice_mosaic = slice_actor.copy() slice_mosaic.display(None, None, cnt) slice_mosaic.SetPosition( (X + border) * i, 0.5 * cols * (Y + border) - (Y + border) * j, 0) slice_mosaic.SetInterpolate(False) slice_mosaic.AddObserver('LeftButtonPressEvent', left_click_callback_mosaic, 1.0) renderer.add(slice_mosaic) cnt += 1 if cnt > Z: break if cnt > Z: break renderer.reset_camera() renderer.zoom(1.6) show_m_mosaic.ren.add(panel_picking) show_m_mosaic.start()
import os from dipy.data import read_viz_icons, fetch_viz_icons from dipy.viz import ui, window # Initializing a TextBox to display the Frame Rate global tb tb = ui.TextBlock2D() # A callback function to calculate Frame Rate def timer_callback(obj, event): global show_manager, tb tb.message = "Frame Rate : " + str(1.0/show_manager.ren.GetLastRenderTimeInSeconds()) show_manager.render() current_size = (600, 600) global show_manager show_manager = window.ShowManager(size=current_size, title=" Frame Rate") show_manager.initialize() show_manager.ren.add(tb.get_actor()) # Rendering 10 spheres for i in range(10): sphereSource = window.vtk.vtkSphereSource() sphereSource.SetCenter(i, 0, 0) mapper = window.vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = window.vtk.vtkActor() actor.SetMapper(mapper)
""" """ Now we would like to add the ability to click on a voxel and show its value on a panel in the window. The panel is a UI element which requires access to different areas of the visualization pipeline and therefore we don't recommend using it with ``window.show``. The more appropriate way is to use the ``ShowManager`` object, which allows accessing the pipeline in different areas. """ show_m = window.ShowManager(scene, size=(1200, 900)) show_m.initialize() """ We'll start by creating the panel and adding it to the ``ShowManager`` """ label_position = ui.TextBlock2D(text='Position:') label_value = ui.TextBlock2D(text='Value:') result_position = ui.TextBlock2D(text='') result_value = ui.TextBlock2D(text='') panel_picking = ui.Panel2D(size=(250, 125), position=(20, 20), color=(0, 0, 0), opacity=0.75, align="left") panel_picking.add_element(label_position, (0.1, 0.55)) panel_picking.add_element(label_value, (0.1, 0.25)) panel_picking.add_element(result_position, (0.45, 0.55))
""" 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. """ text = ui.TextBlock2D(text='Click me') text2 = ui.TextBlock2D(text='Me too') panel.add_element(text, (50, 100)) panel.add_element(text2, (180, 100)) """ Then we'll create two buttons and add them to the panel. Note that here we specify the positions with floats. In this case, these are percentages of the panel size. """ button_example = ui.Button2D(icon_fnames=[('square', read_viz_icons(fname='stop2.png'))]) icon_files = [] icon_files.append(('down', read_viz_icons(fname='circle-down.png')))
def show_odfs_and_fa(fa, pam, mask, affine, sphere, ftmp='odf.mmap', basis_type=None, norm_odfs=True, scale_odfs=0.5): renderer = window.Renderer() renderer.background((1, 1, 1)) slice_actor = actor.slicer(fa) #, value_range) odf_shape = fa.shape + (sphere.vertices.shape[0], ) odfs = np.memmap(ftmp, dtype=np.float32, mode='w+', shape=odf_shape) sph_harm_basis = sph_harm_lookup.get(basis_type) if sph_harm_basis is None: raise ValueError("Invalid basis name.") B, m, n = sph_harm_basis(8, sphere.theta, sphere.phi) odfs[:] = np.dot(pam.shm_coeff.astype('f4'), B.T.astype('f4')) odf_slicer = actor.odf_slicer(odfs, mask=mask, sphere=sphere, scale=scale_odfs, norm=norm_odfs, colormap='magma') renderer.add(odf_slicer) renderer.add(slice_actor) show_m = window.ShowManager(renderer, size=(2000, 1000)) show_m.initialize() """ We'll start by creating the panel and adding it to the ``ShowManager`` """ label_position = ui.TextBlock2D(text='Position:') label_value = ui.TextBlock2D(text='Value:') result_position = ui.TextBlock2D(text='') result_value = ui.TextBlock2D(text='') line_slider_z = ui.LineSlider2D(min_value=0, max_value=shape[2] - 1, initial_value=shape[2] / 2, text_template="{value:.0f}", length=140) def change_slice_z(i_ren, obj, slider): z = int(np.round(slider.value)) slice_actor.display(z=z) odf_slicer.display(z=z) show_m.render() line_slider_z.add_callback(line_slider_z.slider_disk, "LeftButtonReleaseEvent", change_slice_z) panel_picking = ui.Panel2D(center=(200, 120), size=(250, 225), color=(0, 0, 0), opacity=0.75, align="left") # panel_picking.add_element(label_position, 'relative', (0.1, 0.55)) # panel_picking.add_element(label_value, 'relative', (0.1, 0.25)) # panel_picking.add_element(result_position, 'relative', (0.45, 0.55)) # panel_picking.add_element(result_value, 'relative', (0.45, 0.25)) panel_picking.add_element(line_slider_z, 'relative', (0.5, 0.9)) show_m.ren.add(panel_picking) def left_click_callback(obj, ev): """Get the value of the clicked voxel and show it in the panel.""" event_pos = show_m.iren.GetEventPosition() obj.picker.Pick(event_pos[0], event_pos[1], 0, show_m.ren) i, j, k = obj.picker.GetPointIJK() print(i, j, k) result_position.message = '({}, {}, {})'.format(str(i), str(j), str(k)) result_value.message = '%.3f' % fa[i, j, k] slice_actor.SetInterpolate(True) slice_actor.AddObserver('LeftButtonPressEvent', left_click_callback, 1.0) show_m.start() odfs._mmap.close() del odfs os.remove(ftmp)
def main(): global parser global args global model global bar global lut_cmap global list_x_file global max_weight global saturation global renderer global norm_fib global norm1 global norm2 global norm3 global big_stream_actor global good_stream_actor global weak_stream_actor global big_Weight global good_Weight global weak_Weight global smallBundle_safe global smallWeight_safe global show_m global big_bundle global good_bundle global weak_bundle global nF global nIC global Ra global change_colormap_slider global remove_small_weights_slider global opacity_slider global remove_big_weights_slider global change_iteration_slider global num_computed_streamlines global numbers_of_streamlines_in_interval #defining the model used (Stick or cylinder) model = None if(os.path.isdir(args.commitOutputPath+"/Results_StickZeppelinBall") and os.path.isdir(args.commitOutputPath+"/Results_CylinderZeppelinBall")): model_index = input("Which model do you want to load (1 for 'Cylinder', 2 for 'Stick') : ") if(model_index==1): model = "Cylinder" else: model ="Stick" elif(os.path.isdir(args.commitOutputPath+"/Results_StickZeppelinBall")): model = "Stick" elif(os.path.isdir(args.commitOutputPath+"/Results_CylinderZeppelinBall")): model = "Cylinder" else: print("No valide model in this path") sys.exit(0) #formalizing the filenames of the iterations list_x_file = [file for file in os.listdir(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/") if (file.endswith('.npy') and (file[:-4]).isdigit() )] normalize_file_name(list_x_file) list_x_file.sort() num_iteration=len(list_x_file) #number of streamlines we want to load num_computed_streamlines = int(args.streamlinesNumber) #computing interval of weights max_weight = 0; if(model == "Cylinder"): file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' ) object_file = pickle.load( file ) Ra = np.linspace( 0.75,3.5,12 ) * 1E-6 nIC = len(Ra) # IC atoms nEC = 4 # EC atoms nISO = 1 # ISO atoms nF = object_file[0]['optimization']['regularisation']['sizeIC'] nE = object_file[0]['optimization']['regularisation']['sizeEC'] nV = object_file[0]['optimization']['regularisation']['sizeISO'] num_ADI = np.zeros( nF ) den_ADI = np.zeros( nF ) dim = nib.load(args.commitOutputPath+"/Results_"+model+"ZeppelinBall/compartment_IC.nii.gz").get_data().shape norm_fib = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm_fib.npy") norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy") norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy") norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy") for itNbr in list_x_file: #computing diameter x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+ itNbr +'.npy') x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) ) for i in range(nIC): den_ADI = den_ADI + x_norm[i*nF:(i+1)*nF] num_ADI = num_ADI + x_norm[i*nF:(i+1)*nF] * Ra[i] Weight = 2 * ( num_ADI / ( den_ADI + np.spacing(1) ) ) * 1E6 smallWeight_safe = Weight[:num_computed_streamlines] itNbr_max = np.amax(smallWeight_safe) if(itNbr_max>max_weight): max_weight=itNbr_max else:#model==Stick file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' ) object_file = pickle.load( file ) norm_fib = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm_fib.npy") norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy") norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy") norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy") nF = object_file[0]['optimization']['regularisation']['sizeIC'] for itNbr in list_x_file: x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+ itNbr +'.npy') x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) ) Weight = x_norm[:nF] #signal fractions smallWeight_safe = Weight[:num_computed_streamlines] itNbr_max = np.amax(smallWeight_safe) if(itNbr_max>max_weight): max_weight=itNbr_max #we need an interval slightly bigger than the max_weight max_weight = max_weight + 0.00001 #computing initial weights if(model == "Cylinder"):#model==Cylinder file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' ) object_file = pickle.load( file ) Ra = np.linspace( 0.75,3.5,12 ) * 1E-6 nIC = len(Ra) # IC atoms nEC = 4 # EC atoms nISO = 1 # ISO atoms nF = object_file[0]['optimization']['regularisation']['sizeIC'] nE = object_file[0]['optimization']['regularisation']['sizeEC'] nV = object_file[0]['optimization']['regularisation']['sizeISO'] dim = nib.load(args.commitOutputPath+"/Results_"+model+"ZeppelinBall/compartment_IC.nii.gz").get_data().shape norm_fib = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm_fib.npy") #add the normalisation x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+list_x_file[0]+'.npy') norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy") norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy") norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy") x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) ) num_ADI = np.zeros( nF ) den_ADI = np.zeros( nF ) for i in range(nIC): den_ADI = den_ADI + x_norm[i*nF:(i+1)*nF] num_ADI = num_ADI + x_norm[i*nF:(i+1)*nF] * Ra[i] Weight = 2 * ( num_ADI / ( den_ADI + np.spacing(1) ) ) * 1E6 smallWeight_safe = Weight[:num_computed_streamlines] weak_Weight = smallWeight_safe[:1] big_Weight = smallWeight_safe[:1] good_Weight = copy.copy(smallWeight_safe) else:#model==Stick file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' ) object_file = pickle.load( file ) nF = object_file[0]['optimization']['regularisation']['sizeIC'] x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+list_x_file[0]+'.npy') norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy") norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy") norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy") x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) ) Weight = x_norm[:nF] #signal fractions smallWeight_safe = Weight[:num_computed_streamlines] weak_Weight = smallWeight_safe[:1] big_Weight = smallWeight_safe[:1] good_Weight = copy.copy(smallWeight_safe) #load streamlines from the dictionary_TRK_fibers_trk file streams, hdr = nib.trackvis.read(args.commitOutputPath+"/dictionary_TRK_fibers.trk") streamlines = [s[0] for s in streams] smallBundle_safe = streamlines[:num_computed_streamlines] weak_bundle = smallBundle_safe[:1] big_bundle = smallBundle_safe[:1] good_bundle = copy.copy(smallBundle_safe) #number of good streamlines num_streamlines = len(smallBundle_safe) # mapping streamlines and initial weights(with a red bar) in a renderer hue = [0, 0] # red only saturation = [0.0, 1.0] # black to white lut_cmap = actor.colormap_lookup_table( scale_range=(0, max_weight), hue_range=hue, saturation_range=saturation) weak_stream_actor = actor.line(weak_bundle, weak_Weight, lookup_colormap=lut_cmap) big_stream_actor = actor.line(big_bundle, big_Weight, lookup_colormap=lut_cmap) good_stream_actor = actor.line(good_bundle, good_Weight, lookup_colormap=lut_cmap) bar = actor.scalar_bar(lut_cmap, title = 'weight') bar.SetHeight(0.5) bar.SetWidth(0.1) bar.SetPosition(0.85,0.45) renderer = window.Renderer() renderer.set_camera(position=(-176.42, 118.52, 128.20), focal_point=(113.30, 100, 76.56), view_up=(0.18, 0.00, 0.98)) renderer.add(big_stream_actor) renderer.add(good_stream_actor) renderer.add(weak_stream_actor) renderer.add(bar) #adding sliders and renderer to a ShowManager show_m = window.ShowManager(renderer, size=(1200, 900)) show_m.initialize() save_one_image_bouton = ui.LineSlider2D(min_value=0, max_value=1, initial_value=0, text_template="save", length=1) add_graph_bouton = ui.LineSlider2D(min_value=0, max_value=1, initial_value=0, text_template="graph", length=1) color_slider = ui.LineSlider2D(min_value=0.0, max_value=1.0, initial_value=0, text_template="{value:.1f}", length=140) change_colormap_slider = ui.LineSlider2D(min_value=0, max_value=1.0, initial_value=0, text_template="", length=40) change_iteration_slider = ui.LineSlider2D(min_value=0, #we can't have max_value=num_iteration because #list_x_file[num_iteration] lead to an error max_value=num_iteration-0.01, initial_value=0, text_template=list_x_file[0], length=140) remove_big_weights_slider = ui.LineSlider2D(min_value=0, max_value=max_weight, initial_value=max_weight, text_template="{value:.2f}", length=140) remove_small_weights_slider = ui.LineSlider2D(min_value=0, max_value=max_weight, initial_value=0, text_template="{value:.2f}", length=140) opacity_slider = ui.LineSlider2D(min_value=0.0, max_value=1.0, initial_value=0.5, text_template="{ratio:.0%}", length=140) save_one_image_bouton.add_callback(save_one_image_bouton.slider_disk, "LeftButtonPressEvent", save_one_image) color_slider.add_callback(color_slider.slider_disk, "MouseMoveEvent", change_streamlines_color) color_slider.add_callback(color_slider.slider_line, "LeftButtonPressEvent", change_streamlines_color) add_graph_bouton.add_callback(add_graph_bouton.slider_disk, "LeftButtonPressEvent", add_graph) change_colormap_slider.add_callback(change_colormap_slider.slider_disk, "MouseMoveEvent", change_colormap) change_colormap_slider.add_callback(change_colormap_slider.slider_line, "LeftButtonPressEvent", change_colormap) change_iteration_slider.add_callback(change_iteration_slider.slider_disk, "MouseMoveEvent", change_iteration) change_iteration_slider.add_callback(change_iteration_slider.slider_line, "LeftButtonPressEvent", change_iteration) remove_big_weights_slider.add_callback(remove_big_weights_slider.slider_disk, "MouseMoveEvent", remove_big_weight) remove_big_weights_slider.add_callback(remove_big_weights_slider.slider_line, "LeftButtonPressEvent", remove_big_weight) remove_small_weights_slider.add_callback(remove_small_weights_slider.slider_disk, "MouseMoveEvent", remove_small_weight) remove_small_weights_slider.add_callback(remove_small_weights_slider.slider_line, "LeftButtonPressEvent", remove_small_weight) opacity_slider.add_callback(opacity_slider.slider_disk, "MouseMoveEvent", change_opacity) opacity_slider.add_callback(opacity_slider.slider_line, "LeftButtonPressEvent", change_opacity) color_slider_label = ui.TextBlock2D() color_slider_label.message = 'color of streamlines' change_colormap_slider_label_weight = ui.TextBlock2D() change_colormap_slider_label_weight.message = 'weight color' change_colormap_slider_label_direction = ui.TextBlock2D() change_colormap_slider_label_direction.message = 'direction color' change_iteration_slider_label = ui.TextBlock2D() change_iteration_slider_label.message = 'number of the iteration' remove_big_weights_slider_label = ui.TextBlock2D() remove_big_weights_slider_label.message = 'big weights subdued' remove_small_weights_slider_label = ui.TextBlock2D() remove_small_weights_slider_label.message = 'small weights subdued' opacity_slider_label = ui.TextBlock2D() opacity_slider_label.message = 'Unwanted weights opacity' numbers_of_streamlines_in_interval = ui.TextBlock2D() numbers_of_streamlines_in_interval.message = "Number of streamlines in interval: "+str(num_streamlines) panel = ui.Panel2D(center=(300, 160), size=(500, 280), color=(1, 1, 1), opacity=0.1, align="right") panel.add_element(save_one_image_bouton, 'relative', (0.9, 0.9)) panel.add_element(add_graph_bouton, 'relative', (0.9, 0.77)) panel.add_element(color_slider_label, 'relative', (0.05, 0.85)) panel.add_element(color_slider, 'relative', (0.7, 0.9)) panel.add_element(numbers_of_streamlines_in_interval, 'relative', (0.05, 0.72)) panel.add_element(change_colormap_slider_label_weight, 'relative', (0.05, 0.59)) panel.add_element(change_colormap_slider_label_direction, 'relative', (0.5, 0.59)) panel.add_element(change_colormap_slider, 'relative', (0.4, 0.64)) panel.add_element(change_iteration_slider_label, 'relative', (0.05, 0.46)) panel.add_element(change_iteration_slider, 'relative', (0.7, 0.51)) panel.add_element(remove_big_weights_slider_label, 'relative', (0.05, 0.33)) panel.add_element(remove_big_weights_slider, 'relative', (0.7, 0.37)) panel.add_element(remove_small_weights_slider_label, 'relative', (0.05, 0.2)) panel.add_element(remove_small_weights_slider, 'relative', (0.7, 0.24)) panel.add_element(opacity_slider_label, 'relative', (0.05, 0.07)) panel.add_element(opacity_slider, 'relative', (0.7, 0.11)) panel.add_to_renderer(renderer) renderer.reset_clipping_range() show_m.render() show_m.start()