def show_atlas_target_graph(atlas, target, out_path, interactive=True): ren = window.Scene() ren.SetBackground(1, 1, 1) ren.add(actor.line(atlas, colors=(1, 0, 1))) # Magenta ren.add(actor.line(target, colors=(1, 1, 0))) # Yellow #window.record(ren, out_path=out_path, size=(600, 600)) if interactive: window.show(ren)
def test_streamtube_and_line_actors(): scene = window.Scene() line1 = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2.]]) line2 = line1 + np.array([0.5, 0., 0.]) lines = [line1, line2] colors = np.array([[1, 0, 0], [0, 0, 1.]]) c = actor.line(lines, colors, linewidth=3) scene.add(c) c = actor.line(lines, colors, spline_subdiv=5, linewidth=3) scene.add(c) # create streamtubes of the same lines and shift them a bit c2 = actor.streamtube(lines, colors, linewidth=.1) c2.SetPosition(2, 0, 0) scene.add(c2) arr = window.snapshot(scene) report = window.analyze_snapshot(arr, colors=[(255, 0, 0), (0, 0, 255)], find_objects=True) npt.assert_equal(report.objects, 4) npt.assert_equal(report.colors_found, [True, True]) # as before with splines c2 = actor.streamtube(lines, colors, spline_subdiv=5, linewidth=.1) c2.SetPosition(2, 0, 0) scene.add(c2) arr = window.snapshot(scene) report = window.analyze_snapshot(arr, colors=[(255, 0, 0), (0, 0, 255)], find_objects=True) npt.assert_equal(report.objects, 4) npt.assert_equal(report.colors_found, [True, True]) c3 = actor.line(lines, colors, depth_cue=True, fake_tube=True) VTK_9_PLUS = window.vtk.vtkVersion.GetVTKMajorVersion() >= 9 shader_obj = c3.GetShaderProperty() if VTK_9_PLUS else c3.GetMapper() mapper_code = shader_obj.GetGeometryShaderCode() file_code = shaders.load("line.geom") npt.assert_equal(mapper_code, file_code) npt.assert_equal(c3.GetProperty().GetRenderLinesAsTubes(), True)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.tractogram]) assert_outputs_exist(parser, args, [], [args.save]) tracts_format = detect_format(args.tractogram) if tracts_format is not TrkFile: raise ValueError("Invalid input streamline file format " + "(must be trk): {0}".format(args.tractogram_filename)) # Load files and data. TRKs can have 'same' as reference tractogram = load_tractogram(args.tractogram, 'same') # Streamlines are saved in RASMM but seeds are saved in VOX # This might produce weird behavior with non-iso tractogram.to_vox() streamlines = tractogram.streamlines if 'seeds' not in tractogram.data_per_streamline: parser.error('Tractogram does not contain seeds') seeds = tractogram.data_per_streamline['seeds'] # Make display objects streamlines_actor = actor.line(streamlines) points = actor.dots(seeds, color=(1., 1., 1.)) # Add display objects to canvas s = window.Scene() s.add(streamlines_actor) s.add(points) # Show and record if needed if args.save is not None: window.record(s, out_path=args.save, size=(1000, 1000)) window.show(s)
def load_and_add_reference_tractogram(self, path_to_tractogram): """ Load tractogram from given path and add all streamlines to the scene. The camera setup is determined based on this tractogram. The streamlines are visualised with transparency. Parameters ---------- path_to_tractogram : str path to tractogram file (.trk) Returns ------- None """ # get streamlines in voxel space tracto = nib.streamlines.load(path_to_tractogram) streamlines = transform_streamlines(tracto.streamlines, np.linalg.inv(tracto.affine)) # add streamlines to the scene sl_actor = actor.line(streamlines, opacity=0.3) self.scene.add(sl_actor) # update camera settings self.apply_camera_update(streamlines, w=1) self.scene.reset_camera()
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.tractogram]) assert_outputs_exist(parser, args, [], [args.save]) tracts_format = detect_format(args.tractogram) if tracts_format is not TrkFile: raise ValueError("Invalid input streamline file format " + "(must be trk): {0}".format(args.tractogram_filename)) # Load files and data trk = TrkFile.load(args.tractogram) tractogram = trk.tractogram streamlines = tractogram.streamlines if 'seeds' not in tractogram.data_per_streamline: parser.error('Tractogram does not contain seeds') seeds = tractogram.data_per_streamline['seeds'] # Make display objects streamlines_actor = actor.line(streamlines) points = actor.dots(seeds, color=(1., 1., 1.)) # Add display objects to canvas r = window.Renderer() r.add(streamlines_actor) r.add(points) # Show and record if needed if args.save is not None: window.record(r, out_path=args.save, size=(1000, 1000)) window.show(r)
def timer_callback(_obj, _event): global pts, time, incre_time, coor_1 time += incre_time cnt = next(counter) x = initial_velocity*time + 0.5*acc*(time**2) y = np.sin(10*angular_frq*time + phase_angle) z = np.cos(10*angular_frq*time + phase_angle) pts = np.array([[x, y, z]]) vertices[:] = initial_vertices + \ np.repeat(pts, no_vertices_per_point, axis=0) utils.update_actor(charge_actor) # Plotting the path followed by the particle coor_2 = np.array([x, y, z]) coors = np.array([coor_1, coor_2]) coors = [coors] line_actor = actor.line(coors, window.colors.cyan, linewidth=3) scene.add(line_actor) coor_1 = coor_2 showm.render() # to end the animation if cnt == end: showm.exit()
def show_model_reco_bundles(model, recognized_bundle, folder_name, file_bundle_name, interactive=True): ren = window.Scene() ren.SetBackground(1, 1, 1) ren.add(actor.line(model, colors=(.1, .7, .26))) #green ren.add(actor.line(recognized_bundle, colors=(.1, .1, 6))) #blue if interactive: window.show(ren) ren.set_camera(ren.camera_info()) window.record(ren, out_path=pjoin(folder_name, file_bundle_name) + '.png', size=(600, 600))
def test_streamtube_and_line_actors(): renderer = window.renderer() line1 = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2.]]) line2 = line1 + np.array([0.5, 0., 0.]) lines = [line1, line2] colors = np.array([[1, 0, 0], [0, 0, 1.]]) c = actor.line(lines, colors, linewidth=3) window.add(renderer, c) c = actor.line(lines, colors, spline_subdiv=5, linewidth=3) window.add(renderer, c) # create streamtubes of the same lines and shift them a bit c2 = actor.streamtube(lines, colors, linewidth=.1) c2.SetPosition(2, 0, 0) window.add(renderer, c2) arr = window.snapshot(renderer) report = window.analyze_snapshot(arr, colors=[(255, 0, 0), (0, 0, 255)], find_objects=True) npt.assert_equal(report.objects, 4) npt.assert_equal(report.colors_found, [True, True]) # as before with splines c2 = actor.streamtube(lines, colors, spline_subdiv=5, linewidth=.1) c2.SetPosition(2, 0, 0) window.add(renderer, c2) arr = window.snapshot(renderer) report = window.analyze_snapshot(arr, colors=[(255, 0, 0), (0, 0, 255)], find_objects=True) npt.assert_equal(report.objects, 4) npt.assert_equal(report.colors_found, [True, True])
def execute(self, iren, event): renderer.RemoveAllViewProps() # streamlines #current_location = pts[self.iterations] # change this to read in real time current_location = np.loadtxt("data/update_pts.txt") mask = np.zeros(handknob_left.shape) location = tuple(dipy.tracking._utils._to_voxel_coordinates([current_location], lin_T, offset)[0]) mask[location]=1 ##size of the mask mask = scipy.ndimage.morphology.binary_dilation(mask, iterations=15) endlabels = mask[i, j, k] idx = np.logical_or(endlabels[0,:]==1, endlabels[1,:]==1) if np.sum(idx)>0: active_stream = streamlines[idx] stream_actor = actor.line(active_stream) renderer.add(stream_actor) # Stimulation Location roiActor = actor.contour_from_roi(mask, affine=handknob_right.affine, color=np.array([1, 1, 1]), opacity=0.5) renderer.AddActor(roiActor) # ROI roiActor = actor.contour_from_roi(handknob_left.get_data(), affine=handknob_left.affine, color=np.array([1, 0, 0]), opacity=0.5) renderer.AddActor(roiActor) roiActor = actor.contour_from_roi(handknob_right.get_data(), affine=handknob_right.affine, color=np.array([0, 0, 1]), opacity=0.5) renderer.AddActor(roiActor) #stream_actor = actor.line([streamlines[self.iterations]]) #self.renderer.add(stream_actor) iren.GetRenderWindow().Render() if self.iterations < len(self.pts)-1: self.iterations += 1
def particle(colors, origin=[0, 0, 0], num_total_steps=300, total_time=5, delta=1.8, path_thickness=3): origin = np.asarray(origin, dtype=float) position = np.tile(origin, (num_total_steps, 1)) path_actor = actor.line([position], colors, linewidth=path_thickness) path_actor.position = position path_actor.delta = delta path_actor.num_total_steps = num_total_steps path_actor.time_step = total_time / num_total_steps path_actor.vertices = utils.vertices_from_actor(path_actor) path_actor.no_vertices_per_point = \ len(path_actor.vertices) / num_total_steps path_actor.initial_vertices = path_actor.vertices.copy() - \ np.repeat(position, path_actor.no_vertices_per_point, axis=0) return path_actor
def save_views_imgs(lines, size=(500, 500), interactive=False, ext='jpg'): """ Function to save view images when the input file does fulfill the requirements of the validator. :param lines: Streamlines-like object. :param size: A 2-tuple, containing (width, height) in pixels. :param interactive: (Boolean) If True, launches a window. Useful for developing/debugging options. :param ext: (String) Extension of the output files. """ # Start virtual display if has_xvfbwrapper: print('Starting Xvfb') vdisplay = Xvfb() vdisplay.start() # Create streamlines actor streamlines_actor = actor.line(lines) # Set renderer window scene = window.Scene() # Add streamlines to renderer scene.add(streamlines_actor) # Loop through views for param in _VIEW_PARAMS: # Set camera scene.set_camera(position=param['cam_pos'], focal_point=param['focal_pnt'], view_up=param['view_up']) if interactive: window.show(scene, size=size) # Save imgs out_file = os.path.join('secondary', param['view'] + '.' + ext) print('Saving: {}'.format(out_file)) window.record(scene, out_path=out_file, size=size) # Stop virtual display if has_xvfbwrapper: vdisplay.stop()
def add_and_render(self, streamlines, w): """ Add given streamlines to the scene and render the update. Parameters ---------- streamlines : nib.streamlines.array_sequence.ArraySequence streamlines to update the scene with w : float weighting factor for the new camera settings Returns ------- None """ # remove oldest bunch of streamlines if self.q.full(): self.scene.rm(self.q.get()) if self.show: sleep(StreamlineVisualiser.TIME_INC) # add new streamlines to the scene and the queue sl_actor = actor.line(streamlines) self.scene.add(sl_actor) self.q.put(sl_actor) # update camera settings if self.update_camera: self.apply_camera_update(streamlines, w) if self.reset_camera: self.scene.reset_camera() # render updated scene or collect 2D snapshot of the scene if self.show: self.sm.render() else: self.frames.append( window.snapshot(self.scene, size=self.plot_size)[::-1, ::-1])
def __init__(self, colors, origin=[0, 0, 0], num_total_steps=300, total_time=5, delta=1.8, path_thickness=3): origin = np.asarray(origin, dtype=float) self.position = np.tile(origin, (num_total_steps, 1)) self.colors = colors self.delta = delta self.num_total_steps = num_total_steps self.time_step = total_time / num_total_steps self.path_actor = actor.line([self.position], colors, linewidth=path_thickness) self.vertices = utils.vertices_from_actor(self.path_actor) self.vcolors = utils.colors_from_actor(self.path_actor, 'colors') self.no_vertices_per_point = len(self.vertices) / num_total_steps nvpp = self.no_vertices_per_point self.initial_vertices = self.vertices.copy() - np.repeat( self.position, nvpp, axis=0)
def show_both_bundles(bundles, colors=None, show=True, fname=None): if colors is None: colors = [window.colors.orange, window.colors.red] scene = window.Scene() #scene.SetBackground(1., 1, 1) # scene.set_camera(position=(-176.42, 118.52, 128.20), # focal_point=(113.30, 128.31, 76.56), # view_up=(0.18, 0.00, 0.98)) for (i, bundle) in enumerate(bundles): color = colors[i] lines_actor = actor.line(bundle, color, linewidth=0.3) #lines_actor.RotateX(-90) #lines_actor.RotateZ(90) scene.add(lines_actor) if show: window.show(scene) if fname is not None: sleep(1) window.record(scene, n_frames=1, out_path=fname, size=(900, 900))
############################################################################### # If we want to see the objects in native space we need to make sure that all # objects which are currently in world coordinates are transformed back to # native space using the inverse of the affine. if not world_coords: from dipy.tracking.streamline import transform_streamlines streamlines = transform_streamlines(streamlines, np.linalg.inv(affine)) ############################################################################### # Now we create, a ``Renderer`` object and add the streamlines using the # ``line`` function and an image plane using the ``slice`` function. ren = window.Renderer() stream_actor = actor.line(streamlines) if not world_coords: image_actor_z = actor.slicer(data, affine=np.eye(4)) else: image_actor_z = actor.slicer(data, affine) ############################################################################### # We can also change also the opacity of the slicer. slicer_opacity = 0.6 image_actor_z.opacity(slicer_opacity) ############################################################################### # We can add additonal slicers by copying the original and adjusting the # ``display_extent``.
def test_bundle_maps(): scene = window.Scene() bundle = simulated_bundle(no_streamlines=10, waves=False) metric = 100 * np.ones((200, 200, 200)) # add lower values metric[100, :, :] = 100 * 0.5 # create a nice orange-red colormap lut = actor.colormap_lookup_table(scale_range=(0., 100.), hue_range=(0., 0.1), saturation_range=(1, 1), value_range=(1., 1)) line = actor.line(bundle, metric, linewidth=0.1, lookup_colormap=lut) scene.add(line) scene.add(actor.scalar_bar(lut, ' ')) report = window.analyze_scene(scene) npt.assert_almost_equal(report.actors, 1) # window.show(scene) scene.clear() nb_points = np.sum([len(b) for b in bundle]) values = 100 * np.random.rand(nb_points) # values[:nb_points/2] = 0 line = actor.streamtube(bundle, values, linewidth=0.1, lookup_colormap=lut) scene.add(line) # window.show(scene) report = window.analyze_scene(scene) npt.assert_equal(report.actors_classnames[0], 'vtkLODActor') scene.clear() colors = np.random.rand(nb_points, 3) # values[:nb_points/2] = 0 line = actor.line(bundle, colors, linewidth=2) scene.add(line) # window.show(scene) report = window.analyze_scene(scene) npt.assert_equal(report.actors_classnames[0], 'vtkLODActor') # window.show(scene) arr = window.snapshot(scene) report2 = window.analyze_snapshot(arr) npt.assert_equal(report2.objects, 1) # try other input options for colors scene.clear() actor.line(bundle, (1., 0.5, 0)) actor.line(bundle, np.arange(len(bundle))) actor.line(bundle) colors = [np.random.rand(*b.shape) for b in bundle] actor.line(bundle, colors=colors)
atlas = sft_atlas.streamlines atlas_header = create_tractogram_header(atlas_file, *sft_atlas.space_attribute) sft_target = load_trk(target_file, "same", bbox_valid_check=False) target = sft_target.streamlines target_header = create_tractogram_header(atlas_file, *sft_atlas.space_attribute) """ let's visualize atlas tractogram and target tractogram before registration """ interactive = False ren = window.Renderer() ren.SetBackground(1, 1, 1) ren.add(actor.line(atlas, colors=(1, 0, 1))) ren.add(actor.line(target, colors=(1, 1, 0))) window.record(ren, out_path='tractograms_initial.png', size=(600, 600)) if interactive: window.show(ren) """ .. figure:: tractograms_initial.png :align: center Atlas and target before registration. """ """ We will register target tractogram to model atlas' space using streamlinear registeration (SLR) [Garyfallidis15]_ """
def keypress_callback(obj, _): key = obj.GetKeySym().lower() nonlocal clusters_linewidth, background_linewidth nonlocal curr_streamlines_actor, concat_streamlines_actor, show_curr_actor iterator = len(accepted_streamlines) + len(rejected_streamlines) renwin = interactor_style.GetInteractor().GetRenderWindow() renderer = interactor_style.GetCurrentRenderer() if key == 'c' and iterator < len(sft_accepted_on_size): if show_curr_actor: renderer.rm(concat_streamlines_actor) renwin.Render() show_curr_actor = False logging.info('Streamlines rendering OFF') else: renderer.add(concat_streamlines_actor) renderer.rm(curr_streamlines_actor) renderer.add(curr_streamlines_actor) renwin.Render() show_curr_actor = True logging.info('Streamlines rendering ON') return if key == 'q': show_manager.exit() if iterator < len(sft_accepted_on_size): logging.warning( 'Early exit, everything remaining to be rejected.') return if key in ['a', 'r'] and iterator < len(sft_accepted_on_size): if key == 'a': accepted_streamlines.append(iterator) choices.append('a') logging.info('Accepted file %s', filename_accepted_on_size[iterator]) elif key == 'r': rejected_streamlines.append(iterator) choices.append('r') logging.info('Rejected file %s', filename_accepted_on_size[iterator]) iterator += 1 if key == 'z': if iterator > 0: last_choice = choices.pop() if last_choice == 'r': rejected_streamlines.pop() else: accepted_streamlines.pop() logging.info('Rewind on step.') iterator -= 1 else: logging.warning('Cannot rewind, first element.') if key in ['a', 'r', 'z'] and iterator < len(sft_accepted_on_size): renderer.rm(curr_streamlines_actor) curr_streamlines = sft_accepted_on_size[iterator].streamlines curr_streamlines_actor = actor.line(curr_streamlines, opacity=0.8, linewidth=clusters_linewidth) renderer.add(curr_streamlines_actor) if iterator == len(sft_accepted_on_size): print('No more cluster, press q to exit') renderer.rm(curr_streamlines_actor) renwin.Render()
def test_bundle_maps(): renderer = window.renderer() bundle = fornix_streamlines() bundle, shift = center_streamlines(bundle) mat = np.array([[1, 0, 0, 100], [0, 1, 0, 100], [0, 0, 1, 100], [0, 0, 0, 1.]]) bundle = transform_streamlines(bundle, mat) # metric = np.random.rand(*(200, 200, 200)) metric = 100 * np.ones((200, 200, 200)) # add lower values metric[100, :, :] = 100 * 0.5 # create a nice orange-red colormap lut = actor.colormap_lookup_table(scale_range=(0., 100.), hue_range=(0., 0.1), saturation_range=(1, 1), value_range=(1., 1)) line = actor.line(bundle, metric, linewidth=0.1, lookup_colormap=lut) window.add(renderer, line) window.add(renderer, actor.scalar_bar(lut, ' ')) report = window.analyze_renderer(renderer) npt.assert_almost_equal(report.actors, 1) # window.show(renderer) renderer.clear() nb_points = np.sum([len(b) for b in bundle]) values = 100 * np.random.rand(nb_points) # values[:nb_points/2] = 0 line = actor.streamtube(bundle, values, linewidth=0.1, lookup_colormap=lut) renderer.add(line) # window.show(renderer) report = window.analyze_renderer(renderer) npt.assert_equal(report.actors_classnames[0], 'vtkLODActor') renderer.clear() colors = np.random.rand(nb_points, 3) # values[:nb_points/2] = 0 line = actor.line(bundle, colors, linewidth=2) renderer.add(line) # window.show(renderer) report = window.analyze_renderer(renderer) npt.assert_equal(report.actors_classnames[0], 'vtkLODActor') # window.show(renderer) arr = window.snapshot(renderer) report2 = window.analyze_snapshot(arr) npt.assert_equal(report2.objects, 1) # try other input options for colors renderer.clear() actor.line(bundle, (1., 0.5, 0)) actor.line(bundle, np.arange(len(bundle))) actor.line(bundle) colors = [np.random.rand(*b.shape) for b in bundle] actor.line(bundle, colors=colors)
############################################################################### # It happened that this bundle is in world coordinates and therefore we need to # transform it into native image coordinates so that it is in the same # coordinate space as the ``fa`` image. bundle_native = transform_streamlines(bundle, np.linalg.inv(affine)) ############################################################################### # Show every streamline with an orientation color # =============================================== # # This is the default option when you are using ``line`` or ``streamtube``. scene = window.Scene() stream_actor = actor.line(bundle_native) scene.set_camera(position=(-176.42, 118.52, 128.20), focal_point=(113.30, 128.31, 76.56), view_up=(0.18, 0.00, 0.98)) scene.add(stream_actor) # Uncomment the line below to show to display the window # window.show(scene, size=(600, 600), reset_camera=False) window.record(scene, out_path='bundle1.png', size=(600, 600)) ############################################################################### # You may wonder how we knew how to set the camera. This is very easy. You just # need to run ``window.show`` once see how you want to see the object and then # close the window and call the ``camera_info`` method which prints the
def test_contour_from_roi(): # Render volume renderer = window.renderer() data = np.zeros((50, 50, 50)) data[20:30, 25, 25] = 1. data[25, 20:30, 25] = 1. affine = np.eye(4) surface = actor.contour_from_roi(data, affine, color=np.array([1, 0, 1]), opacity=.5) renderer.add(surface) renderer.reset_camera() renderer.reset_clipping_range() # window.show(renderer) # Test binarization renderer2 = window.renderer() data2 = np.zeros((50, 50, 50)) data2[20:30, 25, 25] = 1. data2[35:40, 25, 25] = 1. affine = np.eye(4) surface2 = actor.contour_from_roi(data2, affine, color=np.array([0, 1, 1]), opacity=.5) renderer2.add(surface2) renderer2.reset_camera() renderer2.reset_clipping_range() # window.show(renderer2) arr = window.snapshot(renderer, 'test_surface.png', offscreen=True) arr2 = window.snapshot(renderer2, 'test_surface2.png', offscreen=True) report = window.analyze_snapshot(arr, find_objects=True) report2 = window.analyze_snapshot(arr2, find_objects=True) npt.assert_equal(report.objects, 1) npt.assert_equal(report2.objects, 2) # test on real streamlines using tracking example from dipy.data import read_stanford_labels from dipy.reconst.shm import CsaOdfModel from dipy.data import default_sphere from dipy.direction import peaks_from_model from dipy.tracking.local import ThresholdTissueClassifier from dipy.tracking import utils from dipy.tracking.local import LocalTracking from fury.colormap import line_colors hardi_img, gtab, labels_img = read_stanford_labels() data = hardi_img.get_data() labels = labels_img.get_data() affine = hardi_img.affine white_matter = (labels == 1) | (labels == 2) csa_model = CsaOdfModel(gtab, sh_order=6) csa_peaks = peaks_from_model(csa_model, data, default_sphere, relative_peak_threshold=.8, min_separation_angle=45, mask=white_matter) classifier = ThresholdTissueClassifier(csa_peaks.gfa, .25) seed_mask = labels == 2 seeds = utils.seeds_from_mask(seed_mask, density=[1, 1, 1], affine=affine) # Initialization of LocalTracking. # The computation happens in the next step. streamlines = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=2) # Compute streamlines and store as a list. streamlines = list(streamlines) # Prepare the display objects. streamlines_actor = actor.line(streamlines, line_colors(streamlines)) seedroi_actor = actor.contour_from_roi(seed_mask, affine, [0, 1, 1], 0.5) # Create the 3d display. r = window.Renderer() r2 = window.Renderer() r.add(streamlines_actor) arr3 = window.snapshot(r, 'test_surface3.png', offscreen=True) report3 = window.analyze_snapshot(arr3, find_objects=True) r2.add(streamlines_actor) r2.add(seedroi_actor) arr4 = window.snapshot(r2, 'test_surface4.png', offscreen=True) report4 = window.analyze_snapshot(arr4, find_objects=True) # assert that the seed ROI rendering is not far # away from the streamlines (affine error) npt.assert_equal(report3.objects, report4.objects)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, args.in_volume) assert_outputs_exist(parser, args, args.out_image) output_names = [ 'axial_superior', 'axial_inferior', 'coronal_posterior', 'coronal_anterior', 'sagittal_left', 'sagittal_right' ] for filename in args.in_bundles: _, ext = os.path.splitext(filename) if ext == '.tck': tractogram = load_tractogram_with_reference(parser, args, filename) else: tractogram = filename if not is_header_compatible(args.in_volume, tractogram): parser.error('{} does not have a compatible header with {}'.format( filename, args.in_volume)) # Delete temporary tractogram else: del tractogram output_dir = os.path.dirname(args.out_image) if output_dir: assert_output_dirs_exist_and_empty(parser, args, output_dir, create_dir=True) _, extension = os.path.splitext(args.out_image) # ----------------------------------------------------------------------- # # Mosaic, column 0: orientation names and data description # ----------------------------------------------------------------------- # width = args.resolution_of_thumbnails height = args.resolution_of_thumbnails rows = 6 cols = len(args.in_bundles) text_pos_x = 50 text_pos_y = 50 # Creates a new empty image, RGB mode mosaic = Image.new('RGB', ((cols + 1) * width, (rows + 1) * height)) # Prepare draw and font objects to render text draw = ImageDraw.Draw(mosaic) font = get_font(args) # Data of the volume used as background ref_img = nib.load(args.in_volume) data = ref_img.get_fdata(dtype=np.float32) affine = ref_img.affine mean, std = data[data > 0].mean(), data[data > 0].std() value_range = (mean - 0.5 * std, mean + 1.5 * std) # First column with rows description draw_column_with_names(draw, output_names, text_pos_x, text_pos_y, height, font) # ----------------------------------------------------------------------- # # Columns with bundles # ----------------------------------------------------------------------- # random.seed(args.random_coloring) for idx_bundle, bundle_file in enumerate(args.in_bundles): bundle_file_name = os.path.basename(bundle_file) bundle_name, bundle_ext = split_name_with_nii(bundle_file_name) i = (idx_bundle + 1) * width if not os.path.isfile(bundle_file): print('\nInput file {} doesn\'t exist.'.format(bundle_file)) number_streamlines = 0 view_number = 6 j = height * view_number draw_bundle_information(draw, bundle_file_name, number_streamlines, i + text_pos_x, j + text_pos_y, font) else: if args.uniform_coloring: colors = args.uniform_coloring elif args.random_coloring is not None: colors = random_rgb() # Select the streamlines to plot if bundle_ext in ['.tck', '.trk']: if (args.random_coloring is None and args.uniform_coloring is None): colors = None bundle_tractogram_file = nib.streamlines.load(bundle_file) streamlines = bundle_tractogram_file.streamlines bundle_actor = actor.line(streamlines, colors) nbr_of_elem = len(streamlines) # Select the volume to plot elif bundle_ext in ['.nii.gz', '.nii']: if not args.random_coloring and not args.uniform_coloring: colors = [1.0, 1.0, 1.0] bundle_img_file = nib.load(bundle_file) roi = get_data_as_mask(bundle_img_file) bundle_actor = actor.contour_from_roi(roi, bundle_img_file.affine, colors) nbr_of_elem = np.count_nonzero(roi) # Render ren = window.Scene() zoom = args.zoom opacity = args.opacity_background # Structural data slice_actor = actor.slicer(data, affine, value_range) slice_actor.opacity(opacity) ren.add(slice_actor) # Streamlines ren.add(bundle_actor) ren.reset_camera() ren.zoom(zoom) view_number = 0 set_img_in_cell(mosaic, ren, view_number, width, height, i) ren.pitch(180) ren.reset_camera() ren.zoom(zoom) view_number = 1 set_img_in_cell(mosaic, ren, view_number, width, height, i) ren.rm(slice_actor) slice_actor2 = slice_actor.copy() slice_actor2.display(None, slice_actor2.shape[1] // 2, None) slice_actor2.opacity(opacity) ren.add(slice_actor2) ren.pitch(90) ren.set_camera(view_up=(0, 0, 1)) ren.reset_camera() ren.zoom(zoom) view_number = 2 set_img_in_cell(mosaic, ren, view_number, width, height, i) ren.pitch(180) ren.set_camera(view_up=(0, 0, 1)) ren.reset_camera() ren.zoom(zoom) view_number = 3 set_img_in_cell(mosaic, ren, view_number, width, height, i) ren.rm(slice_actor2) slice_actor3 = slice_actor.copy() slice_actor3.display(slice_actor3.shape[0] // 2, None, None) slice_actor3.opacity(opacity) ren.add(slice_actor3) ren.yaw(90) ren.reset_camera() ren.zoom(zoom) view_number = 4 set_img_in_cell(mosaic, ren, view_number, width, height, i) ren.yaw(180) ren.reset_camera() ren.zoom(zoom) view_number = 5 set_img_in_cell(mosaic, ren, view_number, width, height, i) view_number = 6 j = height * view_number draw_bundle_information(draw, bundle_file_name, nbr_of_elem, i + text_pos_x, j + text_pos_y, font) # Save image to file mosaic.save(args.out_image)
classifier = ThresholdTissueClassifier(csa_peaks.gfa, .25) seed_mask = labels == 2 seeds = utils.seeds_from_mask(seed_mask, density=[1, 1, 1], affine=affine) # Initialization of LocalTracking. The computation happens in the next step. streamlines = LocalTracking(csa_peaks, classifier, seeds, affine, step_size=2) # Compute streamlines and store as a list. streamlines = Streamlines(streamlines) ############################################################################### # We will create a streamline actor from the streamlines. streamlines_actor = actor.line(streamlines, line_colors(streamlines)) ############################################################################### # Next, we create a surface actor from the corpus callosum seed ROI. We # provide the ROI data, the affine, the color in [R,G,B], and the opacity as # a decimal between zero and one. Here, we set the color as blue/green with # 50% opacity. surface_opacity = 0.5 surface_color = [0, 1, 1] seedroi_actor = actor.contour_from_roi(seed_mask, affine, surface_color, surface_opacity) ############################################################################### # Next, we initialize a ''Scene'' object and add both actors
def main(): parser = _build_arg_parser() args = parser.parse_args() required = [args.in_bundle, args.in_anat] assert_inputs_exist(parser, required, args.target_template) if args.verbose: logging.basicConfig(level=logging.DEBUG) output_filenames_3d = [] output_filenames_glass = [] for axis_name in ['sagittal', 'coronal', 'axial']: if args.output_suffix: output_filenames_3d.append( os.path.join( args.out_dir, '{0}_{1}_3d.png'.format(axis_name, args.output_suffix))) output_filenames_glass.append( os.path.join( args.out_dir, '{0}_{1}_glass.png'.format(axis_name, args.output_suffix))) else: output_filenames_3d.append( os.path.join(args.out_dir, '{0}_3d.png'.format(axis_name))) output_filenames_glass.append( os.path.join(args.out_dir, '{0}_glass.png'.format(axis_name))) assert_outputs_exist(parser, args, output_filenames_3d + output_filenames_glass) if args.out_dir and not os.path.isdir(args.out_dir): os.mkdir(args.out_dir) if args.anat_opacity < 0.0 or args.anat_opacity > 1.0: parser.error('Opacity must be between 0 and 1') if args.uniform_coloring: for val in args.uniform_coloring: if val < 0 or val > 255: parser.error('{0} is not a valid RGB value'.format(val)) # Get the relevant slices from the template if args.target_template: mni_space_img = nib.load(args.target_template) affine = nib.load(args.target_template).affine else: mni_space_img = nib.load(args.in_anat) affine = nib.load(args.in_anat).affine x_slice = int(mni_space_img.shape[0] / 2) y_slice = int(mni_space_img.shape[1] / 2) z_slice = int(mni_space_img.shape[2] / 2) slices_choice = (x_slice, y_slice, z_slice) subject_data = prepare_data_for_actors(args.in_bundle, args.in_anat, args.target_template) # Create actors from each dataset for Dipy sft, reference_data = subject_data streamlines = sft.streamlines volume_actor = actor.slicer(reference_data, affine=affine, opacity=args.anat_opacity, interpolation='nearest') if args.local_coloring: colors = [] for i in streamlines: local_color = np.gradient(i, axis=0) local_color = np.abs(local_color) local_color = (local_color.T / np.max(local_color, axis=1)).T colors.append(local_color) elif args.uniform_coloring: colors = (args.uniform_coloring[0] / 255.0, args.uniform_coloring[1] / 255.0, args.uniform_coloring[2] / 255.0) elif args.reference_coloring: sft.to_vox() streamlines_vox = sft.get_streamlines_copy() sft.to_rasmm() colors = [] normalized_data = reference_data / np.max(reference_data) cmap = plt.get_cmap(args.reference_coloring) for points in streamlines_vox: values = map_coordinates(normalized_data, points.T, order=1, mode='nearest') colors.append(cmap(values)[:, 0:3]) else: colors = None streamlines_actor = actor.line(streamlines, colors=colors, linewidth=0.2) # Take a snapshot of each dataset, camera settings are fixed for the # known template, won't work with another. if args.right: side_pos = (300, -10, 10) else: side_pos = (-300, 10, 10) display_slices(volume_actor, slices_choice, output_filenames_3d[0], 'sagittal', view_position=tuple([x for x in side_pos]), focal_point=tuple([x for x in (0, -10, 10)]), streamlines_actor=streamlines_actor) display_slices(volume_actor, slices_choice, output_filenames_3d[1], 'coronal', view_position=tuple([x for x in (0, -300, 15)]), focal_point=tuple([x for x in (0, 0, 15)]), streamlines_actor=streamlines_actor) display_slices(volume_actor, slices_choice, output_filenames_3d[2], 'axial', view_position=tuple([x for x in (0, -15, 350)]), focal_point=tuple([x for x in (0, -15, 0)]), streamlines_actor=streamlines_actor) plot_glass_brain(args, sft, mni_space_img, output_filenames_glass)
edges_colors = np.average(np.array(edges_colors), axis=1) ############################################################################### # Our data preparation is ready, it is time to visualize them all. We start to # build 2 actors that we represent our data : sphere_actor for the nodes and # lines_actor for the edges. sphere_actor = actor.sphere(centers=np.zeros(positions.shape), colors=colors, radii=radii * 0.5, theta=8, phi=8) lines_actor = actor.line(np.zeros((len(edges), 2, 3)), colors=edges_colors, lod=False, fake_tube=True, linewidth=3) ############################################################################### # Defining timer callback and layout iterator def new_layout_timer(showm, edges_list, vertices_count, max_iterations=1000, vertex_initial_positions=None): view_size = 500 viscosity = 0.10 alpha = 0.5
def qa_tractography(stream_path, qa_out_path, brain_path): """ Visualize the streamlines, then using window.record to get nine snapshots of the 3D streamslines. Parameters ---------- stream_path : str Path for the input streamline.trk file(s). qa_out_path_path : str Path for the output QA imgae file(s) brain_path : str Path for the reference brain scan, in order to get the scan volume. """ #Use window to visualize the streamlines r = window.renderer() #Load the streamline.trk file streamlines_mni_load = nib.streamlines.load(stream_path).streamlines streamlines_mni_in = Streamlines(streamlines_mni_load) streamlines_actor = actor.line( streamlines_mni_in, colormap.line_colors(streamlines_mni_in), lod_points=10000, depth_cue=True, linewidth=0.2, fake_tube=True, opacity=0.3, ) r.add(streamlines_actor) #window.show(r) showmng = window.ShowManager(r) #window.record function can rotate the 3D-image, then get the snapshot of the specific angle. window.record(r, cam_pos=(70.03, 64.97, 269.80), cam_view=(0, 1, 0), path_numbering=True, out_path=qa_out_path + '/Rotate_Z_axis_', az_ang=120, n_frames=3, reset_camera=True, size=(600, 600)) window.record(r, cam_pos=(70.03, 64.97, 269.80), cam_view=(1, 0, 0), path_numbering=True, out_path=qa_out_path + '/Rotate_Y_axis_', az_ang=120, n_frames=3, reset_camera=True, size=(600, 600)) window.record(r, cam_pos=(70.03, 64.97, 269.80), cam_view=(0, 0, 1), path_numbering=True, out_path=qa_out_path + '/Rotate_X_axis_', az_ang=120, n_frames=3, reset_camera=True, size=(600, 600)) showmng.exit() combine_plot(qa_out_path, brain_path)
} r_times = [p_data['earth_days'] for p_data in planets_data] ############################################################################## # Here we are calculating and updating the path/orbit before animation starts. planet_tracks = [ calculate_path(rplanet, rplanet * 85) for rplanet in r_planets ] ############################################################################## # This is for orbit visualization. We are using line actor for orbits. # After creating an actor we add it to the scene. orbit_actor = actor.line(planet_tracks, colors=(1, 1, 1), linewidth=0.1) scene.add(orbit_actor) ############################################################################## # Define the ``timer_callback`` function, which controls what events happen # at certain times, using the counter. Update the position of each planet # actor using ``update_planet_position,`` assigning the x and y values of # each planet's position with the newly calculated ones. def timer_callback(_obj, _event): cnt = next(counter) showm.render() # Rotating the sun actor rotate_axial(sun_actor, sun_data['earth_days'], 1)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.anat_reference]) assert_outputs_exist(parser, args, [args.output_name]) output_names = [ 'axial_superior', 'axial_inferior', 'coronal_posterior', 'coronal_anterior', 'sagittal_left', 'sagittal_right' ] list_of_bundles = [f for f in args.inputs] # output_dir: where temporary files will be created output_dir = os.path.dirname(args.output_name) # ----------------------------------------------------------------------- # # Mosaic, column 0: orientation names and data description # ----------------------------------------------------------------------- # width = args.resolution_of_thumbnails height = args.resolution_of_thumbnails rows = 6 cols = len(list_of_bundles) text_pos_x = 50 text_pos_y = 50 # Creates a new empty image, RGB mode mosaic = Image.new('RGB', ((cols + 1) * width, (rows + 1) * height)) # Prepare draw and font objects to render text draw = ImageDraw.Draw(mosaic) font = get_font(args) # Data of the image used as background ref_img = nib.load(args.anat_reference) data = ref_img.get_data() affine = ref_img.affine mean, std = data[data > 0].mean(), data[data > 0].std() value_range = (mean - 0.5 * std, mean + 1.5 * std) # First column with rows description draw_column_with_names(draw, output_names, text_pos_x, text_pos_y, height, font) # ----------------------------------------------------------------------- # # Columns with bundles # ----------------------------------------------------------------------- # for idx_bundle, bundle_file in enumerate(list_of_bundles): bundle_file_name = os.path.basename(bundle_file) bundle_name, _ = os.path.splitext(bundle_file_name) # !! It creates a temporary folder to create # the images to concatenate in the mosaic !! output_bundle_dir = os.path.join(output_dir, bundle_name) if not os.path.isdir(output_bundle_dir): os.makedirs(output_bundle_dir) output_paths = [ os.path.join(output_bundle_dir, '{}_' + os.path.basename(output_bundle_dir)).format(name) for name in output_names ] i = (idx_bundle + 1) * width if not os.path.isfile(bundle_file): print('\nInput file {} doesn\'t exist.'.format(bundle_file)) number_streamlines = 0 view_number = 6 j = height * view_number draw_bundle_information(draw, bundle_file_name, number_streamlines, i + text_pos_x, j + text_pos_y, font) else: # Select the streamlines to plot bundle_tractogram_file = nib.streamlines.load(bundle_file) streamlines = bundle_tractogram_file.streamlines tubes = actor.line(streamlines) number_streamlines = len(streamlines) # Render ren = window.Renderer() zoom = args.zoom opacity = args.opacity_background # Structural data slice_actor = actor.slicer(data, affine, value_range) slice_actor.opacity(opacity) ren.add(slice_actor) # Streamlines ren.add(tubes) ren.reset_camera() ren.zoom(zoom) view_number = 0 set_img_in_cell(mosaic, ren, view_number, output_paths[view_number], width, height, i) ren.pitch(180) ren.reset_camera() ren.zoom(zoom) view_number = 1 set_img_in_cell(mosaic, ren, view_number, output_paths[view_number], width, height, i) ren.rm(slice_actor) slice_actor2 = slice_actor.copy() slice_actor2.display(None, slice_actor2.shape[1] // 2, None) slice_actor2.opacity(opacity) ren.add(slice_actor2) ren.pitch(90) ren.set_camera(view_up=(0, 0, 1)) ren.reset_camera() ren.zoom(zoom) view_number = 2 set_img_in_cell(mosaic, ren, view_number, output_paths[view_number], width, height, i) ren.pitch(180) ren.set_camera(view_up=(0, 0, 1)) ren.reset_camera() ren.zoom(zoom) view_number = 3 set_img_in_cell(mosaic, ren, view_number, output_paths[view_number], width, height, i) ren.rm(slice_actor2) slice_actor3 = slice_actor.copy() slice_actor3.display(slice_actor3.shape[0] // 2, None, None) slice_actor3.opacity(opacity) ren.add(slice_actor3) ren.yaw(90) ren.reset_camera() ren.zoom(zoom) view_number = 4 set_img_in_cell(mosaic, ren, view_number, output_paths[view_number], width, height, i) ren.yaw(180) ren.reset_camera() ren.zoom(zoom) view_number = 5 set_img_in_cell(mosaic, ren, view_number, output_paths[view_number], width, height, i) view_number = 6 j = height * view_number draw_bundle_information(draw, bundle_file_name, number_streamlines, i + text_pos_x, j + text_pos_y, font) shutil.rmtree(output_bundle_dir) # Save image to file mosaic.save(args.output_name)
############################################################################### # Our data preparation is ready, it is time to visualize them all. We start to # build 2 actors that we represent our data : sphere_actor for the nodes and # lines_actor for the edges. sphere_actor = actor.sphere( centers=positions, colors=colors, radii=radii * 0.5, theta=8, phi=8, ) lines_actor = actor.line( edgesPositions, colors=edgesColors, opacity=0.1, ) ############################################################################### # All actors need to be added in a scene, so we build one and add our # lines_actor and sphere_actor. scene = window.Scene() scene.add(lines_actor) scene.add(sphere_actor) ############################################################################### # The final step ! Visualize and save the result of our creation! Please, # switch interactive variable to True if you want to visualize it.
# mesh_structure = mcds.get_mesh() # X_domain = np.unique(mesh_structure[0][0]) # Y_domain = np.unique(mesh_structure[1][0]) # Z_domain = np.unique(mesh_structure[2][0]) # dx = X_domain[1]-X_domain[0] # dy = Y_domain[1]-Y_domain[0] # dz = Z_domain[1]-Z_domain[0] # xlims = np.array([X_domain[0]-dx/2, X_domain[-1]+dx/2]) # ylims = np.array([Y_domain[0]-dy/2, Y_domain[-1]+dy/2]) # zlims = np.array([Z_domain[0]-dz/2, Z_domain[-1]+dz/2]) #Drawing Domain Boundaries lines = [np.array([[-2880.,-500.,-2880.],[2880.,-500.,-2880.],[2880.,500.,-2880.],[-2880.,500.,-2880.],[-2880.,-500.,-2880.],[-2880.,-500.,2880.],[-2880.,500.,2880.],[-2880.,500.,-2880.],[-2880.,500.,2880.],[2880.,500.,2880.],[2880.,500.,-2880.],[2880.,500.,-2880.],[2880.,-500.,-2880.],[2880.,-500.,2880.],[2880.,500.,2880.],[2880.,-500.,2880.],[-2880.,-500.,2880.]])] colors = np.array([0.5, 0.5, 0.5]) c = actor.line(lines, colors) scene.add(c) #Adding Dimension Labels x_label = actor.text_3d(text='x axis (micron)',position=(-750.0,-700.0,3000.0),font_size=200,justification='left') scene.add(x_label) y_label = actor.text_3d(text='y axis (micron)',position=(3000,0,3000.0),font_size=200,justification='left') scene.add(y_label) z_label = actor.text_3d(text='z axis (micron)',position=(3000,-700.0,0.0),font_size=200,justification='left') scene.add(z_label) #scene.add(actor.texture_on_sphere(image))