def plot_text(self, label, X, text, size=1): view = mlab.view() roll = mlab.roll() self.figure.scene.disable_render = True scale = (size, size, size) mlab_objs = self.plots.get(label) if mlab_objs != None: if len(mlab_objs) != len(text): for obj in mlab_objs: obj.remove() self.plots.pop(label) mlab_objs = self.plots.get(label) if mlab_objs == None: text_objs = [] for x, t in zip(X, text): text_objs.append(mlab.text3d(x[0], x[1], x[2], str(t), scale=scale)) self.plots[label] = text_objs elif len(mlab_objs) == len(text): for i, obj in enumerate(mlab_objs): obj.position = X[i,:] obj.text = str(text[i]) obj.scale = scale else: print "HELP, I shouldn\'t be here!!!!!" self.figure.scene.disable_render = False mlab.view(*view) mlab.roll(roll)
def __view(self, viewargs=None, roll=None): """Wrapper for mlab.view() Parameters ---------- viewargs: dict mapping with keys corresponding to mlab.view args roll: num int or float to set camera roll Returns ------- camera settings: tuple view settings, roll setting """ try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab if viewargs: viewargs['reset_roll'] = True mlab.view(**viewargs) if not roll is None: mlab.roll(roll) return mlab.view(), mlab.roll()
def setup(): sc = mlab.figure(0) mlab.view(90., -90., 3.) mlab.roll(90.) arm = Arm() neuron = Neuron(arm) return neuron, arm
def plot_text(self, label, X, text, size=1): view = mlab.view() roll = mlab.roll() self.figure.scene.disable_render = True scale = (size, size, size) mlab_objs = self.plots.get(label) if mlab_objs != None: if len(mlab_objs) != len(text): for obj in mlab_objs: obj.remove() self.plots.pop(label) mlab_objs = self.plots.get(label) if mlab_objs == None: text_objs = [] for x, t in zip(X, text): text_objs.append( mlab.text3d(x[0], x[1], x[2], str(t), scale=scale)) self.plots[label] = text_objs elif len(mlab_objs) == len(text): for i, obj in enumerate(mlab_objs): obj.position = X[i, :] obj.text = str(text[i]) obj.scale = scale else: print "HELP, I shouldn\'t be here!!!!!" self.figure.scene.disable_render = False mlab.view(*view) mlab.roll(roll)
def plot_points(self, label, X, color=None, size=None, mode=None): mlab.figure(self.figure.name) if color==None: color=(1,0,0) if size == None and mode == None or size == 0: size = 1 mode = 'point' if size == None: size = 1 if mode==None: mode='sphere' if isinstance(X, list): X = numpy.array(X) if len(X.shape) == 1: X = numpy.array([X]) mlab_obj = self.plots.get(label) if mlab_obj == None: if isinstance(color, tuple): self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color=color, scale_factor=size, mode=mode) else: self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color, scale_factor=size, scale_mode='none', mode=mode) else: self.figure.scene.disable_render = True view = mlab.view() roll = mlab.roll() ### Commented out since VTK gives an error when using mlab_source.set #~ if X.shape[0] == mlab_obj.mlab_source.x.shape[0]: #~ if isinstance(color, tuple): #~ mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2]) #~ mlab_obj.actor.property.color = color #~ else: #~ mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2], scalars=color) #~ #~ #~ else: #~ self.clear(label) #~ if isinstance(color, tuple): #~ self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color=color, scale_factor=size, mode=mode) #~ else: #~ self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color, scale_factor=size, scale_mode='none', mode=mode) self.clear(label) if isinstance(color, tuple): self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color=color, scale_factor=size, mode=mode) else: self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color, scale_factor=size, scale_mode='none', mode=mode) mlab.view(*view) mlab.roll(roll) self.figure.scene.disable_render = False
def autoPositionCamera(): """ Set camera position looking along the x-axis. """ s = mlab.gcf().scene s.disable_render = True mlab.view(90,90,distance='auto',focalpoint='auto') mlab.roll(0) s.disable_render = False
def autoPositionCamera(): """ Set camera position looking along the x-axis. """ s = mlab.gcf().scene s.disable_render = True mlab.view(90, 90, distance='auto', focalpoint='auto') mlab.roll(0) s.disable_render = False
def draw_dots3d(dots, edges, fignum, clear=True, title='', size=(1024, 768), graph_colormap='viridis', bgcolor=(1, 1, 1), node_color=(0.3, 0.65, 0.3), node_size=0.01, edge_color=(0.3, 0.3, 0.9), edge_size=0.003, text_size=0.14, text_color=(0, 0, 0), text_coords=[0.84, 0.75], text={}, title_size=0.3, angle=get_ra()): # https://stackoverflow.com/questions/17751552/drawing-multiplex-graphs-with-networkx # numpy array of x, y, z positions in sorted node order xyz = shrink_to_3d(dots) if fignum == 0: mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size) # Mayavi is buggy, and following code causes sockets leak. #if mlab.options.offscreen: # mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size) #elif fignum == 0: # mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size) if clear: mlab.clf() # the x,y, and z co-ordinates are here # manipulate them to obtain the desired projection perspective pts = mlab.points3d(xyz[:, 0], xyz[:, 1], xyz[:, 2], scale_factor=node_size, scale_mode='none', color=node_color, #colormap=graph_colormap, resolution=20, transparent=False) mlab.text(text_coords[0], text_coords[1], '\n'.join(['{} = {}'.format(n, v) for n, v in text.items()]), width=text_size) if clear: mlab.title(title, height=0.95) mlab.roll(next(angle)) mlab.orientation_axes(pts) mlab.outline(pts) """ for i, (x, y, z) in enumerate(xyz): label = mlab.text(x, y, str(i), z=z, width=text_size, name=str(i), color=text_color) label.property.shadow = True """ pts.mlab_source.dataset.lines = edges tube = mlab.pipeline.tube(pts, tube_radius=edge_size) mlab.pipeline.surface(tube, color=edge_color)
def plot_paths(list_of_electrons): """Plots paths of all the electrons using Mayavi 3D image package Args: list_of_electrons: A list/array of electron class instances. """ N = len(list_of_electrons[0].list_t) # number of points per line from mayavi import mlab mlab.figure(1, size=(400, 400), bgcolor=(0, 0, 0)) mlab.clf() x_positions, y_positions, z_positions = list(), list(), list( ) # Create lists of coordinate positions timestamps, connections = list(), list( ) # Create lists of coordinate connections index = 0 # The index of the current point in the total amount of points for i in range( len(list_of_electrons)): # Create each line one after the other x_positions.append(np.asarray(list_of_electrons[i].list_x)) y_positions.append(np.asarray(list_of_electrons[i].list_y)) z_positions.append(np.asarray(list_of_electrons[i].list_z)) timestamps.append(np.asarray(list_of_electrons[i].list_t)) """This is the tricky part: in a line, each point is connected to the one following it. We have to express this with the indices of the final set of points once all lines have been combined together, this is why we need to keep track of the total number of points already created (index). """ connections.append( np.vstack( # Collapse them in one array before plotting [ np.arange(index, index + N - 1.5), np.arange(index + 1, index + N - .5) ]).T) index += N # Now collapse all positions, scalars and connections in big arrays x_positions, y_positions, z_positions = np.hstack(x_positions), np.hstack( y_positions), np.hstack(z_positions) timestamps, connections = np.hstack(timestamps), np.vstack(connections) src = mlab.pipeline.scalar_scatter(x_positions, y_positions, z_positions, timestamps) # Create the points src.mlab_source.dataset.lines = connections # Connect them src.update() # Connect them lines = mlab.pipeline.tube( src, tube_radius=0.005, tube_sides=6) # The stripper filter cleans up connected lines mlab.pipeline.surface(lines, colormap='Accent', line_width=1, opacity=.4) # Finally, display the set of lines mlab.view(elevation=0) # And choose a nice view mlab.roll(125) # Again, choose a nice view mlab.show()
def anim(): global bondcolors while True: print mlab.view(), mlab.roll() bondcolors[:] = bondcolors * .5 bondsrc.update() yield
def save_fig_by_data(data, path_to_save, vmin=None, vmax=None): mlab.figure(bgcolor=(1, 1, 1), size=(800, 600)) mlab.view(azimuth=0, elevation=0, distance=10) # yaw the camera (tilt left-right) y # pitch the camera (tilt up-down) z # roll control the absolute roll angle of the camera x mlab.yaw(90) mlab.pitch(80) mlab.roll(-10) if vmax is None: volume(scalar_field(np.absolute(data))) else: volume(scalar_field(np.absolute(data)), vmin=vmin, vmax=vmax) mlab.savefig(path_to_save) mlab.clf() mlab.close()
def anim(): global bondcolors while True: print mlab.view(), mlab.roll() bondcolors[:] = bondcolors*.5 bondsrc.update() yield
def _mlab_init(self): import mayavi.mlab as mlab from pyface.api import GUI self.mlab = mlab mlab.figure(bgcolor=(0, 0, 0)) x, y, z = [i.flatten() for i in np.mgrid[0:8:1, 0:8:1, 0:8:1]] self.points = mlab.points3d(x, y, z, list(range(512)), scale_mode="none", scale_factor=0.4) mlab.view(127, 24, distance="auto") mlab.roll(0) self.points.module_manager.scalar_lut_manager.lut.table = self.colormap self.gui = GUI mlab.show()
def generate_spinning_brain_frames(trajectories, nframes_per_cycle=30, figsize=[800, 700]): ''' Plots spike amps versus the time Parameters ------------- trajectories: list of dicts list of dictionaries of trajectories fetched from ONE nframes_per_cycle: int, optional number of frames per cycle of spinning, default 30. figsize: list, [width, height], optional size of the images, default [800, 700] Return ------------ frames: list of numpy.darray image in rgb for each frame ''' fig = rendering.figure() for index, trj in enumerate(trajectories): if trj['coordinate_system'] == 'IBL-Allen': brain_atlas = ba_allen elif trj['coordinate_system'] == 'Needles-Allen': brain_atlas = ba_needles else: brain_atlas = ba_allen ins = atlas.Insertion.from_dict(trj, brain_atlas=brain_atlas) ins = atlas.Insertion.from_dict(trj, brain_atlas=ba_allen) mlapdv = brain_atlas.xyz2ccf(ins.xyz) if trj['provenance'] == 'Ephys aligned histology track': color = (0, 0, 1.) # Blue mlab.plot3d(mlapdv[:, 1], mlapdv[:, 2], mlapdv[:, 0], line_width=3, color=color, tube_radius=20) frames = [] for i in range(nframes_per_cycle): mlab.view(azimuth=0, elevation=0 - i * (360 / nframes_per_cycle)) mlab.roll(180) mlab.test_plot3d() f = mlab.gcf() f.scene._lift() frames.append(mlab.screenshot(mode='rgb', antialiased=True)) return frames
def parameters(self): """Get current camera parameters. Returns a dictionary associating each parameter name (i.e., `azimuth`, `focalpoint`, `distance`, `elevation` and `roll`) to its current value. """ self.azimuth, self.elevation, self.distance, self.focalpoint = mlab.view() self.roll = mlab.roll() return {'focalpoint' : self.focalpoint, 'distance' : self.distance, 'azimuth' : self.azimuth, 'elevation' : self.elevation, 'roll' : self.roll}
def plot_surfaces(self, label, X, T, scalars=None, color=None, rep='surface', opacity=1.0): mlab.figure(self.figure.name) if color == None: color = (1,0,0) mlab_obj = self.plots.get(label) if mlab_obj == None: if scalars==None: self.plots[label] = mlab.triangular_mesh(X[:,0], X[:,1], X[:,2], T, color=color, opacity=opacity, representation=rep) else: self.plots[label] = mlab.triangular_mesh(X[:,0], X[:,1], X[:,2], T, scalars=scalars, opacity=opacity) else: self.figure.scene.disable_render = True view = mlab.view() roll = mlab.roll() if X.shape[0] == mlab_obj.mlab_source.x.shape[0]: if scalars==None: mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2]) mlab_obj.actor.property.color = color mlab_obj.actor.property.opacity = opacity else: mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2], scalars=scalars, opacity=opacity) else: self.clear(label) if scalars==None: self.plots[label] = mlab.triangular_mesh(X[:,0], X[:,1], X[:,2], T, color=color, opacity=opacity, representation=rep) else: self.plots[label] = mlab.triangular_mesh(X[:,0], X[:,1], X[:,2], T, scalars=scalars, opacity=opacity) mlab.view(*view) mlab.roll(roll) self.figure.scene.disable_render = False
def show_3d_point(points): """ show a (n, 3) array of point cloud :param points: :return: """ if points.shape[1] != 3: points = np.asarray(points).T print('show shape: ', points.shape) fig = figure(bgcolor=(0, 0, 0), fgcolor=(1, 1, 1), size=(1400, 800)) points3d(points[:, 0], points[:, 1], points[:, 2], mode='sphere', colormap='gnuplot', scale_factor=0.05, figure=fig) # mlab.view(75.0, 140.0, [30., 30., 30.]) mlab.roll(360) mlab.move(3, -1, 3.2) print(mlab.view()) mlab.show()
def plot_atom(istep, num, typ, crd, ivert, vert, edges, view = None, roll = None): import networkx as nx from mayavi import mlab dictXI = dict(zip(ivert, xrange(len(ivert)))) G = nx.Graph() for edge in edges: G.add_edge(dictXI[edge[0]], dictXI[edge[1]]) colors = typ # mlab.options.offscreen = True mlab.figure(1, bgcolor = (0., 0., 0.)) mlab.clf() atoms = mlab.points3d(crd[:,0], crd[:,1], crd[:,2], colors, scale_factor = 1, scale_mode = 'none', colormap = 'autumn', resolution = 20) vp_verts = mlab.points3d(vert[:,0], vert[:,1], vert[:,2], color=(1.,1.,1.), scale_factor = 0.02, scale_mode = 'none', resolution = 20) vp_verts.mlab_source.dataset.lines = np.array(G.edges()) tube = mlab.pipeline.tube(vp_verts, tube_radius=0.1) mlab.pipeline.surface(tube, color = (0.8, 0.8, 0.8)) if view == None: view = mlab.view() roll = mlab.roll() else: mlab.view(*view) mlab.roll(roll) mlab.show() mlab.savefig(str(istep) +'.png') return view, roll
def UpdateViewPositionChange(self, position): if self.logger.isEnabledFor(logging.DEBUG): self.logger.debug('position=%s', str(position)) previous_position = self.slicePosition self.slicePosition = position # Check for new slice position if not previous_position[0] == position[0]: self.UpdateScalarField() self.UpdateChoppedVolume() self.UpdateCutPlaneX() self.UpdateCutPlaneZ() # Ensure the cut planes are not movable # self.cutplane_x.implicit_plane.widget.enabled = False # self.cutplane_y.implicit_plane.widget.enabled = False # self.cutplane_z.implicit_plane.widget.enabled = False # Set initial camera angle if self.first_view: mlab.view(120, -45, 900) mlab.roll(75) self.first_view = False
def anim(): global t, frame, F, az, spin_dir while True: print mlab.view(), mlab.roll() print frame, t t += dt az += spin_dir*.5 mlab.view(azimuth=az, distance=60, focalpoint=(0, 0, zmax/2)) F = field(x, y, z, t) s.set(u=F[0].reshape(size), v=F[1].reshape(size), w=F[2].reshape(size)) yield fname = "anim/3d-%s-%02i.png" %(name, frame) print 'saving', fname figure.scene.save(fname) frame += 1 if frame > nframes/2: spin_dir = -1 if frame > nframes: exit(0)
def _display_maya_voxel(x_plot, y_plot, z_plot, faces, scalars, origin=[0, 0, 0], cmap='jet', colorbar=False, figure=None, vmin=None, vmax=None, file_name=None, azimuth=60, elevation=90, roll=0, points=False, cmap_points=None, scale_points=False, color=None): """ Helper function to show data from a voxel in a mayavi figure """ x_plot += origin[0] y_plot += origin[1] z_plot += origin[2] if figure is None: figure = maya.figure() else: figure = figure # Take care of the color-map: if vmin is None: vmin = np.min(scalars) if vmax is None: vmax = np.max(scalars) # Plot the sample points as spheres: if points: # Unless you specify it, use the same colormap for the points as for # the surface: if cmap_points is None: cmap_points = cmap if scale_points is False: tm = maya.points3d(x_plot, y_plot, z_plot, color=(0.4, 0.4, 0.8), figure=figure, mode='sphere', scale_factor=0.07) else: if scale_points is True: pass # just use the scalars to scale elif scale_points: # If it's a sequence: if hasattr(scale_points, '__len__'): scalars = scale_points else: scalars = np.ones(scalars.shape) * scale_points tm = maya.points3d(x_plot, y_plot, z_plot, scalars, colormap=cmap_points, figure=figure, vmin=vmin, vmax=vmax) else: tm = maya.triangular_mesh(x_plot, y_plot, z_plot, faces, scalars=scalars, colormap=cmap, color=color, figure=figure, vmin=vmin, vmax=vmax) if colorbar: maya.colorbar(tm, orientation='vertical') scene = figure.scene scene.background = (1, 1, 1) scene.parallel_projection = True scene.light_manager.light_mode = 'vtk' # Set it to be aligned along the negative dimension of the y axis: #scene.y_minus_view() maya.view(azimuth=azimuth, elevation=elevation) maya.roll(roll) module_manager = tm.parent module_manager.scalar_lut_manager.number_of_labels = 6 scene.render() if file_name is not None: scene.save(file_name) return figure
def _display_maya_voxel(x_plot, y_plot, z_plot, faces, scalars, origin=[0,0,0], cmap='jet', colorbar=False, figure=None, vmin=None, vmax=None, file_name=None, azimuth=60, elevation=90, roll=0, points=False, cmap_points=None, scale_points=False, color=None): """ Helper function to show data from a voxel in a mayavi figure """ x_plot += origin[0] y_plot += origin[1] z_plot += origin[2] if figure is None: figure = maya.figure() else: figure = figure # Take care of the color-map: if vmin is None: vmin = np.min(scalars) if vmax is None: vmax = np.max(scalars) # Plot the sample points as spheres: if points: # Unless you specify it, use the same colormap for the points as for # the surface: if cmap_points is None: cmap_points = cmap if scale_points is False: tm = maya.points3d(x_plot, y_plot, z_plot, color=(0.4,0.4,0.8), figure=figure, mode='sphere', scale_factor = 0.07) else: if scale_points is True: pass # just use the scalars to scale elif scale_points: # If it's a sequence: if hasattr(scale_points, '__len__'): scalars = scale_points else: scalars = np.ones(scalars.shape) * scale_points tm = maya.points3d(x_plot, y_plot, z_plot, scalars, colormap=cmap_points, figure=figure, vmin=vmin, vmax=vmax) else: tm = maya.triangular_mesh(x_plot, y_plot, z_plot, faces, scalars=scalars, colormap=cmap, color=color, figure=figure, vmin=vmin, vmax=vmax) if colorbar: maya.colorbar(tm, orientation='vertical') scene = figure.scene scene.background = (1,1,1) scene.parallel_projection=True scene.light_manager.light_mode = 'vtk' # Set it to be aligned along the negative dimension of the y axis: #scene.y_minus_view() maya.view(azimuth=azimuth, elevation=elevation) maya.roll(roll) module_manager = tm.parent module_manager.scalar_lut_manager.number_of_labels = 6 scene.render() if file_name is not None: scene.save(file_name) return figure
def update_scene(): global plots, offsets, p_scale, show_in_p, aim_point, point_i # Get the current view v = mlab.view() roll = mlab.roll() # clear figure for key in plots.keys(): plots[key].remove() plots = {} # Plot new data feature p = points[obj_i] # Rescale points for visu p = (p * 1.5 / config.in_radius) # Show point cloud if show_in_p <= 1: plots['points'] = mlab.points3d(p[:, 0], p[:, 1], p[:, 2], resolution=8, scale_factor=p_scale, scale_mode='none', color=(0, 1, 1), figure=fig1) if show_in_p >= 1: # Get points and colors in_p = in_points[obj_i] in_p = (in_p * 1.5 / config.in_radius) # Color point cloud if possible in_c = in_colors[obj_i] if in_c is not None: # Primitives scalars = np.arange( len(in_p) ) # Key point: set an integer for each point # Define color table (including alpha), which must be uint8 and [0,255] colors = np.hstack( (in_c, np.ones_like(in_c[:, :1]))) colors = (colors * 255).astype(np.uint8) plots['in_points'] = mlab.points3d( in_p[:, 0], in_p[:, 1], in_p[:, 2], scalars, resolution=8, scale_factor=p_scale * 0.8, scale_mode='none', figure=fig1) plots[ 'in_points'].module_manager.scalar_lut_manager.lut.table = colors else: plots['in_points'] = mlab.points3d( in_p[:, 0], in_p[:, 1], in_p[:, 2], resolution=8, scale_factor=p_scale * 0.8, scale_mode='none', figure=fig1) # Get KP locations rescaled_aim_point = aim_point * config.in_radius / 1.5 point_i = lookuptrees[obj_i].query( rescaled_aim_point, return_distance=False)[0][0] if offsets: KP = points[obj_i][point_i] + deformed_KP[obj_i][ point_i] scals = np.ones_like(KP[:, 0]) else: KP = points[obj_i][point_i] + original_KP scals = np.zeros_like(KP[:, 0]) KP = (KP * 1.5 / config.in_radius) plots['KP'] = mlab.points3d(KP[:, 0], KP[:, 1], KP[:, 2], scals, colormap='autumn', resolution=8, scale_factor=1.2 * p_scale, scale_mode='none', vmin=0, vmax=1, figure=fig1) if True: plots['center'] = mlab.points3d(p[point_i, 0], p[point_i, 1], p[point_i, 2], scale_factor=1.1 * p_scale, scale_mode='none', color=(0, 1, 0), figure=fig1) # New title plots['title'] = mlab.title(str(obj_i), color=(0, 0, 0), size=0.3, height=0.01) text = '<--- (press g for previous)' + 50 * ' ' + '(press h for next) --->' plots['text'] = mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98) plots['orient'] = mlab.orientation_axes() # Set the saved view mlab.view(*v) mlab.roll(roll) return
[np.arange(index, index + N - 1.5), np.arange(index+1, index + N - .5)] ).T) index += N # Now collapse all positions, scalars and connections in big arrays x = np.hstack(x) y = np.hstack(y) z = np.hstack(z) s = np.hstack(s) connections = np.vstack(connections) # Create the points src = mlab.pipeline.scalar_scatter(x, y, z, s) # Connect them src.mlab_source.dataset.lines = connections # The stripper filter cleans up connected lines lines = mlab.pipeline.stripper(src) # Finally, display the set of lines mlab.pipeline.surface(lines, colormap='Accent', line_width=1, opacity=.4) # And choose a nice view mlab.view(33.6, 106, 5.5, [0, 0, .05]) mlab.roll(125) mlab.show()
grid_qy, np.log10(data), contours=contours, opacity=0.2, colormap='hsv', vmin=0, vmax=np.ceil(np.log10(data[~np.isnan(data)].max()))) if distance: mlab.view(azimuth=38, elevation=63, distance=distance) else: mlab.view(azimuth=38, elevation=63, distance=np.sqrt(qx.max()**2 + qz.max()**2 + qy.max()**2)) # azimut is the rotation around z axis of mayavi (x) mlab.roll(0) if crop_symmetric: ax = mlab.axes(line_width=2.0, nb_labels=2 * half_labels + 1) else: ax = mlab.axes(line_width=2.0, nb_labels=4) mlab.xlabel('Qx (1/nm)') mlab.ylabel('Qz (1/nm)') mlab.zlabel('-Qy (1/nm)') mlab.savefig(savedir + 'S' + str(scan) + comment + '_labels.png', figure=myfig) ax.label_text_property.opacity = 0.0 ax.title_text_property.opacity = 0.0 mlab.savefig(savedir + 'S' + str(scan) + comment + '_axes.png', figure=myfig) ax.axes.x_axis_visibility = False ax.axes.y_axis_visibility = False
def render(name, vlim, angle, suppress=True, **kw): ''' Render a single sclr file. Arguments: name -- A tuple of the form ''' logprint("loading mlab") import mayavi.mlab as mlab if len(name) == 3: inname, outname, label = name else: inname, outname, label, traj = name if outname: print("hi") mlab.options.offscreen = True #setting otf kw['otf'] = otf_type(vlim, kw['otf']) d = volumetric(inname, mlab=mlab, vlim=vlim, **kw) #label if label: l = label d['t'] = mlab.text(0.075, 0.875, l, width=len(l) * 0.015) #show the nubs kw['oa'] = mlab.orientation_axes(xlabel=kw['xlabel'], ylabel=kw['ylabel'], zlabel=kw['zlabel']) kw['oa'].marker.set_viewport(0, 0, 0.4, 0.4) #setting the view mlab.view(elevation=angle[0], azimuth=angle[1], focalpoint='auto', distance='auto') mlab.roll(angle[2]) #doing the crazy trajectory stuff. if 'traj' in kw: #the first index into the start firsti = d[ 'traj_firsti'] = kw['traj_firsti'] if 'traj_firsti' in kw else 0 #ugh step = d['traj_step'] = kw['traj_step'] if 'traj_step' in kw else 1 full_traj = readfile(traj) #the shape of each dimension is d[dimension,particle,step] steps = full_traj.shape[2] N = full_traj.shape[1] #creating connections between points, this should be an #array of pairs that give indices of coordinates that should #be connected. sarray = np.arange(steps) conn_1 = np.array(zip(sarray[:-1], sarray[1:])) conn = np.vstack([conn_1 + steps * i for i in range(N)]) del sarray, conn_1 #cleaning up. #making current part of the track to be plotted cur_traj = np.empty(full_traj.shape) cur_traj.fill(np.nan) cur_traj[:, :, :firsti] = full_traj[:, :, :firsti] x = np.hstack(cur_traj[0, :, :]) y = np.hstack(cur_traj[1, :, :]) z = np.hstack(cur_traj[2, :, :]) #trajectory source tracks_src = mlab.pipeline.scalar_scatter(x, y, z, np.ones(x.shape)) tracks_src.mlab_source.dataset.lines = conn lines = mlab.pipeline.stripper(tracks_src) #creating tracks. tracks = mlab.pipeline.surface(lines, line_width=2, opacity=1.0) d['tracks'] = tracks d['traj_cur'] = cur_traj d['traj_full'] = full_traj d['fig'].scene.disable_render = False d['image'] = mlab.screenshot() if not suppress: if not outname: logprint('showing') mlab.show() else: logprint('saving {}'.format(outname)) #hack to avoid the lines, now mayavi really is headless imsave(outname, d['image']) return d
mlab.figure(bgcolor=(0,0,0), size = (400, 400)) src = mlab.pipeline.scalar_field(imgs_after_rg) #src.spacing = [1, 1, 1] #src.update_image_data = True blur = mlab.pipeline.user_defined(src, filter='ImageGaussianSmooth') voi = mlab.pipeline.extract_grid(blur) voi.trait_set(x_min=0, x_max=300, y_min=0, y_max=300, z_min=0, z_max=300) mlab.pipeline.iso_surface(voi) mlab.view(90,90, 400) mlab.roll(-90) mlab.show() #Bronchial Grower import numpy as np from skimage import data, color, io, img_as_float import cv2 from skimage import measure from plotly.offline import download_plotlyjs, init_notebook_mode, plot from plotly.tools import FigureFactory as FF from pydicom.data import get_testdata_files import pydicom import matplotlib.pyplot as plt from collections import Counter import matplotlib as mpl
def get_camera(self): return (mlab.view(), mlab.roll())
print size_array #print image.GetPixel(90,80,50) image_array = sitk.GetArrayFromImage(image)[:,:,:] print image_array.ptp() #sys.exit() mlab.figure(bgcolor=(0,0,0), size=(400,400)) src = mlab.pipeline.scalar_field(image_array) src.spacing = [0.33,0.33,0.33] src.update_image_data = True #blur = mlab.pipeline.user_defined(src, filter = 'ImageGaussianSmooth') voi = mlab.pipeline.extract_grid(src) mlab.pipeline.iso_surface(voi, contours = [50, 255], colormap='Spectral', opacity = 0.2) mlab.view(-125, 54, 326, (145.5, 138, 66.5)) mlab.roll(0) mlab.show() # x = np.linspace(0,1,size_array[0]) # y = np.linspace(0,1,size_array[1]) # z = np.linspace(0,1,size_array[2]) # mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) # obj = contour3d(x,y,z,image_array, transparent = True)
def plot_points(self, label, X, color=None, size=None, mode=None): mlab.figure(self.figure.name) if color == None: color = (1, 0, 0) if size == None and mode == None or size == 0: size = 1 mode = 'point' if size == None: size = 1 if mode == None: mode = 'sphere' if isinstance(X, list): X = numpy.array(X) if len(X.shape) == 1: X = numpy.array([X]) mlab_obj = self.plots.get(label) if mlab_obj == None: if isinstance(color, tuple): self.plots[label] = mlab.points3d(X[:, 0], X[:, 1], X[:, 2], color=color, scale_factor=size, mode=mode) else: self.plots[label] = mlab.points3d(X[:, 0], X[:, 1], X[:, 2], color, scale_factor=size, scale_mode='none', mode=mode) else: self.figure.scene.disable_render = True view = mlab.view() roll = mlab.roll() ### Commented out since VTK gives an error when using mlab_source.set #~ if X.shape[0] == mlab_obj.mlab_source.x.shape[0]: #~ if isinstance(color, tuple): #~ mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2]) #~ mlab_obj.actor.property.color = color #~ else: #~ mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2], scalars=color) #~ #~ #~ else: #~ self.clear(label) #~ if isinstance(color, tuple): #~ self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color=color, scale_factor=size, mode=mode) #~ else: #~ self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color, scale_factor=size, scale_mode='none', mode=mode) self.clear(label) if isinstance(color, tuple): self.plots[label] = mlab.points3d(X[:, 0], X[:, 1], X[:, 2], color=color, scale_factor=size, mode=mode) else: self.plots[label] = mlab.points3d(X[:, 0], X[:, 1], X[:, 2], color, scale_factor=size, scale_mode='none', mode=mode) mlab.view(*view) mlab.roll(roll) self.figure.scene.disable_render = False
cut_plane.implicit_plane.widget.enabled = False cut_plane2 = mlab.pipeline.scalar_cut_plane(thr, plane_orientation='z_axes', colormap='black-white', vmin=1400, vmax=2600) cut_plane2.implicit_plane.origin = (136, 111.5, 82) cut_plane2.implicit_plane.widget.enabled = False # Extract two views of the outside surface. We need to define VOIs in # order to leave out a cut in the head. voi2 = mlab.pipeline.extract_grid(src) voi2.set(y_min=112) outer = mlab.pipeline.iso_surface(voi2, contours=[1776, ], color=(0.8, 0.7, 0.6)) voi3 = mlab.pipeline.extract_grid(src) voi3.set(y_max=112, z_max=53) outer3 = mlab.pipeline.iso_surface(voi3, contours=[1776, ], color=(0.8, 0.7, 0.6)) mlab.view(-125, 54, 326, (145.5, 138, 66.5)) mlab.roll(-175) mlab.show() import shutil shutil.rmtree('mri_data')
nX, -startLabelOffset, ZOffset - 1, "1", orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=labelScale, ) mlab.text3d( nX - 1, nY + 1, ZOffset + 0.5, str(nY), orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=labelScale, ) roll = 177.9584710619396 view = (-20.96663248113742, 107.30927449790735, 94.066015884153884, np.array([17.14404891, 16.30124532, 9.85753332])) mlab.view(*view) mlab.roll(roll) fname = outputDir + "/network_layers.png" mlab.savefig(fname)
connect_ = tvtk.PolyDataConnectivityFilter(extraction_mode=4) connect = mlab.pipeline.user_defined(smooth, filter=connect_) # Compute normals for shading the surface compute_normals = mlab.pipeline.poly_data_normals(connect) compute_normals.filter.feature_angle = 80 surf = mlab.pipeline.surface(compute_normals, color=(0.9, 0.72, 0.62)) #---------------------------------------------------------------------- # Display a cut plane of the raw data ipw = mlab.pipeline.image_plane_widget(src, colormap='bone', plane_orientation='z_axes', slice_index=55) mlab.view(-165, 32, 350, [143, 133, 73]) mlab.roll(180) fig.scene.disable_render = False #---------------------------------------------------------------------- # To make the link between the Mayavi pipeline and the much more # complex VTK pipeline, we display both: mlab.show_pipeline(rich_view=False) from tvtk.pipeline.browser import PipelineBrowser browser = PipelineBrowser(fig.scene) browser.show() mlab.show()
connections.append( np.vstack([ np.arange(index, index + N - 1.5), np.arange(index + 1, index + N - .5) ]).T) index += N # Now collapse all positions, scalars and connections in big arrays x = np.hstack(x) y = np.hstack(y) z = np.hstack(z) s = np.hstack(s) connections = np.vstack(connections) # Create the points src = mlab.pipeline.scalar_scatter(x, y, z, s) # Connect them src.mlab_source.dataset.lines = connections # The stripper filter cleans up connected lines lines = mlab.pipeline.stripper(src) # Finally, display the set of lines mlab.pipeline.surface(lines, colormap='Accent', line_width=1, opacity=.4) # And choose a nice view mlab.view(33.6, 106, 5.5, [0, 0, .05]) mlab.roll(125) mlab.show()
def set_camera(self, camera): mlab.view(*camera[0]) mlab.roll(camera[1])
# plot the left cortical surface mesh = mlab.pipeline.triangular_mesh_source(x1, y1, z1, faces) mesh.data.point_data.normals = normals mlab.pipeline.surface(mesh, color=3*(0.7,)) # plot the convex hull bounding the left cerebellum hull = ConvexHull(np.c_[x2, y2, z2]) mlab.triangular_mesh(x2, y2, z2, hull.simplices, color=3*(0.5,), opacity=0.3) # plot the left cerebellum sources mlab.points3d(x2, y2, z2, color=(1, 1, 0), scale_factor=0.001) # adjust view parameters mlab.view(173.78, 101.75, 0.30, np.array([-0.03, -0.01, 0.03])) mlab.roll(85) mlab.show() ############################################################################## # Compare volume source locations to segmentation file in freeview # Export source positions to nift file nii_fname = data_path + '/MEG/sample/mne_sample_lh-cerebellum-cortex.nii' # Combine the source spaces src = surf + lh_cereb src.export_volume(nii_fname, mri_resolution=True) # Uncomment the following lines to display source positions in freeview. '''
def plot_surfaces(self, label, X, T, scalars=None, color=None, rep='surface', opacity=1.0): mlab.figure(self.figure.name) if color == None: color = (1, 0, 0) mlab_obj = self.plots.get(label) if mlab_obj == None: if scalars == None: self.plots[label] = mlab.triangular_mesh(X[:, 0], X[:, 1], X[:, 2], T, color=color, opacity=opacity, representation=rep) else: self.plots[label] = mlab.triangular_mesh(X[:, 0], X[:, 1], X[:, 2], T, scalars=scalars, opacity=opacity) else: self.figure.scene.disable_render = True view = mlab.view() roll = mlab.roll() if X.shape[0] == mlab_obj.mlab_source.x.shape[0]: if scalars == None: mlab_obj.mlab_source.set(x=X[:, 0], y=X[:, 1], z=X[:, 2]) mlab_obj.actor.property.color = color mlab_obj.actor.property.opacity = opacity else: mlab_obj.mlab_source.set(x=X[:, 0], y=X[:, 1], z=X[:, 2], scalars=scalars, opacity=opacity) else: self.clear(label) if scalars == None: self.plots[label] = mlab.triangular_mesh( X[:, 0], X[:, 1], X[:, 2], T, color=color, opacity=opacity, representation=rep) else: self.plots[label] = mlab.triangular_mesh(X[:, 0], X[:, 1], X[:, 2], T, scalars=scalars, opacity=opacity) mlab.view(*view) mlab.roll(roll) self.figure.scene.disable_render = False
mlab.text3d(x[0] - 0.075*nX, y[0] - 0.075*nY, ZOffset/2, "gE", orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=textScale) mlab.text3d(x[1] + 0.075*nX, y[1] + 0.075*nY, ZOffset/2, "gI", orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=textScale) # Neuron labels startLabelOffset = 1 labelScale = 1.5 mlab.text3d(-startLabelOffset, -startLabelOffset, ZOffset - 1, str(nX), orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=labelScale) mlab.text3d(nX, -startLabelOffset, ZOffset - 1, "1", orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=labelScale) mlab.text3d(nX - 1, nY + 1, ZOffset + 0.5, str(nY), orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=labelScale) roll = 177.9584710619396 view = (-20.96663248113742, 107.30927449790735, 94.066015884153884, np.array([ 17.14404891, 16.30124532, 9.85753332])) mlab.view(*view) mlab.roll(roll) fname = outputDir + "/network_layers.png" mlab.savefig(fname)
def show_triangular_mesh(x, y, z, triangles, scalars, vmin=None, vmax=None, colormap='jet', lut=None, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 350), azimuth=-48, elevation=142, distance=422, focalpoint=(33, -17, 16), roll=-84, cbar_orientation=None, cbar_position=None, cbar_position2=None, cbar_label_fmt=None, cbar_num=0, mode='show', **kwargs): """ Parameters: ---------- x[ndarray]: 1-D array with shape as (n_vtx) y[ndarray]: 1-D array with shape as (n_vtx) z[ndarray]: 1-D array with shape as (n_vtx) triangles[seq]: a list of triplets (or an array) list the vertices in each triangle scalars[ndarray]: 1-D or 2-D array if 1-D array, its shape is (n_vtx,). if 2-D array, its shape is (N, n_vtx), where N is the number of overlays. Overlays with larger row numbers will cover on the overlays with smaller row numbers. Vertices with the smallest scalar will be set transparent except for the bottom overlay. vmin[float|list]: the minimal scalar to display If is list, one-by-one corresponding to the rows of scalars. Else, applied to all overlays. vmax[float|list]: the maximal scalar to display If is list, one-by-one corresponding to the rows of scalars. Else, applied to all overlays. colormap[str|list]: the color map method If is list, one-by-one corresponding to the rows of scalars. Else, applied to all overlays. lut[ndarray|list]: lookup table of color with shape as (n_color, 4) If is not None, ignore 'colormap' bgcolor[seq]: the rgb color of background. fgcolor[seq]: the rgb color of foreground. size[seq]: size of figure (width x height) azimuth[float]: elevation[float]: distance[float]: focalpoint[seq]: roll[float]: cbar_orientation[str]: the orientation of colorbar cbar_position[seq]: position of bottom-left corner cbar_position2[seq]: distance from the bottom-left corner cbar_label_fmt[str]: string format of labels of the colorbar cbar_num[int]: show colorbar of the cbar_num overlay If is 0, no colorbar will be displayed. If is 1, show the first overlay's colorbar, i.e. the bottom overlay. mode[str]: show or return If is 'show', just show the figure. If is 'return', return screen shot and close the figure. Else, regard as the output path of the figure. kwargs: reference to doc of mlab.triangular_mesh Return: ------ img[ndarray]: """ # transform x, y, z x = np.asarray(x) y = np.asarray(y) z = np.asarray(z) assert x.ndim == 1 and y.ndim == 1 and z.ndim == 1 assert x.shape == y.shape and y.shape == z.shape # transform scalars if scalars.ndim == 1: scalars = scalars[None, :] elif scalars.ndim != 2: raise ValueError('Unsupported dimension number of scalars:', scalars.ndim) assert scalars.shape[1] == x.shape[0] n_overlay = scalars.shape[0] # transform vmin if not isinstance(vmin, list): vmin = [vmin] * n_overlay else: assert len(vmin) == n_overlay # transform vmax if not isinstance(vmax, list): vmax = [vmax] * n_overlay else: assert len(vmax) == n_overlay # transform colormap if not isinstance(colormap, list): colormap = [colormap] * n_overlay else: assert len(colormap) == n_overlay # transform LUT if not isinstance(lut, list): lut = [lut] * n_overlay else: assert len(lut) == n_overlay fig = mlab.figure(bgcolor=bgcolor, fgcolor=fgcolor, size=size) for idx, data in enumerate(zip(scalars, vmin, vmax, colormap, lut), 1): s, vi, va, cm, lut_i = data if vi is None: vi = np.min(s) if va is None: va = np.max(s) surf = mlab.triangular_mesh(x, y, z, triangles, scalars=s, figure=fig, vmin=vi, vmax=va, colormap=cm, **kwargs) # fix the color of the smallest scalar if lut_i is None: lut_i = np.array(surf.module_manager.scalar_lut_manager.lut.table) if idx == 1: lut_i[0, :3] = 127.5 else: lut_i[0, 3] = 0 surf.module_manager.scalar_lut_manager.lut.table = lut_i if idx == cbar_num: # create color bar cbar = mlab.scalarbar(surf, orientation=cbar_orientation, label_fmt=cbar_label_fmt, nb_labels=5) cbar.scalar_bar_representation.position = cbar_position cbar.scalar_bar_representation.position2 = cbar_position2 # adjust camera mlab.view(azimuth, elevation, distance, focalpoint, figure=fig) mlab.roll(roll, figure=fig) if mode == 'return': # may have some bugs img = mlab.screenshot(fig) mlab.close(fig) return img elif mode == 'show': mlab.show() else: # regard as output filename mlab.savefig(mode, figure=fig) mlab.close(fig)
fig = mlab.figure(bgcolor=(0, 0, 0), size=(1280, 720)) visual.set_viewer(fig) # Iterate through all the files in this folder. for name in glob.glob(os.path.join(path, '*.txt')): num = int(name[-8:-4]) if num == 1: continue # Disable rendering for faster speed. fig.scene.disable_render = True draw(name, mag=True) fig.scene.disable_render = False # Set view and save image. # line mlab.view(azimuth=45, elevation=90, distance=6, reset_roll=True, focalpoint=[0, 0, 0]) mlab.roll(roll=45) # toroid #mlab.view(azimuth=90, elevation=45, distance=20, reset_roll=True, focalpoint=[0, 0, 0]) mlab.savefig(name[:-3] + 'png') print name #mlab.show() #raw_input("Press Enter")
colormap='black-white', vmin=1400, vmax=2600) cut_plane2.implicit_plane.origin = (136, 111.5, 82) cut_plane2.implicit_plane.widget.enabled = False # Extract two views of the outside surface. We need to define VOIs in # order to leave out a cut in the head. voi2 = mlab.pipeline.extract_grid(src) voi2.trait_set(y_min=112) outer = mlab.pipeline.iso_surface(voi2, contours=[ 1776, ], color=(0.8, 0.7, 0.6)) voi3 = mlab.pipeline.extract_grid(src) voi3.trait_set(y_max=112, z_max=53) outer3 = mlab.pipeline.iso_surface(voi3, contours=[ 1776, ], color=(0.8, 0.7, 0.6)) mlab.view(-125, 54, 326, (145.5, 138, 66.5)) mlab.roll(-175) mlab.show() import shutil shutil.rmtree('mri_data')
def detector_intercept_info(system, use_random=True, dispersion_curve=False): # consider using mayavi.mlab.imshow for this image... # compute intercept points and energies, dispersion curves, etc... # find correct directory curr_dir = os.getcwd() run_dir = curr_dir + "/" + system.sysName if os.path.exists(run_dir) and curr_dir is not run_dir: print "Changing to directory with ray trace data...\n" os.chdir(run_dir) # get optic reflection points and energies if use_random: optic_points = np.loadtxt("random_crystal_intercept_points.dat") rvecs = np.loadtxt("random_reflected_kvectors.dat") spectrum_func = interp1d(system.source.spectrum[0], system.source.spectrum[1]) # load the energy list and modify the spectrum according to the distribution ref_nrgs = np.loadtxt("random_energies.dat") init_intensities = np.ones(ref_nrgs.shape) src_intensities = spectrum_func(ref_nrgs) fin_intensities = src_intensities * init_intensities print fin_intensities.max() else: optic_points = np.loadtxt("grid_crystal_intercept_points.dat") rvecs = np.loadtxt("grid_reflected_kvectors.dat") spectrum_func = interp1d(system.source.spectrum[0], system.source.spectrum[1]) # load the energy list and modify the spectrum according to the distribution ref_nrgs = np.loadtxt("grid_energies.dat") init_intensities = np.ones(ref_nrgs.shape) src_intensities = spectrum_func(ref_nrgs) fin_intensities = src_intensities * init_intensities # detector location p = system.detectorVec # detector normal n = system.detectorNorm pR = p - optic_points # intersection distance d = (pR * n).sum(-1)[..., np.newaxis] / (rvecs * n).sum(-1)[..., np.newaxis] # define the end points finPoints = optic_points + rvecs * d # the translated intersect points points = finPoints - p yaxis = np.array([0.0, 1.0, 0.0]) rotang = np.arccos(np.dot(yaxis, -system.detectorNorm)) # rotation matrix about z Rz = np.matrix([[np.cos(rotang), -np.sin(rotang), 0.0], [np.sin(rotang), np.cos(rotang), 0.0], [0.0, 0.0, 1.0]]) # operate on the points with the rotation rotPoints = Rz * points.T # the non-zero entries become the new x,y coordinates for the image # x --> x , z --> y x = rotPoints[0] y = rotPoints[2] # 1/2 detector dimensions hw = 0.5 * system.detector.width hh = 0.5 * system.detector.height # masked arrays to find points outside detector xm = np.ma.masked_outside(x, -hw, hw) ym = np.ma.masked_outside(y, -hh, hh) # convert points outside detector ranges to 0.0 value... # this places them along the edge of the detector frame xm -= hw ym -= hh xm = xm.filled(0.0) ym = ym.filled(0.0) # convert in order to use as indices for the image array #system resolution rez = 1.0 / (system.detector.pixelSize) #rez = system.detector.resPixPerMM # system resolution xm = np.abs(np.around(xm * rez)) ym = np.abs(np.around(ym * rez)) cols = xm.astype(int) rows = ym.astype(int) # empty image array with dimensions of detector imRowMax = np.abs(np.around(rez * 2.0 * hh)) + 1 imColMax = np.abs(np.around(rez * 2.0 * hw)) + 1 im = np.zeros((imRowMax, imColMax), dtype=np.uint32) vals = fin_intensities # set the image pixels im[rows, cols] = vals * 255 from mayavi import mlab mlab.imshow(im, colormap='jet', interpolate=True) mlab.view(0, 0) mlab.roll(-90) mlab.show()
def reset_view(): mlab.view(90., -90., 3.) mlab.roll(90.)
def manual_sphere(image_file): # caveat 1: flip the input image along its first axis img = plt.imread(image_file) # shape (N,M,3), flip along first dim outfile = image_file.replace('.jpg', '_flipped.jpg') # flip output along first dim to get right chirality of the mapping img = img[::-1, ...] plt.imsave(outfile, img) image_file = outfile # work with the flipped file from now on # parameters for the sphere R = 2 # radius of the sphere Nrad = 180 # points along theta and phi phi = np.linspace(0, 2 * np.pi, Nrad) # shape (Nrad,) theta = np.linspace(0, np.pi, Nrad) # shape (Nrad,) phigrid, thetagrid = np.meshgrid(phi, theta) # shapes (Nrad, Nrad) # compute actual points on the sphere x = R * np.sin(thetagrid) * np.cos(phigrid) y = R * np.sin(thetagrid) * np.sin(phigrid) z = R * np.cos(thetagrid) # create figure f = mlab.figure(size=(500, 500), bgcolor=(1, 1, 1)) # f.scene.movie_maker.record = True # create meshed sphere mesh = mlab.mesh(x, y, z) mesh.actor.actor.mapper.scalar_visibility = False mesh.actor.enable_texture = True # probably redundant assigning the texture later # load the (flipped) image for texturing img = tvtk.JPEGReader(file_name=image_file) texture = tvtk.Texture(input_connection=img.output_port, interpolate=1, repeat=0) mesh.actor.actor.texture = texture # tell mayavi that the mapping from points to pixels happens via a sphere # map is already given for a spherical mapping mesh.actor.tcoord_generator_mode = 'sphere' cylinder_mapper = mesh.actor.tcoord_generator # caveat 2: if prevent_seam is 1 (default), half the image is used to map half the sphere # use 360 degrees, might cause seam but no fake data cylinder_mapper.prevent_seam = 0 # mlab.view(180.0, 90.0, 17.269256680431845, [0.00010503, 0.00011263, 0.]) mlab.view(180.0, 90.0, 10, [0.00010503, 0.00011263, 0.]) n_images = 36 padding = len(str(n_images)) mlab.roll(90.0) @mlab.animate(delay=10, ui=False) def anim(): for i in range(n_images): mesh.actor.actor.rotate_z(360 / n_images) zeros = '0' * (padding - len(str(i))) filename = os.path.join(out_path, '{}_{}{}{}'.format(prefix, zeros, i, ext)) mlab.savefig(filename=filename) yield mlab.close(all=True) # cylinder_mapper.center = np.array([0,0,0]) # set non-trivial center for the mapping sphere if necessary # print(mlab.move()) a = anim() mlab.show() ffmpeg_fname = os.path.join(out_path, '{}_%0{}d{}'.format(prefix, padding, ext)) cmd = 'ffmpeg -f image2 -r {} -i {} -vcodec mpeg4 -y {}.mp4'.format( fps, ffmpeg_fname, prefix) subprocess.check_output(['bash', '-c', cmd]) [os.remove(f) for f in os.listdir(out_path) if f.endswith(ext)]