def get_polydata_lines(line_polydata): """Convert vtk polydata to a list of lines ndarrays. Parameters ---------- line_polydata : vtkPolyData Returns ------- lines : list List of N curves represented as 2D ndarrays """ lines_vertices = numpy_support.vtk_to_numpy( line_polydata.GetPoints().GetData()) lines_idx = numpy_support.vtk_to_numpy(line_polydata.GetLines().GetData()) lines = [] current_idx = 0 while current_idx < len(lines_idx): line_len = lines_idx[current_idx] next_idx = current_idx + line_len + 1 line_range = lines_idx[current_idx + 1:next_idx] lines += [lines_vertices[line_range]] current_idx = next_idx return lines
def _timer(_obj, _event): nonlocal counter, pos counter += 1 if (mode == 0): iterate(1) else: pos[:] += (np.random.random(pos.shape) - 0.5) * 1.5 spheres_positions = numpy_support.vtk_to_numpy( sphere_actor.GetMapper().GetInput().GetPoints().GetData()) spheres_positions[:] = sphere_geometry + \ np.repeat(pos, geometry_length, axis=0) edges_positions = numpy_support.vtk_to_numpy( lines_actor.GetMapper().GetInput().GetPoints().GetData()) edges_positions[::2] = pos[edges_list[:, 0]] edges_positions[1::2] = pos[edges_list[:, 1]] lines_actor.GetMapper().GetInput().GetPoints().GetData().Modified() lines_actor.GetMapper().GetInput().ComputeBounds() sphere_actor.GetMapper().GetInput().GetPoints().GetData().Modified() sphere_actor.GetMapper().GetInput().ComputeBounds() showm.scene.ResetCameraClippingRange() showm.render() if counter >= max_iterations: showm.exit()
def test_add_polydata_numeric_field(): my_polydata = PolyData() poly_field_data = my_polydata.GetFieldData() npt.assert_equal(poly_field_data.GetNumberOfArrays(), 0) bool_data = True add_polydata_numeric_field(my_polydata, 'Test Bool', bool_data) npt.assert_equal(poly_field_data.GetNumberOfArrays(), 1) npt.assert_equal( poly_field_data.GetArray('Test Bool').GetValue(0), bool_data) poly_field_data.RemoveArray('Test Bool') npt.assert_equal(poly_field_data.GetNumberOfArrays(), 0) int_data = 1 add_polydata_numeric_field(my_polydata, 'Test Int', int_data) npt.assert_equal(poly_field_data.GetNumberOfArrays(), 1) npt.assert_equal( poly_field_data.GetArray('Test Int').GetValue(0), int_data) poly_field_data.RemoveArray('Test Int') npt.assert_equal(poly_field_data.GetNumberOfArrays(), 0) float_data = .1 add_polydata_numeric_field(my_polydata, 'Test Float', float_data, array_type=VTK_FLOAT) npt.assert_equal(poly_field_data.GetNumberOfArrays(), 1) npt.assert_almost_equal( poly_field_data.GetArray('Test Float').GetValue(0), float_data) poly_field_data.RemoveArray('Test Float') npt.assert_equal(poly_field_data.GetNumberOfArrays(), 0) double_data = .1 add_polydata_numeric_field(my_polydata, 'Test Double', double_data, array_type=VTK_DOUBLE) npt.assert_equal(poly_field_data.GetNumberOfArrays(), 1) npt.assert_equal( poly_field_data.GetArray('Test Double').GetValue(0), double_data) poly_field_data.RemoveArray('Test Double') npt.assert_equal(poly_field_data.GetNumberOfArrays(), 0) array_data = [-1, 0, 1] add_polydata_numeric_field(my_polydata, 'Test Array', array_data) npt.assert_equal(poly_field_data.GetNumberOfArrays(), 1) npt.assert_equal( numpy_support.vtk_to_numpy(poly_field_data.GetArray('Test Array')), array_data) poly_field_data.RemoveArray('Test Array') npt.assert_equal(poly_field_data.GetNumberOfArrays(), 0) ndarray_data = np.array([[-.1, -.1], [0, 0], [.1, .1]]) add_polydata_numeric_field(my_polydata, 'Test NDArray', ndarray_data, array_type=VTK_FLOAT) npt.assert_equal(poly_field_data.GetNumberOfArrays(), 1) npt.assert_almost_equal( numpy_support.vtk_to_numpy(poly_field_data.GetArray('Test NDArray')), ndarray_data)
def test_save_and_load_polydata(): l_ext = ["vtk", "fib", "ply", "xml"] fname = "temp-io" for ext in l_ext: with InTemporaryDirectory() as odir: data = np.random.randint(0, 255, size=(50, 3)) pd = PolyData() pd.SetPoints(numpy_to_vtk_points(data)) fname_path = pjoin(odir, "{0}.{1}".format(fname, ext)) save_polydata(pd, fname_path) npt.assert_equal(os.path.isfile(fname_path), True) assert_greater(os.stat(fname_path).st_size, 0) out_pd = load_polydata(fname_path) out_data = numpy_support.vtk_to_numpy(out_pd.GetPoints().GetData()) npt.assert_array_equal(data, out_data) npt.assert_raises(IOError, save_polydata, PolyData(), "test.vti") npt.assert_raises(IOError, save_polydata, PolyData(), "test.obj") npt.assert_raises(IOError, load_polydata, "test.vti")
def select(self, disp_xy, sc, area=0): """Select multiple objects using display coordinates. Parameters ---------- disp_xy : tuple Display coordinates x, y. sc : Scene area : int or 2d tuple of ints Selection area around x, y coords. """ info_plus = {} self.hsel.SetRenderer(sc) if isinstance(area, int): picking_area = area, area else: picking_area = area try: self.hsel.SetArea(disp_xy[0] - picking_area[0], disp_xy[1] - picking_area[1], disp_xy[0] + picking_area[0], disp_xy[1] + picking_area[1]) res = self.hsel.Select() except OverflowError: return {0: {'node': None, 'vertex': None, 'face': None, 'actor': None}} num_nodes = res.GetNumberOfNodes() if num_nodes < 1: sel_node = None return {0: {'node': None, 'vertex': None, 'face': None, 'actor': None}} else: for i in range(num_nodes): sel_node = res.GetNode(i) info = {'node': None, 'vertex': None, 'face': None, 'actor': None} if sel_node is not None: selected_nodes = set( np.floor(numpy_support.vtk_to_numpy( sel_node.GetSelectionList())).astype(int)) info['node'] = sel_node info['actor'] = \ sel_node.GetProperties().Get(sel_node.PROP()) if self.selected_type == 'faces': info['face'] = list(selected_nodes) if self.selected_type == 'vertex': info['vertex'] = list(selected_nodes) info_plus[i] = info return info_plus
def test_attribute_to_actor(): cube = generate_cube_with_effect() test_arr = np.arange(24).reshape((8, 3)) attribute_to_actor(cube, test_arr, 'test_arr') arr = cube.GetMapper().GetInput().GetPointData().GetArray('test_arr') npt.assert_array_equal(test_arr, numpy_support.vtk_to_numpy(arr))
def test__points_to_vtk_cells(): points = np.array([[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) vtk_cells = _points_to_vtk_cells(points) actual = numpy_support.vtk_to_numpy(vtk_cells.GetData()) desired = [2, 0, 1, 2, 2, 3, 2, 4, 5] npt.assert_array_equal(actual, desired) npt.assert_equal(vtk_cells.GetNumberOfCells(), 3)
def test_tangents_to_actor(): my_actor = actor.square(np.array([[0, 0, 0]])) poly_point_data = my_actor.GetMapper().GetInput().GetPointData() npt.assert_equal(poly_point_data.HasArray('Tangents'), False) array = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]) tangents_to_actor(my_actor, array) npt.assert_equal(poly_point_data.HasArray('Tangents'), True) tangents = numpy_support.vtk_to_numpy(poly_point_data.GetArray('Tangents')) npt.assert_array_equal(tangents, array)
def get_all_atomic_positions(molecule): """Return an array of atomic coordinates corresponding to the atoms present in the molecule. Parameters ---------- molecule : Molecule The molecule whose atomic position array is to be obtained. """ return nps.vtk_to_numpy(molecule.GetAtomicPositionArray().GetData())
def get_all_bond_orders(molecule): """Return an array of integers containing the bond orders (single/double/ triple) corresponding to the bonds present in the molecule. Parameters ---------- molecule : Molecule The molecule whose bond types array is to be obtained. """ return nps.vtk_to_numpy(molecule.GetBondOrdersArray())
def get_all_atomic_numbers(molecule): """Return an array of atomic numbers corresponding to the atoms present in a given molecule. Parameters ---------- molecule : Molecule The molecule whose atomic number array is to be obtained. """ return nps.vtk_to_numpy(molecule.GetAtomicNumberArray())
def get_polydata_vertices(polydata): """Get vertices (ndarrays Nx3 int) from a vtk polydata. Parameters ---------- polydata : vtkPolyData Returns ------- output : array (N, 3) points, represented as 2D ndarrays """ return numpy_support.vtk_to_numpy(polydata.GetPoints().GetData())
def get_polydata_colors(polydata): """Get points color (ndarrays Nx3 int) from a vtk polydata. Parameters ---------- polydata : vtkPolyData Returns ------- output : array (N, 3) Colors. None if no normals in the vtk polydata. """ vtk_colors = polydata.GetPointData().GetScalars() if vtk_colors is None: return None return numpy_support.vtk_to_numpy(vtk_colors)
def get_polydata_triangles(polydata): """Get triangles (ndarrays Nx3 int) from a vtk polydata. Parameters ---------- polydata : vtkPolyData Returns ------- output : array (N, 3) triangles """ vtk_polys = numpy_support.vtk_to_numpy(polydata.GetPolys().GetData()) # test if its really triangles if not (vtk_polys[::4] == 3).all(): raise AssertionError("Shape error: this is not triangles") return np.vstack([vtk_polys[1::4], vtk_polys[2::4], vtk_polys[3::4]]).T
def get_polydata_tangents(polydata): """Get vertices tangent (ndarrays Nx3 int) from a vtk polydata. Parameters ---------- polydata : vtkPolyData Returns ------- output : array (N, 3) Tangents, represented as 2D ndarrays (Nx3). None if there are no tangents in the vtk polydata. """ vtk_tangents = polydata.GetPointData().GetTangents() if vtk_tangents is None: return None return numpy_support.vtk_to_numpy(vtk_tangents)
def test_numpy_to_vtk_image_data(): array = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[21, 22, 23], [24, 25, 26]], [[27, 28, 29], [210, 211, 212]]]) # converting numpy array to vtk_image_data vtk_image_data = utils.numpy_to_vtk_image_data(array) # extracting the image data from vtk_image_data w, h, depth = vtk_image_data.GetDimensions() vtk_img_array = vtk_image_data.GetPointData().GetScalars() elements = vtk_img_array.GetNumberOfComponents() # converting vtk array to numpy array numpy_img_array = numpy_support.vtk_to_numpy(vtk_img_array) npt.assert_equal(np.flipud(array), numpy_img_array.reshape(h, w, elements)) npt.assert_raises(IOError, utils.numpy_to_vtk_image_data, np.array([1, 2, 3]))
def vertices_from_actor(actor, as_vtk=False): """Access to vertices from actor. Parameters ---------- actor : actor as_vtk: bool, optional by default, ndarray is returned. Returns ------- vertices : ndarray """ vtk_array = actor.GetMapper().GetInput().GetPoints().GetData() if as_vtk: return vtk_array return numpy_support.vtk_to_numpy(vtk_array)
def test_save_and_load_options(): l_ext = ["ply", "vtk"] l_options = [{ 'color_array_name': 'horizon', }, { 'binary': True, }] fname = "temp-io" for ext, option in zip(l_ext, l_options): with InTemporaryDirectory() as odir: data = np.random.randint(0, 255, size=(50, 3)) pd = PolyData() pd.SetPoints(numpy_to_vtk_points(data)) fname_path = pjoin(odir, "{0}.{1}".format(fname, ext)) save_polydata(pd, fname_path, **option) npt.assert_equal(os.path.isfile(fname_path), True) assert_greater(os.stat(fname_path).st_size, 0) out_pd = load_polydata(fname_path) out_data = numpy_support.vtk_to_numpy(out_pd.GetPoints().GetData()) npt.assert_array_equal(data, out_data) l_ext = ["vtk", "vtp", "ply", "stl", "mni.obj"] l_options = [{}, { 'binary': False, }] for ext, option in zip(l_ext, l_options): with InTemporaryDirectory() as odir: data = np.random.randint(0, 255, size=(50, 3)) pd = PolyData() pd.SetPoints(numpy_to_vtk_points(data)) fname_path = pjoin(odir, "{0}.{1}".format(fname, ext)) save_polydata(pd, fname_path, **option) npt.assert_equal(os.path.isfile(fname_path), True) assert_greater(os.stat(fname_path).st_size, 0)
def test_update_surface_actor_colors(): x = np.linspace(-1, 1, 20) y = np.linspace(-1, 1, 20) x, y = np.meshgrid(x, y) x = x.reshape(-1) y = y.reshape(-1) z = x**2 + y**2 colors = np.array([[0.2, 0.4, 0.8]] * 400) xyz = np.vstack([x, y, z]).T act = actor.surface(xyz) update_surface_actor_colors(act, colors) # Multiplying colors by 255 to convert them into RGB format used by VTK. colors *= 255 # colors obtained from the surface surface_colors = numpy_support.vtk_to_numpy( act.GetMapper().GetInput().GetPointData().GetScalars()) # Checking if the colors passed to the function and colors assigned are # same. npt.assert_equal(colors, surface_colors)
def array_from_actor(actor, array_name, as_vtk=False): """Access array from actor which uses polydata. Parameters ---------- actor : actor array_name: str as_vtk_type: bool, optional by default, ndarray is returned. Returns ------- output : array (N, 3) """ vtk_array = \ actor.GetMapper().GetInput().GetPointData().GetArray(array_name) if vtk_array is None: return None if as_vtk: return vtk_array return numpy_support.vtk_to_numpy(vtk_array)
def get_polydata_field(polydata, field_name, as_vtk=False): """Get a field from a vtk polydata. Parameters ---------- polydata : vtkPolyData field_name : str as_vtk : optional By default, ndarray is returned. Returns ------- output : ndarray or vtkDataArray Field data. The return type depends on the value of the as_vtk parameter. None if the field is not found. """ vtk_field_data = polydata.GetFieldData().GetArray(field_name) if vtk_field_data is None: return None if as_vtk: return vtk_field_data return numpy_support.vtk_to_numpy(vtk_field_data)
def test__peaks_colors_from_points(): points = np.array([[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) colors_tuple = _peaks_colors_from_points(points, colors=None) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, 1) colors_tuple = _peaks_colors_from_points(points, colors='rgb_standard') vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, 1) colors_tuple = _peaks_colors_from_points(points, colors=(0, 1, 0)) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, 1) colors_tuple = _peaks_colors_from_points(points, colors=(0, 1, 0, .1)) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[0, 255, 0, 25], [0, 255, 0, 25], [0, 255, 0, 25], [0, 255, 0, 25], [0, 255, 0, 25], [0, 255, 0, 25]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, -1) colors = [.3, .6, 1] colors_tuple = _peaks_colors_from_points(points, colors=colors) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [.3, .3, .6, .6, 1, 1] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, True) npt.assert_equal(global_opacity, 1) colors = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] colors_tuple = _peaks_colors_from_points(points, colors=colors) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[255, 0, 0], [255, 0, 0], [0, 255, 0], [0, 255, 0], [0, 0, 255], [0, 0, 255]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, 1) colors = [[1, 0, 0, .1], [0, 1, 0, .1], [0, 0, 1, .1]] colors_tuple = _peaks_colors_from_points(points, colors=colors) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[255, 0, 0, 25], [255, 0, 0, 25], [0, 255, 0, 25], [0, 255, 0, 25], [0, 0, 255, 25], [0, 0, 255, 25]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, -1) colors = [.5, .6, .7, .8, .9, 1] colors_tuple = _peaks_colors_from_points(points, colors=colors) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [.5, .6, .7, .8, .9, 1] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, True) npt.assert_equal(global_opacity, 1) colors = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1]] colors_tuple = _peaks_colors_from_points(points, colors=colors) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [255, 0, 255], [0, 255, 255]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, 1) colors = [[1, 0, 0, .1], [0, 1, 0, .1], [0, 0, 1, .1], [1, 1, 0, .1], [1, 0, 1, .1], [0, 1, 1, .1]] colors_tuple = _peaks_colors_from_points(points, colors=colors) vtk_colors, colors_are_scalars, global_opacity = colors_tuple desired = [[255, 0, 0, 25], [0, 255, 0, 25], [0, 0, 255, 25], [255, 255, 0, 25], [255, 0, 255, 25], [0, 255, 255, 25]] npt.assert_array_equal(numpy_support.vtk_to_numpy(vtk_colors), desired) npt.assert_equal(colors_are_scalars, False) npt.assert_equal(global_opacity, -1)
def snapshot(scene, fname=None, size=(300, 300), offscreen=True, order_transparent=False, stereo='off', multi_samples=8, max_peels=4, occlusion_ratio=0.0): """Save a snapshot of the scene in a file or in memory. Parameters ----------- scene : Scene() or vtkRenderer Scene instance fname : str or None Save PNG file. If None return only an array without saving PNG. size : (int, int) ``(width, height)`` of the window. Default is (300, 300). offscreen : bool Default True. Go stealth mode no window should appear. order_transparent : bool Default False. Use depth peeling to sort transparent objects. If True also enables anti-aliasing. stereo: string Set the stereo type. Default is 'off'. Other types include: * 'opengl': OpenGL frame-sequential stereo. Referred to as 'CrystalEyes' by VTK. * 'anaglyph': For use with red/blue glasses. See VTK docs to use different colors. * 'interlaced': Line interlaced. * 'checkerboard': Checkerboard interlaced. * 'left': Left eye only. * 'right': Right eye only. * 'horizontal': Side-by-side. multi_samples : int Number of samples for anti-aliazing (Default 8). For no anti-aliasing use 0. max_peels : int Maximum number of peels for depth peeling (Default 4). occlusion_ratio : float Occlusion ration for depth peeling (Default 0 - exact image). Returns ------- arr : ndarray Color array of size (width, height, 3) where the last dimension holds the RGB values. """ width, height = size render_window = RenderWindow() if offscreen: render_window.SetOffScreenRendering(1) if stereo.lower() != 'off': enable_stereo(render_window, stereo) render_window.AddRenderer(scene) render_window.SetSize(width, height) if order_transparent: antialiasing(scene, render_window, multi_samples, max_peels, occlusion_ratio) render_window.Render() window_to_image_filter = WindowToImageFilter() window_to_image_filter.SetInput(render_window) window_to_image_filter.Update() vtk_image = window_to_image_filter.GetOutput() h, w, _ = vtk_image.GetDimensions() vtk_array = vtk_image.GetPointData().GetScalars() components = vtk_array.GetNumberOfComponents() arr = numpy_support.vtk_to_numpy(vtk_array).reshape(w, h, components) if fname is None: return arr save_image(arr, fname) return arr
def run(self, input_files, cluster=False, cluster_thr=15., random_colors=None, length_gt=0, length_lt=1000, clusters_gt=0, clusters_lt=10**8, native_coords=False, stealth=False, emergency_header='icbm_2009a', bg_color=(0, 0, 0), disable_order_transparency=False, buan=False, buan_thr=0.5, buan_highlight=(1, 0, 0), roi_images=False, roi_colors=(1, 0, 0), out_dir='', out_stealth_png='tmp.png'): """ Interactive medical visualization - Invert the Horizon! Interact with any number of .trk, .tck or .dpy tractograms and anatomy files .nii or .nii.gz. Cluster streamlines on loading. Parameters ---------- input_files : variable string cluster : bool, optional Enable QuickBundlesX clustering. cluster_thr : float, optional Distance threshold used for clustering. Default value 15.0 for small animal brains you may need to use something smaller such as 2.0. The distance is in mm. For this parameter to be active ``cluster`` should be enabled. random_colors : variable str, optional Given multiple tractograms and/or ROIs then each tractogram and/or ROI will be shown with different color. If no value is provided, both the tractograms and the ROIs will have a different random color generated from a distinguishable colormap. If the effect should only be applied to one of the 2 types, then use the options 'tracts' and 'rois' for the tractograms and the ROIs respectively. length_gt : float, optional Clusters with average length greater than ``length_gt`` amount in mm will be shown. length_lt : float, optional Clusters with average length less than ``length_lt`` amount in mm will be shown. clusters_gt : int, optional Clusters with size greater than ``clusters_gt`` will be shown. clusters_lt : int, optional Clusters with size less than ``clusters_gt`` will be shown. native_coords : bool, optional Show results in native coordinates. stealth : bool, optional Do not use interactive mode just save figure. emergency_header : str, optional If no anatomy reference is provided an emergency header is provided. Current options 'icbm_2009a' and 'icbm_2009c'. bg_color : variable float, optional Define the background color of the scene. Colors can be defined with 1 or 3 values and should be between [0-1]. disable_order_transparency : bool, optional Use depth peeling to sort transparent objects. If True also enables anti-aliasing. buan : bool, optional Enables BUAN framework visualization. buan_thr : float, optional Uses the threshold value to highlight segments on the bundle which have pvalues less than this threshold. buan_highlight : variable float, optional Define the bundle highlight area color. Colors can be defined with 1 or 3 values and should be between [0-1]. For example, a value of (1, 0, 0) would mean the red color. roi_images : bool, optional Displays binary images as contours. roi_colors : variable float, optional Define the color for the roi images. Colors can be defined with 1 or 3 values and should be between [0-1]. For example, a value of (1, 0, 0) would mean the red color. out_dir : str, optional Output directory. (default current directory) out_stealth_png : str, optional Filename of saved picture. References ---------- .. [Horizon_ISMRM19] Garyfallidis E., M-A. Cote, B.Q. Chandio, S. Fadnavis, J. Guaje, R. Aggarwal, E. St-Onge, K.S. Juneja, S. Koudoro, D. Reagan, DIPY Horizon: fast, modular, unified and adaptive visualization, Proceedings of: International Society of Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019. """ verbose = True tractograms = [] images = [] pams = [] numpy_files = [] interactive = not stealth world_coords = not native_coords bundle_colors = None mni_2009a = {} mni_2009a['affine'] = np.array([[1., 0., 0., -98.], [0., 1., 0., -134.], [0., 0., 1., -72.], [0., 0., 0., 1.]]) mni_2009a['dims'] = (197, 233, 189) mni_2009a['vox_size'] = (1., 1., 1.) mni_2009a['vox_space'] = 'RAS' mni_2009c = {} mni_2009c['affine'] = np.array([[1., 0., 0., -96.], [0., 1., 0., -132.], [0., 0., 1., -78.], [0., 0., 0., 1.]]) mni_2009c['dims'] = (193, 229, 193) mni_2009c['vox_size'] = (1., 1., 1.) mni_2009c['vox_space'] = 'RAS' if emergency_header == 'icbm_2009a': hdr = mni_2009c else: hdr = mni_2009c emergency_ref = create_nifti_header(hdr['affine'], hdr['dims'], hdr['vox_size']) io_it = self.get_io_iterator() for input_output in io_it: fname = input_output[0] if verbose: print('Loading file ...') print(fname) print('\n') fl = fname.lower() ends = fl.endswith if ends('.trk'): sft = load_tractogram(fname, 'same', bbox_valid_check=False) tractograms.append(sft) if ends('.dpy') or ends('.tck'): sft = load_tractogram(fname, emergency_ref) tractograms.append(sft) if ends('.nii.gz') or ends('.nii'): data, affine = load_nifti(fname) images.append((data, affine)) if verbose: print('Affine to RAS') np.set_printoptions(3, suppress=True) print(affine) np.set_printoptions() if ends(".pam5"): pam = load_peaks(fname) pams.append(pam) if verbose: print('Peak_dirs shape') print(pam.peak_dirs.shape) if ends(".npy"): data = np.load(fname) numpy_files.append(data) if verbose: print('numpy array length') print(len(data)) if buan: bundle_colors = [] for i in range(len(numpy_files)): n = len(numpy_files[i]) pvalues = numpy_files[i] bundle = tractograms[i].streamlines indx = assignment_map(bundle, bundle, n) ind = np.array(indx) nb_lines = len(bundle) lines_range = range(nb_lines) points_per_line = [len(bundle[i]) for i in lines_range] points_per_line = np.array(points_per_line, np.intp) cols_arr = line_colors(bundle) colors_mapper = np.repeat(lines_range, points_per_line, axis=0) vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper]) colors = numpy_support.vtk_to_numpy(vtk_colors) colors = (colors - np.min(colors)) / np.ptp(colors) for i in range(n): if pvalues[i] < buan_thr: colors[ind == i] = buan_highlight bundle_colors.append(colors) if len(bg_color) == 1: bg_color *= 3 elif len(bg_color) != 3: raise ValueError('You need 3 values to set up background color. ' 'e.g --bg_color 0.5 0.5 0.5') if len(roi_colors) == 1: roi_colors *= 3 elif len(roi_colors) != 3: raise ValueError('You need 3 values to set up ROI color. ' 'e.g. --roi_colors 0.5 0.5 0.5') order_transparent = not disable_order_transparency horizon(tractograms=tractograms, images=images, pams=pams, cluster=cluster, cluster_thr=cluster_thr, random_colors=random_colors, bg_color=bg_color, order_transparent=order_transparent, length_gt=length_gt, length_lt=length_lt, clusters_gt=clusters_gt, clusters_lt=clusters_lt, world_coords=world_coords, interactive=interactive, buan=buan, buan_colors=bundle_colors, roi_images=roi_images, roi_colors=roi_colors, out_png=pjoin(out_dir, out_stealth_png))
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 a = 0.0005 b = 1.0 deltaT = 1.0 sphere_geometry = np.array( numpy_support.vtk_to_numpy( sphere_actor.GetMapper().GetInput().GetPoints().GetData())) geometry_length = sphere_geometry.shape[0] / vertices_count if (vertex_initial_positions is not None): pos = np.array(vertex_initial_positions) else: pos = view_size * \ np.random.random((vertices_count, 3)) - view_size / 2.0 velocities = np.zeros((vertices_count, 3)) def iterate(iterationCount): nonlocal pos, velocities for _ in range(iterationCount): forces = np.zeros((vertices_count, 3)) # repulstive forces for vertex1 in range(vertices_count): for vertex2 in range(vertex1): x1, y1, z1 = pos[vertex1] x2, y2, z2 = pos[vertex2] distance = math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1)) + alpha rx = (x2 - x1) / distance ry = (y2 - y1) / distance rz = (z2 - z1) / distance Fx = -b * rx / distance / distance Fy = -b * ry / distance / distance Fz = -b * rz / distance / distance forces[vertex1] += np.array([Fx, Fy, Fz]) forces[vertex2] -= np.array([Fx, Fy, Fz]) # attractive forces for vFrom, vTo in edges_list: if (vFrom == vTo): continue x1, y1, z1 = pos[vFrom] x2, y2, z2 = pos[vTo] distance = math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1)) Rx = (x2 - x1) Ry = (y2 - y1) Rz = (z2 - z1) Fx = a * Rx * distance Fy = a * Ry * distance Fz = a * Rz * distance forces[vFrom] += np.array([Fx, Fy, Fz]) forces[vTo] -= np.array([Fx, Fy, Fz]) velocities += forces * deltaT velocities *= (1.0 - viscosity) pos += velocities * deltaT pos[:, 0] -= np.mean(pos[:, 0]) pos[:, 1] -= np.mean(pos[:, 1]) pos[:, 2] -= np.mean(pos[:, 2]) counter = 0 def _timer(_obj, _event): nonlocal counter, pos counter += 1 if (mode == 0): iterate(1) else: pos[:] += (np.random.random(pos.shape) - 0.5) * 1.5 spheres_positions = numpy_support.vtk_to_numpy( sphere_actor.GetMapper().GetInput().GetPoints().GetData()) spheres_positions[:] = sphere_geometry + \ np.repeat(pos, geometry_length, axis=0) edges_positions = numpy_support.vtk_to_numpy( lines_actor.GetMapper().GetInput().GetPoints().GetData()) edges_positions[::2] = pos[edges_list[:, 0]] edges_positions[1::2] = pos[edges_list[:, 1]] lines_actor.GetMapper().GetInput().GetPoints().GetData().Modified() lines_actor.GetMapper().GetInput().ComputeBounds() sphere_actor.GetMapper().GetInput().GetPoints().GetData().Modified() sphere_actor.GetMapper().GetInput().ComputeBounds() showm.scene.ResetCameraClippingRange() showm.render() if counter >= max_iterations: showm.exit() return _timer
def record(scene=None, cam_pos=None, cam_focal=None, cam_view=None, out_path=None, path_numbering=False, n_frames=1, az_ang=10, magnification=1, size=(300, 300), reset_camera=True, screen_clip=False, stereo='off', verbose=False): """Record a video of your scene. Records a video as a series of ``.png`` files of your scene by rotating the azimuth angle az_angle in every frame. Parameters ----------- scene : Scene() or vtkRenderer() object Scene instance cam_pos : None or sequence (3,), optional Camera's position. If None then default camera's position is used. cam_focal : None or sequence (3,), optional Camera's focal point. If None then default camera's focal point is used. cam_view : None or sequence (3,), optional Camera's view up direction. If None then default camera's view up vector is used. out_path : str, optional Output path for the frames. If None a default fury.png is created. path_numbering : bool When recording it changes out_path to out_path + str(frame number) n_frames : int, optional Number of frames to save, default 1 az_ang : float, optional Azimuthal angle of camera rotation. magnification : int, optional How much to magnify the saved frame. Default is 1. A value greater than 1 increases the quality of the image. However, the output size will be larger. For example, 200x200 image with magnification of 2 will be a 400x400 image. size : (int, int) ``(width, height)`` of the window. Default is (300, 300). screen_clip: bool Clip the png based on screen resolution. Default is False. reset_camera : bool If True Call ``scene.reset_camera()``. Otherwise you need to set the camera before calling this function. stereo: string Set the stereo type. Default is 'off'. Other types include: * 'opengl': OpenGL frame-sequential stereo. Referred to as 'CrystalEyes' by VTK. * 'anaglyph': For use with red/blue glasses. See VTK docs to use different colors. * 'interlaced': Line interlaced. * 'checkerboard': Checkerboard interlaced. * 'left': Left eye only. * 'right': Right eye only. * 'horizontal': Side-by-side. verbose : bool print information about the camera. Default is False. Examples --------- >>> from fury import window, actor >>> scene = window.Scene() >>> a = actor.axes() >>> scene.add(a) >>> # uncomment below to record >>> # window.record(scene) >>> # check for new images in current directory """ if scene is None: scene = Scene() renWin = RenderWindow() renWin.SetOffScreenRendering(1) renWin.SetBorders(screen_clip) renWin.AddRenderer(scene) renWin.SetSize(size[0], size[1]) iren = RenderWindowInteractor() iren.SetRenderWindow(renWin) # scene.GetActiveCamera().Azimuth(180) if reset_camera: scene.ResetCamera() if stereo.lower() != 'off': enable_stereo(renWin, stereo) renderLarge = RenderLargeImage() renderLarge.SetInput(scene) renderLarge.SetMagnification(magnification) renderLarge.Update() ang = 0 if cam_pos is not None: cx, cy, cz = cam_pos scene.GetActiveCamera().SetPosition(cx, cy, cz) if cam_focal is not None: fx, fy, fz = cam_focal scene.GetActiveCamera().SetFocalPoint(fx, fy, fz) if cam_view is not None: ux, uy, uz = cam_view scene.GetActiveCamera().SetViewUp(ux, uy, uz) cam = scene.GetActiveCamera() if verbose: print('Camera Position (%.2f, %.2f, %.2f)' % cam.GetPosition()) print('Camera Focal Point (%.2f, %.2f, %.2f)' % cam.GetFocalPoint()) print('Camera View Up (%.2f, %.2f, %.2f)' % cam.GetViewUp()) for i in range(n_frames): scene.GetActiveCamera().Azimuth(ang) renderLarge = RenderLargeImage() renderLarge.SetInput(scene) renderLarge.SetMagnification(magnification) renderLarge.Update() if path_numbering: if out_path is None: filename = str(i).zfill(6) + '.png' else: filename = out_path + str(i).zfill(6) + '.png' else: if out_path is None: filename = 'fury.png' else: filename = out_path arr = numpy_support.vtk_to_numpy(renderLarge.GetOutput().GetPointData() .GetScalars()) w, h, _ = renderLarge.GetOutput().GetDimensions() components = renderLarge.GetOutput().GetNumberOfScalarComponents() arr = arr.reshape((h, w, components)) save_image(arr, filename) ang = +az_ang
def load_image(filename, as_vtktype=False, use_pillow=True): """Load an image. Parameters ---------- filename: str should be png, bmp, jpeg or jpg files as_vtktype: bool, optional if True, return vtk output otherwise an ndarray. Default False. use_pillow: bool, optional Use pillow python library to load the files. Default True Returns ------- image: ndarray or vtk output desired image array """ is_url = filename.lower().startswith('http://') \ or filename.lower().startswith('https://') if is_url: image_name = os.path.basename(filename) if len(image_name.split('.')) < 2: raise IOError(f'{filename} is not a valid image URL') urlretrieve(filename, image_name) filename = image_name if use_pillow: with Image.open(filename) as pil_image: if pil_image.mode in ['RGBA', 'RGB', 'L']: image = np.asarray(pil_image) elif pil_image.mode.startswith('I;16'): raw = pil_image.tobytes('raw', pil_image.mode) dtype = '>u2' if pil_image.mode.endswith('B') else '<u2' image = np.frombuffer(raw, dtype=dtype) image.reshape(pil_image.size[::-1]).astype('=u2') else: try: image = pil_image.convert('RGBA') except ValueError: raise RuntimeError('Unknown image mode {}'.format( pil_image.mode)) image = np.asarray(pil_image) image = np.flipud(image) if as_vtktype: if image.ndim not in [2, 3]: raise IOError("only 2D (L, RGB, RGBA) or 3D image available") vtk_image = ImageData() depth = 1 if image.ndim == 2 else image.shape[2] # width, height vtk_image.SetDimensions(image.shape[1], image.shape[0], depth) vtk_image.SetExtent(0, image.shape[1] - 1, 0, image.shape[0] - 1, 0, 0) vtk_image.SetSpacing(1.0, 1.0, 1.0) vtk_image.SetOrigin(0.0, 0.0, 0.0) image = image.reshape(image.shape[1] * image.shape[0], depth) image = np.ascontiguousarray(image, dtype=image.dtype) vtk_array_type = numpy_support.get_vtk_array_type(image.dtype) uchar_array = numpy_support.numpy_to_vtk(image, deep=True, array_type=vtk_array_type) vtk_image.GetPointData().SetScalars(uchar_array) image = vtk_image if is_url: os.remove(filename) return image d_reader = { ".png": PNGReader, ".bmp": BMPReader, ".jpeg": JPEGReader, ".jpg": JPEGReader, ".tiff": TIFFReader, ".tif": TIFFReader } extension = os.path.splitext(os.path.basename(filename).lower())[1] if extension.lower() not in d_reader.keys(): raise IOError( "Impossible to read the file {0}: Unknown extension {1}".format( filename, extension)) reader = d_reader.get(extension)() reader.SetFileName(filename) reader.Update() reader.GetOutput().GetPointData().GetArray(0).SetName("original") if not as_vtktype: w, h, _ = reader.GetOutput().GetDimensions() vtk_array = reader.GetOutput().GetPointData().GetScalars() components = vtk_array.GetNumberOfComponents() image = numpy_support.vtk_to_numpy(vtk_array).reshape(h, w, components) if is_url: os.remove(filename) return reader.GetOutput() if as_vtktype else image