def saliancey2range(resolution_control=0.005): for j, i in enumerate(f_list): print(' point cloud is', i) pc = PointCloud(i) pc.down_sample(number_of_downsample=2048) for k in range(4): if k == 0: k = -0.5 fig = pc.compute_key_points(percentage=0.1, show_result=False, resolution_control=resolution_control, rate=0.05 * k + 0.05, use_deficiency=False, show_saliency=True) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() img = mlab.screenshot() mlab.savefig(filename=str(j) + str(k) + '_without.png') mlab.close() fig = pc.compute_key_points(percentage=0.1, show_result=False, resolution_control=resolution_control, rate=0.05 * k + 0.05, use_deficiency=True, show_saliency=True) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() img = mlab.screenshot() mlab.savefig(filename=str(j) + str(k) + '_with.png') mlab.close() del pc
def rotating_video(output_file, mfig, fps=12, secs=6): # ffmpeg -i input.webm -pix_fmt rgb24 output.gif # ffmpeg -i certification.webm -vf scale=640:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 5 -loop 0 - certification.gif # noqa file_video = Path(output_file) if file_video.suffix == '.avi': fourcc = cv2.VideoWriter_fourcc(*'XVID') elif file_video.suffix == '.webm': fourcc = cv2.VideoWriter_fourcc(*'VP80') else: NotImplementedError(f"Extension {file_video.suffix} not supported") mlab.view(azimuth=180, elevation=0) mfig.scene.render() mfig.scene._lift() frame = mlab.screenshot(figure=mfig, mode='rgb', antialiased=True) w, h, _ = frame.shape video = cv2.VideoWriter(str(file_video), fourcc, float(fps), (h, w)) # import time for e in np.linspace(-180, 180, secs * fps): # frame = np.random.randint(0, 256, (w, h, 3), dtype=np.uint8) mlab.view(azimuth=0, elevation=e, reset_roll=False) mfig.scene.render() frame = mlab.screenshot(figure=mfig, mode='rgb', antialiased=True) print(e, (h, w), frame.shape) video.write(np.flip(frame, axis=2)) # bgr instead of rgb... # time.sleep(0.05) video.release() cv2.destroyAllWindows()
def mcrtmv(frames, dt, mesh, d_nodes, map, savemovie=False, mvname='test', vmin=-1, vmax=1): """ Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac! """ size = 500, 500 fig = ml.figure(size=size, bgcolor=(1., 1., 1.)) #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] xaxis = np.linspace(0, 1, d_nodes[0] + 1) yaxis = np.linspace(0, 1, d_nodes[1] + 1) ml.clf(figure=fig) u = np.load('solution_%06d.npy' % 1) u = numpyfy(u, mesh, d_nodes, map) fname = '_tmp%07d.png' % 1 s = ml.imshow(xaxis, yaxis, u, figure=fig, vmin=vmin, vmax=vmax) #scale = 1./np.max(np.abs(u)) u = u ml.axes(extent=[0, 1, 0, 1, 0, 2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2, frames): u = np.load('solution_%06d.npy' % i) u = numpyfy(u, mesh, d_nodes, map) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname) #,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False if savemovie: os.system( "mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname)
def montage_screenshot(self, zoom=1.5, horiz=True): self._scene.disable_render = True # hide subcortical subcortical_objects = [self._pts] + self._rois_surfaces for el in subcortical_objects: el.visible = False self._scene.disable_render = False ## screenshot self._scene.parallel_projection = True self._scene.x_minus_view() self._scene.camera.view_up = [0, 1, 0] self._scene.camera.zoom(zoom * .80) self._scene.render() lh_lat = mlab.screenshot() #l,r=np.where(np.abs(np.diff(lh_lat.sum(-1).astype(np.int),1,0)).sum(0))[0][[0,-1]]+[-10,10] l, r = 250, 750 lh_lat = lh_lat[:, l:r] self._scene.x_plus_view() self._scene.camera.view_up = [0, 1, 0] self._scene.camera.zoom(zoom * .80) self._scene.render() rh_lat = mlab.screenshot() #l,r=np.where(np.abs(np.diff(rh_lat.sum(-1).astype(np.int),1,0)).sum(0))[0][[0,-1]]+[-10,10] rh_lat = rh_lat[:, l:r] self._scene.disable_render = True for el in subcortical_objects: el.visible = True angle_medial_view = 30 for surf in [self._lh_surf, self._lh_bg_surf]: surf.actor.actor.rotate_y(-angle_medial_view) for surf in [self._rh_surf, self._rh_bg_surf]: surf.actor.actor.rotate_y(angle_medial_view) self._scene.disable_render = False self._scene.z_plus_view() self._scene.camera.zoom(zoom * .95) self._scene.render() lrh_sup = mlab.screenshot() for surf in [self._lh_surf, self._lh_bg_surf]: surf.actor.actor.rotate_y(angle_medial_view) for surf in [self._rh_surf, self._rh_bg_surf]: surf.actor.actor.rotate_y(-angle_medial_view) self._scene.parallel_projection = False if horiz: montage = np.hstack([lh_lat, lrh_sup, rh_lat]) else: montage = np.vstack( [lrh_sup[125:800], np.hstack([lh_lat, rh_lat])[175:800]]) return montage
def montage_screenshot(self,zoom=1.5,horiz=True): self._scene.disable_render = True # hide subcortical subcortical_objects = [self._pts]+self._rois_surfaces for el in subcortical_objects: el.visible = False self._scene.disable_render = False ## screenshot self._scene.parallel_projection = True self._scene.x_minus_view() self._scene.camera.view_up=[0,1,0] self._scene.camera.zoom(zoom*.80) self._scene.render() lh_lat = mlab.screenshot() #l,r=np.where(np.abs(np.diff(lh_lat.sum(-1).astype(np.int),1,0)).sum(0))[0][[0,-1]]+[-10,10] l,r=250,750 lh_lat = lh_lat[:,l:r] self._scene.x_plus_view() self._scene.camera.view_up=[0,1,0] self._scene.camera.zoom(zoom*.80) self._scene.render() rh_lat = mlab.screenshot() #l,r=np.where(np.abs(np.diff(rh_lat.sum(-1).astype(np.int),1,0)).sum(0))[0][[0,-1]]+[-10,10] rh_lat = rh_lat[:,l:r] self._scene.disable_render = True for el in subcortical_objects: el.visible = True angle_medial_view = 30 for surf in [self._lh_surf, self._lh_bg_surf]: surf.actor.actor.rotate_y(-angle_medial_view) for surf in [self._rh_surf, self._rh_bg_surf]: surf.actor.actor.rotate_y(angle_medial_view) self._scene.disable_render = False self._scene.z_plus_view() self._scene.camera.zoom(zoom*.95) self._scene.render() lrh_sup = mlab.screenshot() for surf in [self._lh_surf, self._lh_bg_surf]: surf.actor.actor.rotate_y(angle_medial_view) for surf in [self._rh_surf, self._rh_bg_surf]: surf.actor.actor.rotate_y(-angle_medial_view) self._scene.parallel_projection = False if horiz: montage = np.hstack([lh_lat,lrh_sup,rh_lat]) else: montage = np.vstack([lrh_sup[125:800],np.hstack([lh_lat,rh_lat])[175:800]]) return montage
def mcrtmv3d(frames, dt, Lx, Ly, Nx, Ny, savemovie=False, mvname='test', vmin=-1, vmax=1): x = np.linspace(0, Lx, Nx) y = np.linspace(0, Lx, Nx) X, Y = np.meshgrid(x, y) size = 500, 500 fig = ml.figure(size=size, bgcolor=(1., 1., 1.)) #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] ml.clf(figure=fig) u = np.load('solution_%06d.npy' % 1) fname = '_tmp%07d.png' % 1 s = make3dplot(u) if savemovie: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2, frames): u = np.load('solution_%06d.npy' % i) u = earthSpherify(u) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i #s = make3dplot(u) if savemovie: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname) #,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False if savemovie: os.system( "mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname)
def mcrtmv(frames, dt,mesh, d_nodes, map, savemovie=False, mvname='test', vmin=-1, vmax=1): """ Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac! """ size = 500,500 fig = ml.figure(size= size, bgcolor=(1.,1.,1.)); #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] xaxis = np.linspace(0,1,d_nodes[0]+1) yaxis = np.linspace(0,1,d_nodes[1]+1) ml.clf(figure=fig) u = np.load('solution_%06d.npy'%1); u = numpyfy(u, mesh, d_nodes, map) fname = '_tmp%07d.png' % 1 s = ml.imshow(xaxis, yaxis, u,figure=fig,vmin=vmin, vmax=vmax) #scale = 1./np.max(np.abs(u)) u = u ml.axes(extent=[0,1,0,1,0,2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2,frames): u = np.load('solution_%06d.npy'%i); u = numpyfy(u, mesh, d_nodes, map) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname)#,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False if savemovie: os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
def render_series(names_list, vlim, angle, **kw): ''' Render a series of files. The names_list ''' first = names_list[0] names_list = names_list[1:] logprint("processing first file {}...".format(first['in'])) d = render(first, vlim, angle, **kw) for i, names in enumerate(names_list): logprint("processing {}...".format(names['in'])) S = readfile(names['in']) if 'zeros' in kw and kw['zeros'] is not None: S = zero_range(S, kw['zeros']) if kw['log']: S = np.log10(S + 0.1) d['fig'].scene.disable_render = True d['v'].mlab_source.set(scalars=S) d['t'].text = names['label'] if 'traj' in kw: #lord have mercy d['traj_cur'][:,:,d['traj_firsti']+d['traj_step']]\ = d['traj_full'][:,:,d['traj_firsti']+d['traj_step']] x = np.hstack(d['traj_cur'][0, :, :]) y = np.hstack(d['traj_cur'][1, :, :]) z = np.hstack(d['traj_cur'][2, :, :]) tracks.mlab_source.set(x=x, y=y, z=z) d['fig'].scene.disable_render = False logprint("saving {}".format(names['out'])) imsave(names['out'], mlab.screenshot()) pass
def make_frame(t): fig.scene.disable_render = True new_y = 50 + 12.5 * t plane.implicit_plane.origin = (136, new_y + 0.5, 82) voi.set(y_min=new_y) fig.scene.disable_render = False return mlab.screenshot(antialiased=True)
def showMesh3DMayvi(mesh, interactive=True): """Proof of concept for mayavi binding. Parameters ---------- mesh : pygimli.Mesh interactive : bool """ # should avoid opening of mayavi window when building documentation if not interactive: mlab.options.offscreen = True fig = mlab.figure(bgcolor=(1, 1, 1), size=(400, 400)) # temporary VTK write & read, may be replaced with direct VTK object. tmp = "/tmp/gimli_3d_view_%s.vtk" % os.getpid() mesh.exportVTK(tmp) src = mlab.pipeline.open(tmp, figure=fig) os.remove(tmp) surf = mlab.pipeline.surface(src, figure=fig, opacity=0.5) edges = mlab.pipeline.extract_edges(surf, figure=fig) mlab.pipeline.surface(edges, color=(0, 0, 0), figure=fig) # mlab.pipeline.image_plane_widget(surf, colormap='gray', # plane_orientation='x_axes') if interactive: mlab.show() else: arr = mlab.screenshot(figure=fig, antialiased=True) plt.imshow(arr) plt.axis('off') plt.show()
def renderViews(mesh, outdir): divide1 = 10 divide2 = 10 divide3 = 10 mlab.figure(size=(1024, 768)) for i in range(divide1): for j in range(divide2): if (i * divide2 + j > 36): sys.exit(0) mesh2 = Mesh() mesh2.f = mesh.f mesh2.v = np.dot( getRotationMatrix(-pi - i * 2 * pi / divide1, -j * pi / divide2), mesh.v.T).T mlab.clf() mlab.triangular_mesh(mesh2.v[:, 0], mesh2.v[:, 1], mesh2.v[:, 2], mesh2.f) mlab.view(0, 0) img = mlab.screenshot() #pp.imsave('visualize{0}.png'.format(i * divide2 + j), img) for k in range(divide3): img2 = ndimage.rotate(img, 360 / divide3 * k, cval=128) pp.imsave(('{1}/visualize{0}.png'.format( i * divide2 * divide3 + j * divide3 + k + 1, outdir)), img2)
def make_frame(t): i = int(t * 30) pts.mlab_source.dataset.point_data.scalars = arr[:, i] im.mlab_source.set(scalars=nm_t[i]) f1.scene.render() f2.scene.render() return mlab.screenshot(antialiased=True)
def plot_scene_w_grasps(list_obj_verts, list_obj_faces, list_obj_handverts, list_obj_handfaces): figure = mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(640, 480)) mlab.clf() for i in range(len(list_obj_verts)): vertices = list_obj_verts[i] mlab.triangular_mesh(vertices[:, 0], vertices[:, 1], vertices[:, 2], list_obj_faces[i], color=(1, 0, 0), opacity=0.5) for i in range(len(list_obj_handverts)): vertices = list_obj_handverts[i] mlab.triangular_mesh(vertices[:, 0], vertices[:, 1], vertices[:, 2], list_obj_handfaces[i], color=(0, 0, 1)) mlab.view(azimuth=-90, distance=1.5) data = mlab.screenshot(figure) return data
def make_frame(t): i = int(np.ceil(t * speed_factor / dt)) source2 = runname + '_{0:04}'.format(i) + '.asc' # Load the dem into a numpy array arr = np.loadtxt(source2, skiprows=6) for i in range(0, ny): H_cent[i, 0:nx] = arr[i, 0:nx] W_cent = B_cent + H_cent idx = np.ma.masked_where(H_cent == -9999, W_cent) W_cent[np.where(np.ma.getmask(idx) == True)] = np.nan mlab.clf() # clear the figure (to reset the colors) topo = mlab.surf(xs, ys, B_cent, color=(0.5, 0.6, 0.7)) mlab.outline(topo, color=(.7, .7, .7)) surf = mlab.surf(xs, ys, W_cent + 1.e-1, color=(0.4, 0.4, 0.4)) surf.actor.property.interpolation = 'phong' surf.actor.property.specular = 1.0 surf.actor.property.specular_power = 50 mlab.text(-10, 0, 't=' + str(t * speed_factor) + 's', z=10, width=0.15, color=(0, 0, 0)) return mlab.screenshot(antialiased=True)
def make_frame(t): t = t % 8 if t < 3: az = (45 + 60 * t) % 360 mlab.view(figure=self.fig, azimuth=az, elevation=60, distance='auto', focalpoint='auto') elif t < 4: el = (60 + 60 * (t - 3)) % 180 mlab.view(figure=self.fig, azimuth=225, elevation=el, distance='auto', focalpoint='auto') elif t < 7: az = (225 - 60 * (t - 4)) % 360 mlab.view(figure=self.fig, azimuth=az, elevation=120, distance='auto', focalpoint='auto') else: el = (120 - 60 * (t - 7)) % 180 mlab.view(figure=self.fig, azimuth=45, elevation=el, distance='auto', focalpoint='auto') return mlab.screenshot(antialiased=True)
def make_frame(t): mlab.clf() # clear the figure (to reset the colors) mlab.mesh(YY, XX, ZZ(2 * np.pi * t / duration), figure=fig_myv) f = mlab.gcf() # And this. WORKS. f.scene._lift() # I found this in the net. WORKS s = mlab.screenshot(antialiased=True) #There was a problem (BEFORE) here return s
def make_frame(t): r""" :param t: time parameter, frame :return: the t-th frame of the animation """ # acquire pcd fime according to the given frame index t start_frame = 300 if int(start_frame + 10 * t) < 10: pcd_path = '/home/mark/Airport/dataset/Benewake_Horn_X2_PointCloud_000{0}.pcd'.format( str(start_frame + int(10 * t))) elif int(start_frame + 10 * t) < 100: pcd_path = '/home/mark/Airport/dataset/Benewake_Horn_X2_PointCloud_00{0}.pcd'.format( str(start_frame + int(10 * t))) else: pcd_path = '/home/mark/Airport/dataset/Benewake_Horn_X2_PointCloud_0{0}.pcd'.format( str(start_frame + int(10 * t))) print(pcd_path) # load pcd file and visualization points = o3d.io.read_point_cloud(pcd_path) points_np = np.array(points.points) mlab = viz_mayavi(points_np, vals="distance", viz=False) # crucial f = mlab.gcf() f.scene._lift() return mlab.screenshot()
def get_voxel_image(data): mlab.figure(size=(480, 340)) xx, yy, zz = np.where(data == 1) mlab.points3d(xx, yy, zz, mode="cube", color=(0, 1, 0), scale_factor=1) img = mlab.screenshot() mlab.close() return img
def sample_image(self): shot = mlab.screenshot() img = Image.fromarray(shot) if self.grayscale: img = img.convert('L') scale = self.resize_scale resized = img.resize((round(np.shape(img)[1] / scale), round(np.shape(img)[0] / scale)), Image.ANTIALIAS) return resized
def make_frame(t): pos_cmd, vel_cmd, acc_cmd = traj.get_state(t) #setCmd(group, cmd, getFbk, pos_cmd, vel_cmd, acc_cmd) X = getFKCoords(model, getFbk(group).position) p1.mlab_source.set(x=X[:, 0], y=X[:, 1], z=X[:, 2]) l1.mlab_source.set(x=X[:, 0], y=X[:, 1], z=X[:, 2]) mlab.view(distance=2, focalpoint=(0, 0, 0)) # camera angle return mlab.screenshot(antialiased=True) # return a RGB image
def make_frame(self, t): """Make a frame.""" f = mlab.gcf() f.scene.camera.azimuth(1) self.update_pts3d() return mlab.screenshot(antialiased=True)
def make_frame(self, t): mlab.clf() mlab.pipeline.volume(self.sfa, figure=self.scene.mayavi_scene) angle, _, _, _ = mlab.view() mlab.view(azimuth=angle + 2) f = mlab.gcf() f.scene._lift() return mlab.screenshot()
def make_frame(t): mlab.clf() a = mlab.surf(x, y, z(2 * np.pi * t / duration), figure=fig, colormap='cool') return mlab.screenshot(antialiased=True)
def vis_first_layer(net_input_point_cloud, first_layrer_output, vis_rate=1 / 10, square_plot_nb=16): """ input to the network should be cubic grid point cloud :param net_input_point_cloud: 1024 x 3 :param first_layrer_output: 1024 x 64 number of points x features :return: """ assert np.shape(first_layrer_output)[1] > square_plot_nb nb_points = np.shape(net_input_point_cloud)[0] fig = plt.figure(figsize=(19, 10), dpi=300, facecolor='w') small_value = np.ones([square_plot_nb, 2]) / .0 # create array of infs for i in range(np.shape(first_layrer_output)[1]): values = np.reshape(first_layrer_output[:, i], [-1]) idx = np.argpartition(values, int(nb_points * vis_rate)) idx = idx[:int(nb_points * vis_rate)] mean_value = np.mean(idx) if mean_value < np.max(small_value[:, 0]): small_value[np.argmax(small_value, axis=0), :] = np.array( [mean_value, i]) for j in range(np.shape(small_value)[0]): i = int(small_value[j, 1]) values = np.reshape(first_layrer_output[:, i], [-1]) idx = np.argpartition(values, int(nb_points * vis_rate)) idx = idx[:int(nb_points * vis_rate)] m_fig = mlab.figure(size=(500, 500), bgcolor=(1, 1, 1)) points = mlab.points3d(net_input_point_cloud[idx, 0], net_input_point_cloud[idx, 1], net_input_point_cloud[idx, 2], net_input_point_cloud[idx, 2] * 10**-2 + 1, colormap='Spectral', scale_factor=0.1, figure=m_fig, resolution=64) points.glyph.glyph_source.glyph_source.phi_resolution = 64 points.glyph.glyph_source.glyph_source.theta_resolution = 64 # mlab.gcf().scene.parallel_projection = True # parallel projection f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() # mlab.show() # for testing img = mlab.screenshot(figure=m_fig) ax = fig.add_subplot(int(math.sqrt(square_plot_nb)), int(math.sqrt(square_plot_nb)), (j + 1)) ax.imshow(img) ax.set_axis_off() mlab.close() plt.subplots_adjust(wspace=0, hspace=0) plt.show()
def mayavi_plt(): ml.test_plot3d() arr = ml.screenshot() ml.close() plt.imshow(arr) plt.axis('off') plt.show()
def make_frame(t): """ Generates and returns the frame for time t. """ dt = 1. / fps i = int(t / dt) scalars = z[i, :] ms.trait_set(scalars=scalars) date.trait_set(text=time[i]) mlab.view(azimuth=2 * np.pi * t / duration, distance=distance) return mlab.screenshot(antialiased=True) # return a RGB image
def mcrtmv(frames, dt, Lx, Ly, Nx, Ny, savemovie=False, mvname='test'): x = np.linspace(0, Lx, Nx) y = np.linspace(0, Lx, Nx) X, Y = np.meshgrid(x, y) size = 500, 500 fig = ml.figure(size=size, bgcolor=(1., 1., 1.)) #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] ml.clf(figure=fig) u = np.loadtxt('solution_%06d.txt' % 1) fname = '_tmp%07d.png' % 1 s = ml.surf(x, y, u, figure=fig, vmin=-1, vmax=1) ml.axes(extent=[0, Lx, 0, Ly, -2, 2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2, frames): u = np.loadtxt('solution_%06d.txt' % i) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname) #,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False os.system( "mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname)
def plot_mol(mesh, scalars=np.zeros(1), return_img=False): """Use mayavi to plot a molecule mesh.""" vertices, faces = mesh x, y, z = vertices[:, 0], vertices[:, 1], vertices[:, 2] mlab.figure(size=(600, 600), bgcolor=(0, 0, 0)) mlab.triangular_mesh(x, y, z, faces, scalars=scalars) if return_img: return mlab.screenshot() else: mlab.show()
def rotate_scene(t): """ Rotate the camera of the mayavi scene at time t. :param t: time in the range [0, duration] :return: a screenshot of the scene """ mlab.view(azimuth=360 / duration * t, elevation=63, distance=distance) return mlab.screenshot(figure=myfig, mode='rgb', antialiased=True) # return a RGB image
def myframe(time): global count """ Demo the bar chart plot with a 2D array. """ print("generate barchar:", time) mlab.clf() tmp = t[:count + 1] mlab.plot3d(np.sin(tmp), np.cos(tmp), 0.1 * tmp, tmp) count += 1 return mlab.screenshot(antialiased=False)
def mcrtmv(frames, dt,Lx,Ly,Nx,Ny,savemovie=False, mvname='test'): x = np.linspace(0,Lx,Nx); y = np.linspace(0,Lx,Nx); X,Y = np.meshgrid(x,y); size = 500,500 fig = ml.figure(size= size, bgcolor=(1.,1.,1.)); #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] ml.clf(figure=fig) u = np.loadtxt('solution_%06d.txt'%1); fname = '_tmp%07d.png' % 1 s = ml.surf(x,y,u,figure=fig,vmin=-1,vmax=1) ml.axes(extent=[0,Lx,0,Ly,-2,2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2,frames): u = np.loadtxt('solution_%06d.txt'%i); s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname)#,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
def mayavi_demo(): """ This function is a practice for the mayavi package in python """ # function x = np.linspace(-10,10,100) y = np.sin(x) z = np.zeros(100) # mayavi plot mlab.figure(1,bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.plot3d(x,y,z) mlab.axes(extent=[-10,10,-10,10,-10,10], \ x_axis_visibility=False, \ y_axis_visibility=False, \ z_axis_visibility=False) mlab.move(1,0,0) mlab.screenshot() #plt.show(img) mlab.show()
def screenshot_segmented(self): img = self.display_resized_image(mlab.screenshot()) array = np.asarray(img) array = array / 255 return array #array = np.asarray(resized) #np.shape(img) for dimensions return array
def mcrtmv3d(frames, dt,Lx,Ly,Nx,Ny,savemovie=False, mvname='test', vmin=-1, vmax=1): x = np.linspace(0,Lx,Nx); y = np.linspace(0,Lx,Nx); X,Y = np.meshgrid(x,y); size = 500,500 fig = ml.figure(size= size, bgcolor=(1.,1.,1.)); #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] ml.clf(figure=fig) u = np.load('solution_%06d.npy'%1); fname = '_tmp%07d.png' % 1 s = make3dplot(u) if savemovie: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2,frames): u = np.load('solution_%06d.npy'%i); u = earthSpherify(u) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i #s = make3dplot(u) if savemovie: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname)#,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False if savemovie: os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
def save_opaque_clinical_sequence( savefile, mayavi_figure ): import pylab as pl from matplotlib.backends.backend_pdf import PdfPages from mayavi import mlab with PdfPages(savefile) as pdf: for angle in sequence_3d_images( mayavi_figure ): angle() force_render( figure=mayavi_figure ) pixmap = mlab.screenshot( figure=mayavi_figure ) mpl_figure = pl.figure() pl.imshow(pixmap, figure=mpl_figure) pdf.savefig(mpl_figure)
def projection_plot(pcpath='', noise=0.05, outlier=0.05, savefig=False): f_list = [ pcpath + '/' + i for i in os.listdir(pcpath) if os.path.splitext(i)[1] == '.ply' ] fig = plt.figure(figsize=(38, 20), dpi=600, facecolor='w') colunms = 8 for i, j in enumerate(f_list): for k in range(colunms): pc = PointCloud(j) pc.down_sample(number_of_downsample=10000) pc.add_noise(noise) pc.add_outlier(outlier) pts_size = 2.5 if i == 7: pts_size = 1 try: mfig = pc.half_by_plane(n=1024, grid_resolution=(200, 200), show_result=pts_size) except: try: mfig = pc.half_by_plane(n=1024, grid_resolution=(250, 250), show_result=pts_size) except: try: mfig = pc.half_by_plane(n=1024, grid_resolution=(300, 300), show_result=pts_size) except: mfig = pc.half_by_plane(n=1024, grid_resolution=(650, 650), show_result=pts_size) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() if savefig: mlab.savefig(str(i) + str(k) + '.png') img = mlab.screenshot(figure=mfig) mlab.close() ax = fig.add_subplot(len(f_list), colunms, i * colunms + k + 1) ax.imshow(img) ax.set_axis_off() plt.subplots_adjust(wspace=0, hspace=0) if savefig: plt.savefig('projection.png') plt.show() plt.close()
def montage_screenshot(self,zoom=1.5): self._scene.disable_render = True # hide subcortical subcortical_objects = [self._pts]+self._rois_surfaces for el in subcortical_objects: el.visible = False self._scene.disable_render = False ## screenshot self._scene.parallel_projection = True self._scene.x_minus_view() self._scene.camera.view_up=[0,1,0] self._scene.camera.zoom(zoom) self._scene.render() lh_lat = mlab.screenshot() l,r=np.where(lh_lat.sum(-1).sum(0))[0][[0,-1]]+[-10,10] lh_lat = lh_lat[:,l:r] self._scene.x_plus_view() self._scene.camera.view_up=[0,1,0] self._scene.camera.zoom(zoom) self._scene.render() rh_lat = mlab.screenshot() l,r=np.where(rh_lat.sum(-1).sum(0))[0][[0,-1]]+[-10,10] rh_lat = rh_lat[:,l:r] self._scene.disable_render = True for el in subcortical_objects: el.visible = True self._scene.disable_render = False self._scene.z_plus_view() self._scene.camera.zoom(zoom) self._scene.render() lrh_sup = mlab.screenshot() self._scene.parallel_projection = False montage = np.hstack([lh_lat,lrh_sup,rh_lat]) return montage
def make_frame(t): global previous_time, alreadyZoomed # print t time = int((t / dt) % nt) # pdb.set_trace() print "t,time", t, time global sfs my_cm = n.append([[0, 0, 0, 0]], cm.gist_rainbow(n.linspace(0, 255, len(ibrains)).astype(n.uint16)), 0) my_cm = my_cm[:, :3] # pdb.set_trace() if len(sfs) != len(ibrains) or time != previous_time: mlab.clf() # clear the figure (to reset the colors) for isample in range(len(ibrains)): print "isample: %s" % isample # data = ((n.array(bs[ibrains[isample]].objects[time]['labels'])>0)*(isample+1)).astype(n.float) data = ((n.array(bs[ibrains[isample]].objects[time]["labels"]) > 0)).astype(n.float) data = imaging.sortAxes(data, [2, 1, 0]) s = ndimage.gaussian_filter(data, 1) if len(sfs) != len(ibrains): print "first time!" sf = mlab.pipeline.scalar_field(x, y, z, s) sf.spacing = spacing sfs.append(sf) else: print "only updating!" sfs[isample].set(scalar_data=s) del data, s contours = [0.5] mlab.pipeline.iso_surface(sfs[isample], contours=contours, figure=fig_myv, color=tuple(my_cm[isample + 1])) calcIso = True if t: print "rotating" scene.scene.camera.azimuth(360.0 / rotPeriod / fps) scene.scene.render() if not alreadyZoomed: scene.scene.camera.zoom(1.25) scene.scene.camera.zoom(1.25) scene.scene.camera.zoom(1.25) scene.scene.render() alreadyZoomed = True previous_time = time # return return mlab.screenshot(antialiased=True)
def to_mpl(figure=None, ax=None, size=None, antialiased=True, hide=True, fit=None, **kwargs): """Display a mayavi figure inline in an ipython notebook. This function takes a screenshot of a figure and blits it to a matplotlib figure using matplotlib.pyplot.imshow() Args: figure: A mayavi figure, if not specified, uses mlab.gcf() ax: Matplotlib axis of the destination (plt.gca() if None) size (None, tuple): if given, resize the scene in pixels (x, y) antialiased (bool): Antialias mayavi plot hide (bool): if True, try to hide the render window fit (None, bool): Resize mpl window to fit image exactly. If None, then fit if figure does not currently exist. **kwargs: passed to mayavi.mlab.screenshot() """ if figure is None: figure = mlab.gcf() if size is not None: resize(size, figure=figure) pixmap = mlab.screenshot(figure, antialiased=antialiased, **kwargs) # try to hide the window... Qt backend only if hide: hide_window(figure) if ax is None: from matplotlib import pyplot as plt # if there are no figures, and fit is None, then fit if fit is None: fit = not bool(plt.get_fignums) ax = plt.gca() if fit: pltfig = ax.figure dpi = pltfig.get_dpi() pltfig.set_size_inches([s / dpi for s in figure.scene.get_size()], forward=True) pltfig.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0) ax.imshow(pixmap) ax.axis('off')
def renderViews(mesh, outdir): divide1 = 10 divide2 = 10 divide3 = 10 mlab.figure(size=(1024, 768)) for i in range(divide1): for j in range(divide2): if i * divide2 + j > 36: sys.exit(0) mesh2 = Mesh() mesh2.f = mesh.f mesh2.v = np.dot(getRotationMatrix(-pi - i * 2 * pi / divide1, -j * pi / divide2), mesh.v.T).T mlab.clf() mlab.triangular_mesh(mesh2.v[:, 0], mesh2.v[:, 1], mesh2.v[:, 2], mesh2.f) mlab.view(0, 0) img = mlab.screenshot() # pp.imsave('visualize{0}.png'.format(i * divide2 + j), img) for k in range(divide3): img2 = ndimage.rotate(img, 360 / divide3 * k, cval=128) pp.imsave(("{1}/visualize{0}.png".format(i * divide2 * divide3 + j * divide3 + k + 1, outdir)), img2)
def make_frame(t): global previous_time#,currentAzimuth # print t time = int((t/dt)%nt) # pdb.set_trace() print 't,time',t,time global sfs # pdb.set_trace() if len(sfs) != len(ibrains) or time != previous_time: mlab.clf() # clear the figure (to reset the colors) for isample in range(len(ibrains)): data = ((n.array(bs[ibrains[isample]].objects[time]['labels'])>0)*(isample+1)).astype(n.float) data = imaging.sortAxes(data,[2,1,0]) s = ndimage.gaussian_filter(data,1) if len(sfs) != len(ibrains): print 'first time!' sf = mlab.pipeline.scalar_field(x,y,z,s) sf.spacing = spacing sfs.append(sf) else: print 'only updating!' sfs[isample].set(scalar_data=s) del data,s contours = [(isample+1)/2.] mlab.pipeline.iso_surface(sfs[isample],contours=contours,figure=fig_myv,color=tuple(my_cm[isample+1])) calcIso = True if t: print 'rotating' scene.scene.camera.azimuth(360./rotPeriod/fps) scene.scene.render() previous_time = time # return return mlab.screenshot(antialiased=True)
def make_frame(t): mlab.view(elevation=70, azimuth=360*t/4.0, distance=1400) #Camera angle return mlab.screenshot(antialiased=True)
def make_frame(t): """ Generates and returns the frame for time t. """ y = np.sin(3*u)*(0.2+0.5*np.cos(2*np.pi*t/duration)) l.mlab_source.set(y = y) # change y-coordinates of the mesh mlab.view(azimuth= 360*t/duration, distance=9) # cameraangle return mlab.screenshot(antialiased=True) # return a RGBimage
def plot3Dslice(geodata,surfs,vbounds, titlestr='', time = 0,gkey = None,cmap=defmap3d, ax=None,fig=None,method='linear',fill_value=np.nan,view = None,units='',colorbar=False,outimage=False): """ This function create 3-D slice image given either a surface or list of coordinates to slice through Inputs: geodata - A geodata object that will be plotted in 3D surfs - This is a three element list. Each element can either be altlist - A list of the altitudes that RISR parameter slices will be taken at xyvecs- A list of x and y numpy arrays that have the x and y coordinates that the data will be interpolated over. ie, xyvecs=[np.linspace(-100.0,500.0),np.linspace(0.0,600.0)] vbounds = a list of bounds for the geodata objec's parameters. ie, vbounds=[500,2000] title - A string that holds for the overall image ax - A handle for an axis that this will be plotted on. Returns a mayavi image with a surface """ if mlab is None: print('mayavi was not successfully imported') return assert geodata.coordnames.lower() =='cartesian' datalocs = geodata.dataloc xvec = sp.unique(datalocs[:,0]) yvec = sp.unique(datalocs[:,1]) zvec = sp.unique(datalocs[:,2]) assert len(xvec)*len(yvec)*len(zvec)==datalocs.shape[0] #determine if the ordering is fortran or c style ordering diffcoord = sp.diff(datalocs,axis=0) if diffcoord[0,1]!=0.0: ord='f' elif diffcoord[0,2]!=0.0: ord='c' elif diffcoord[0,0]!=0.0: if len(np.where(diffcoord[:,1])[0])==0: ord = 'f' elif len(np.where(diffcoord[:,2])[0])==0: ord = 'c' matshape = (len(yvec),len(xvec),len(zvec)) # reshape the arrays into a matricies for plotting x,y,z = [sp.reshape(datalocs[:,idim],matshape,order=ord) for idim in range(3)] if gkey is None: gkey = geodata.datanames()[0] porig = geodata.data[gkey][:,time] mlab.figure(fig) #determine if list of slices or surfaces are given islists = isinstance(surfs[0],list) if isinstance(surfs[0],np.ndarray): onedim = surfs[0].ndim==1 #get slices for each dimension out surflist = [] if islists or onedim: p = np.reshape(porig,matshape,order= ord ) xslices = surfs[0] for isur in xslices: indx = sp.argmin(sp.absolute(isur-xvec)) xtmp = x[:,indx] ytmp = y[:,indx] ztmp = z[:,indx] ptmp = p[:,indx] pmask = sp.zeros_like(ptmp).astype(bool) pmask[sp.isnan(ptmp)]=True surflist.append( mlab.mesh(xtmp,ytmp,ztmp,scalars=ptmp,vmin=vbounds[0],vmax=vbounds[1],colormap=cmap,mask=pmask)) surflist[-1].module_manager.scalar_lut_manager.lut.nan_color = 0, 0, 0, 0 yslices = surfs[1] for isur in yslices: indx = sp.argmin(sp.absolute(isur-yvec)) xtmp = x[indx] ytmp = y[indx] ztmp = z[indx] ptmp = p[indx] pmask = sp.zeros_like(ptmp).astype(bool) pmask[sp.isnan(ptmp)]=True surflist.append( mlab.mesh(xtmp,ytmp,ztmp,scalars=ptmp,vmin=vbounds[0],vmax=vbounds[1],colormap=cmap,mask=pmask)) surflist[-1].module_manager.scalar_lut_manager.lut.nan_color = 0, 0, 0, 0 zslices = surfs[2] for isur in zslices: indx = sp.argmin(sp.absolute(isur-zvec)) xtmp = x[:,:,indx] ytmp = y[:,:,indx] ztmp = z[:,:,indx] ptmp = p[:,:,indx] pmask = sp.zeros_like(ptmp).astype(bool) pmask[sp.isnan(ptmp)]=True surflist.append( mlab.mesh(xtmp,ytmp,ztmp,scalars=ptmp,vmin=vbounds[0],vmax=vbounds[1],colormap=cmap,mask=pmask)) surflist[-1].module_manager.scalar_lut_manager.lut.nan_color = 0, 0, 0, 0 else: # For a general surface. xtmp,ytmp,ztmp = surfs[:] gooddata = ~np.isnan(porig) curparam = porig[gooddata] curlocs = datalocs[gooddata] new_coords = np.column_stack((xtmp.flatten(),ytmp.flatten(),ztmp.flatten())) ptmp = spinterp.griddata(curlocs,curparam,new_coords,method,fill_value) pmask = sp.zeros_like(ptmp).astype(bool) pmask[sp.isnan(ptmp)]=True surflist.append( mlab.mesh(xtmp,ytmp,ztmp,scalars=ptmp,vmin=vbounds[0],vmax=vbounds[1],colormap=cmap,mask=pmask)) surflist[-1].module_manager.scalar_lut_manager.lut.nan_color = 0, 0, 0, 0 mlab.title(titlestr,color=(0,0,0)) #mlab.outline(color=(0,0,0)) mlab.axes(color=(0,0,0),x_axis_visibility=True,xlabel = 'x in km',y_axis_visibility=True, ylabel = 'y in km',z_axis_visibility=True,zlabel = 'z in km') mlab.orientation_axes(xlabel = 'x in km',ylabel = 'y in km',zlabel = 'z in km') if view is not None: mlab.view(view[0],view[1]) if colorbar: if len(units)>0: titlstr = gkey +' in ' +units else: titlestr = gkey mlab.colorbar(surflist[-1],title=titlstr,orientation='vertical') if outimage: arr = mlab.screenshot(fig,antialiased = True) mlab.close(fig) return arr else: return surflist
r''' Construct a general crease pattern configuration, used in the examples below demonstrating the evaluation of goal functions and constraints. ''' from sim04_map_to_surface import create_sim_step if __name__ == '__main__': import mayavi.mlab as m map_to_surface = create_sim_step() m.figure(bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.6, 0.6, 0.6)) map_to_surface.previous_task.formed_object.plot_mlab(m, lines=True) map_to_surface.formed_object.plot_mlab(m, lines=True) m.view(azimuth=120, elevation=82) m.axes(extent=[0, 2, 0, 1, 0, 1]) arr = m.screenshot() import pylab as p p.imshow(arr) p.axis('off') p.show()
def make_frame(t): view = data2[int(t*fps)] bar.mlab_source.set(scalars=view) return mlab.screenshot(antialiased=True)
def make_frame(t): """ Generates and returns the frame for time t. """ mlab.view(azimuth= 360*t/duration, distance=6*radius[IDvoid]) # camera angle return mlab.screenshot(antialiased=True) # return a RGB image
def make_frame(t): y = np.sin(3 * u) * (0.2 + 0.5 * np.cos(2 * np.pi * t / duration)) l.mlab_source.set(y=y) mlab.view(azimuth=360 * t / duration, distance=9) return mlab.screenshot(antialiased=True)
plt.xticks([]) plt.yticks([]) plt.axis('off') #Frame 1 mlab.close(all=True) loc_mat = loc_mat_list[0][0] mlab.figure( size=( 800, 800), bgcolor=(1,1,1)) vf.floc_axes( loc_mat[:, 0:3] ) mlab.view(distance = 60 ) plt.imshow( mlab.screenshot(antialiased=True) ) plt.title( r'$R_g='+str( round( move_radg[0] , 2 ) )+'$' ) mlab.close() img_name = 'images/initial_floc'+ext plt.savefig(img_name, dpi=400, bbox_inches='tight' ) fig = plt.figure( 1 ) rect=fig.patch rect.set_facecolor('white') plt.xticks([]) plt.yticks([]) plt.axis('off')
def gen_html_report(p, subjects, structurals, run_indices=None): """Generates HTML reports""" import matplotlib.pyplot as plt from ._mnefun import (_load_trans_to, plot_good_coils, _head_pos_annot, _get_bem_src_trans, safe_inserter, _prebad, _load_meg_bads, mlab_offscreen, _fix_raw_eog_cals, _handle_dict, _get_t_window, plot_chpi_snr_raw) if run_indices is None: run_indices = [None] * len(subjects) style = {'axes.spines.right': 'off', 'axes.spines.top': 'off', 'axes.grid': True} time_kwargs = dict() if 'time_unit' in mne.fixes._get_args(mne.viz.plot_evoked): time_kwargs['time_unit'] = 's' for si, subj in enumerate(subjects): struc = structurals[si] report = Report(verbose=False) print(' Processing subject %s/%s (%s)' % (si + 1, len(subjects), subj)) # raw fnames = get_raw_fnames(p, subj, 'raw', erm=False, add_splits=False, run_indices=run_indices[si]) for fname in fnames: if not op.isfile(fname): raise RuntimeError('Cannot create reports until raw data ' 'exist, missing:\n%s' % fname) raw = [read_raw_fif(fname, allow_maxshield='yes') for fname in fnames] _fix_raw_eog_cals(raw) prebad_file = _prebad(p, subj) for r in raw: _load_meg_bads(r, prebad_file, disp=False) raw = mne.concatenate_raws(raw) # sss sss_fnames = get_raw_fnames(p, subj, 'sss', False, False, run_indices[si]) has_sss = all(op.isfile(fname) for fname in sss_fnames) sss_info = mne.io.read_raw_fif(sss_fnames[0]) if has_sss else None bad_file = get_bad_fname(p, subj) if bad_file is not None: sss_info.load_bad_channels(bad_file) sss_info = sss_info.info # pca pca_fnames = get_raw_fnames(p, subj, 'pca', False, False, run_indices[si]) has_pca = all(op.isfile(fname) for fname in pca_fnames) # whitening and source localization inv_dir = op.join(p.work_dir, subj, p.inverse_dir) has_fwd = op.isfile(op.join(p.work_dir, subj, p.forward_dir, subj + p.inv_tag + '-fwd.fif')) with plt.style.context(style): ljust = 25 # # Head coils # section = 'Good HPI count' if p.report_params.get('good_hpi_count', True) and p.movecomp: t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') figs = list() captions = list() for fname in fnames: _, _, fit_data = _head_pos_annot(p, fname, prefix=' ') assert fit_data is not None fig = plot_good_coils(fit_data, show=False) fig.set_size_inches(10, 2) fig.tight_layout() figs.append(fig) captions.append('%s: %s' % (section, op.split(fname)[-1])) report.add_figs_to_section(figs, captions, section, image_format='svg') print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) # # cHPI SNR # section = 'cHPI SNR' if p.report_params.get('chpi_snr', True) and p.movecomp: t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') figs = list() captions = list() for fname in fnames: raw = mne.io.read_raw_fif(fname, allow_maxshield='yes') t_window = _get_t_window(p, raw) fig = plot_chpi_snr_raw(raw, t_window, show=False, verbose=False) fig.set_size_inches(10, 5) fig.subplots_adjust(0.1, 0.1, 0.8, 0.95, wspace=0, hspace=0.5) figs.append(fig) captions.append('%s: %s' % (section, op.split(fname)[-1])) report.add_figs_to_section(figs, captions, section, image_format='png') # svd too slow print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) # # Head movement # section = 'Head movement' if p.report_params.get('head_movement', True) and p.movecomp: print((' %s ... ' % section).ljust(ljust), end='') t0 = time.time() trans_to = _load_trans_to(p, subj, run_indices[si], raw) figs = list() captions = list() for fname in fnames: pos, _, _ = _head_pos_annot(p, fname, prefix=' ') fig = plot_head_positions(pos=pos, destination=trans_to, info=raw.info, show=False) for ax in fig.axes[::2]: """ # tighten to the sensor limits assert ax.lines[0].get_color() == (0., 0., 0., 1.) mn, mx = np.inf, -np.inf for line in ax.lines: ydata = line.get_ydata() if np.isfinite(ydata).any(): mn = min(np.nanmin(ydata), mn) mx = max(np.nanmax(line.get_ydata()), mx) """ # always show at least 10cm span, and use tight limits # if greater than that coord = ax.lines[0].get_ydata() for line in ax.lines: if line.get_color() == 'r': extra = line.get_ydata()[0] mn, mx = coord.min(), coord.max() md = (mn + mx) / 2. mn = min([mn, md - 50., extra]) mx = max([mx, md + 50., extra]) assert (mn <= coord).all() assert (mx >= coord).all() ax.set_ylim(mn, mx) fig.set_size_inches(10, 6) fig.tight_layout() figs.append(fig) captions.append('%s: %s' % (section, op.split(fname)[-1])) del trans_to report.add_figs_to_section(figs, captions, section, image_format='svg') print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) # # Raw segments # if op.isfile(pca_fnames[0]): raw_pca = mne.concatenate_raws( [mne.io.read_raw_fif(fname) for fname in pca_fnames]) section = 'Raw segments' if p.report_params.get('raw_segments', True) and has_pca: times = np.linspace(raw.times[0], raw.times[-1], 12)[1:-1] raw_plot = list() for t in times: this_raw = raw_pca.copy().crop(t - 0.5, t + 0.5) this_raw.load_data() this_raw._data[:] -= np.mean(this_raw._data, axis=-1, keepdims=True) raw_plot.append(this_raw) raw_plot = mne.concatenate_raws(raw_plot) for key in ('BAD boundary', 'EDGE boundary'): raw_plot.annotations.delete( np.where(raw_plot.annotations.description == key)[0]) new_events = np.linspace( 0, int(round(10 * raw.info['sfreq'])) - 1, 11).astype(int) new_events += raw_plot.first_samp new_events = np.array([new_events, np.zeros_like(new_events), np.ones_like(new_events)]).T fig = raw_plot.plot(group_by='selection', butterfly=True, events=new_events) fig.axes[0].lines[-1].set_zorder(10) # events fig.axes[0].set(xticks=np.arange(0, len(times)) + 0.5) xticklabels = ['%0.1f' % t for t in times] fig.axes[0].set(xticklabels=xticklabels) fig.axes[0].set(xlabel='Center of 1-second segments') fig.axes[0].grid(False) for _ in range(len(fig.axes) - 1): fig.delaxes(fig.axes[-1]) fig.set(figheight=(fig.axes[0].get_yticks() != 0).sum(), figwidth=12) fig.subplots_adjust(0.0, 0.0, 1, 1, 0, 0) report.add_figs_to_section(fig, 'Processed', section, image_format='png') # svg too slow # # PSD # section = 'PSD' if p.report_params.get('psd', True) and has_pca: t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') if p.lp_trans == 'auto': lp_trans = 0.25 * p.lp_cut else: lp_trans = p.lp_trans n_fft = 8192 fmax = raw.info['lowpass'] figs = [raw.plot_psd(fmax=fmax, n_fft=n_fft, show=False)] captions = ['%s: Raw' % section] fmax = p.lp_cut + 2 * lp_trans figs.append(raw.plot_psd(fmax=fmax, n_fft=n_fft, show=False)) captions.append('%s: Raw (zoomed)' % section) if op.isfile(pca_fnames[0]): figs.append(raw_pca.plot_psd(fmax=fmax, n_fft=n_fft, show=False)) captions.append('%s: Processed' % section) # shared y limits n = len(figs[0].axes) // 2 for ai, axes in enumerate(list(zip( *[f.axes for f in figs]))[:n]): ylims = np.array([ax.get_ylim() for ax in axes]) ylims = [np.min(ylims[:, 0]), np.max(ylims[:, 1])] for ax in axes: ax.set_ylim(ylims) ax.set(title='') for fig in figs: fig.set_size_inches(8, 8) with warnings.catch_warnings(record=True): fig.tight_layout() report.add_figs_to_section(figs, captions, section, image_format='svg') print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) # # SSP # section = 'SSP topomaps' proj_nums = _handle_dict(p.proj_nums, subj) if p.report_params.get('ssp_topomaps', True) and has_pca and \ np.sum(proj_nums) > 0: assert sss_info is not None t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') figs = [] comments = [] proj_files = get_proj_fnames(p, subj) if p.proj_extra is not None: comments.append('Custom') projs = read_proj(op.join(p.work_dir, subj, p.pca_dir, p.proj_extra)) figs.append(plot_projs_topomap(projs, info=sss_info, show=False)) if any(proj_nums[0]): # ECG if 'preproc_ecg-proj.fif' in proj_files: comments.append('ECG') figs.append(_proj_fig(op.join( p.work_dir, subj, p.pca_dir, 'preproc_ecg-proj.fif'), sss_info, proj_nums[0], p.proj_meg, 'ECG')) if any(proj_nums[1]): # EOG if 'preproc_blink-proj.fif' in proj_files: comments.append('Blink') figs.append(_proj_fig(op.join( p.work_dir, subj, p.pca_dir, 'preproc_blink-proj.fif'), sss_info, proj_nums[1], p.proj_meg, 'EOG')) if any(proj_nums[2]): # ERM if 'preproc_cont-proj.fif' in proj_files: comments.append('Continuous') figs.append(_proj_fig(op.join( p.work_dir, subj, p.pca_dir, 'preproc_cont-proj.fif'), sss_info, proj_nums[2], p.proj_meg, 'ERM')) captions = [section] + [None] * (len(comments) - 1) report.add_figs_to_section( figs, captions, section, image_format='svg', comments=comments) print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) # # Source alignment # section = 'Source alignment' source_alignment = p.report_params.get('source_alignment', True) if source_alignment is True or isinstance(source_alignment, dict) \ and has_sss and has_fwd: assert sss_info is not None kwargs = source_alignment if isinstance(source_alignment, dict): kwargs = dict(**source_alignment) else: assert source_alignment is True kwargs = dict() t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') captions = [section] try: from mayavi import mlab except ImportError: warnings.warn('Cannot plot alignment in Report, mayavi ' 'could not be imported') else: subjects_dir = mne.utils.get_subjects_dir( p.subjects_dir, raise_error=True) bem, src, trans, _ = _get_bem_src_trans( p, sss_info, subj, struc) if len(mne.pick_types(sss_info)): coord_frame = 'meg' else: coord_frame = 'head' with mlab_offscreen(): fig = mlab.figure(bgcolor=(0., 0., 0.), size=(1000, 1000)) for key, val in ( ('info', sss_info), ('subjects_dir', subjects_dir), ('bem', bem), ('dig', True), ('coord_frame', coord_frame), ('show_axes', True), ('fig', fig), ('trans', trans), ('src', src)): kwargs[key] = kwargs.get(key, val) try_surfs = ['head-dense', 'head', 'inner_skull'] for surf in try_surfs: try: mne.viz.plot_alignment(surfaces=surf, **kwargs) except Exception: pass else: break else: raise RuntimeError('Could not plot any surface ' 'for alignment:\n%s' % (try_surfs,)) fig.scene.parallel_projection = True view = list() for ai, angle in enumerate([180, 90, 0]): mlab.view(angle, 90, focalpoint=(0., 0., 0.), distance=0.6, figure=fig) view.append(mlab.screenshot(figure=fig)) mlab.close(fig) view = trim_bg(np.concatenate(view, axis=1), 0) report.add_figs_to_section(view, captions, section) print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) # # SNR # section = 'SNR' if p.report_params.get('snr', None) is not None: t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') snrs = p.report_params['snr'] if not isinstance(snrs, (list, tuple)): snrs = [snrs] for snr in snrs: assert isinstance(snr, dict) analysis = snr['analysis'] name = snr['name'] times = snr.get('times', [0.1]) inv_dir = op.join(p.work_dir, subj, p.inverse_dir) fname_inv = op.join(inv_dir, safe_inserter(snr['inv'], subj)) fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif' % (analysis, p.lp_cut, p.inv_tag, p.eq_tag, subj)) if not op.isfile(fname_inv): print(' Missing inv: %s' % op.basename(fname_inv), end='') elif not op.isfile(fname_evoked): print(' Missing evoked: %s' % op.basename(fname_evoked), end='') else: inv = mne.minimum_norm.read_inverse_operator(fname_inv) this_evoked = mne.read_evokeds(fname_evoked, name) title = ('%s<br>%s["%s"] (N=%d)' % (section, analysis, name, this_evoked.nave)) figs = plot_snr_estimate(this_evoked, inv, verbose=False) figs.axes[0].set_ylim(auto=True) captions = ('%s<br>%s["%s"] (N=%d)' % (section, analysis, name, this_evoked.nave)) report.add_figs_to_section( figs, captions, section=section, image_format='svg') print('%5.1f sec' % ((time.time() - t0),)) # # BEM # section = 'BEM' if p.report_params.get('bem', True) and has_fwd: caption = '%s<br>%s' % (section, struc) bem, src, trans, _ = _get_bem_src_trans( p, raw.info, subj, struc) if not bem['is_sphere']: subjects_dir = mne.utils.get_subjects_dir( p.subjects_dir, raise_error=True) mri_fname = op.join(subjects_dir, struc, 'mri', 'T1.mgz') if not op.isfile(mri_fname): warnings.warn( 'Could not find MRI:\n%s\nIf using surrogate ' 'subjects, use ' 'params.report_params["bem"] = False to avoid ' 'this warning', stacklevel=2) else: t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') report.add_bem_to_section(struc, caption, section, decim=10, n_jobs=1, subjects_dir=subjects_dir) print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped (sphere)' % section) else: print(' %s skipped' % section) # # Whitening # section = 'Whitening' if p.report_params.get('whitening', False): t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') whitenings = p.report_params['whitening'] if not isinstance(whitenings, (list, tuple)): whitenings = [whitenings] for whitening in whitenings: assert isinstance(whitening, dict) analysis = whitening['analysis'] name = whitening['name'] cov_name = op.join(p.work_dir, subj, p.cov_dir, safe_inserter(whitening['cov'], subj)) # Load the inverse fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif' % (analysis, p.lp_cut, p.inv_tag, p.eq_tag, subj)) if not op.isfile(cov_name): print(' Missing cov: %s' % op.basename(cov_name), end='') elif not op.isfile(fname_evoked): print(' Missing evoked: %s' % op.basename(fname_evoked), end='') else: noise_cov = mne.read_cov(cov_name) evo = mne.read_evokeds(fname_evoked, name) captions = ('%s<br>%s["%s"] (N=%d)' % (section, analysis, name, evo.nave)) fig = evo.plot_white(noise_cov, **time_kwargs) report.add_figs_to_section( fig, captions, section=section, image_format='png') print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) # # Sensor space plots # section = 'Responses' if p.report_params.get('sensor', False): t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') sensors = p.report_params['sensor'] if not isinstance(sensors, (list, tuple)): sensors = [sensors] for sensor in sensors: assert isinstance(sensor, dict) analysis = sensor['analysis'] name = sensor['name'] times = sensor.get('times', [0.1, 0.2]) fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif' % (analysis, p.lp_cut, p.inv_tag, p.eq_tag, subj)) if not op.isfile(fname_evoked): print(' Missing evoked: %s' % op.basename(fname_evoked), end='') else: this_evoked = mne.read_evokeds(fname_evoked, name) figs = this_evoked.plot_joint( times, show=False, ts_args=dict(**time_kwargs), topomap_args=dict(outlines='head', **time_kwargs)) if not isinstance(figs, (list, tuple)): figs = [figs] captions = ('%s<br>%s["%s"] (N=%d)' % (section, analysis, name, this_evoked.nave)) captions = [captions] + [None] * (len(figs) - 1) report.add_figs_to_section( figs, captions, section=section, image_format='png') print('%5.1f sec' % ((time.time() - t0),)) # # Source estimation # section = 'Source estimation' if p.report_params.get('source', False): t0 = time.time() print((' %s ... ' % section).ljust(ljust), end='') sources = p.report_params['source'] if not isinstance(sources, (list, tuple)): sources = [sources] for source in sources: assert isinstance(source, dict) analysis = source['analysis'] name = source['name'] times = source.get('times', [0.1, 0.2]) # Load the inverse inv_dir = op.join(p.work_dir, subj, p.inverse_dir) fname_inv = op.join(inv_dir, safe_inserter(source['inv'], subj)) fname_evoked = op.join(inv_dir, '%s_%d%s_%s_%s-ave.fif' % (analysis, p.lp_cut, p.inv_tag, p.eq_tag, subj)) if not op.isfile(fname_inv): print(' Missing inv: %s' % op.basename(fname_inv), end='') elif not op.isfile(fname_evoked): print(' Missing evoked: %s' % op.basename(fname_evoked), end='') else: inv = mne.minimum_norm.read_inverse_operator(fname_inv) this_evoked = mne.read_evokeds(fname_evoked, name) title = ('%s<br>%s["%s"] (N=%d)' % (section, analysis, name, this_evoked.nave)) stc = mne.minimum_norm.apply_inverse( this_evoked, inv, lambda2=source.get('lambda2', 1. / 9.), method=source.get('method', 'dSPM')) stc = abs(stc) # get clim using the reject_tmin <->reject_tmax stc_crop = stc.copy().crop( p.reject_tmin, p.reject_tmax) clim = source.get('clim', dict(kind='percent', lims=[82, 90, 98])) out = mne.viz._3d._limits_to_control_points( clim, stc_crop.data, 'viridis', transparent=True) # dummy cmap if isinstance(out[0], (list, tuple, np.ndarray)): clim = out[0] # old MNE else: clim = out[1] # new MNE (0.17+) clim = dict(kind='value', lims=clim) if not isinstance(stc, mne.SourceEstimate): print('Only surface source estimates currently ' 'supported') else: subjects_dir = mne.utils.get_subjects_dir( p.subjects_dir, raise_error=True) with mlab_offscreen(): brain = stc.plot( hemi=source.get('hemi', 'split'), views=source.get('views', ['lat', 'med']), size=source.get('size', (800, 600)), colormap=source.get('colormap', 'viridis'), transparent=source.get('transparent', True), foreground='k', background='w', clim=clim, subjects_dir=subjects_dir, ) imgs = list() for t in times: brain.set_time(t) imgs.append( trim_bg(brain.screenshot(), 255)) brain.close() captions = ['%2.3f sec' % t for t in times] report.add_slider_to_section( imgs, captions=captions, section=section, title=title, image_format='png') print('%5.1f sec' % ((time.time() - t0),)) else: print(' %s skipped' % section) report_fname = get_report_fnames(p, subj)[0] report.save(report_fname, open_browser=False, overwrite=True)
apply_transform_to_points(hmgns_world_coords, comb_trans_mat) # to get normalized view coordinates, we divide through by the fourth # element norm_view_coords = view_coords / (view_coords[:, 3].reshape(-1, 1)) # the last step is to transform from normalized view coordinates to # display coordinates. view_to_disp_mat = get_view_to_display_matrix(f.scene) disp_coords = apply_transform_to_points(norm_view_coords, view_to_disp_mat) # at this point disp_coords is an Nx4 array of homogenous coordinates # where X and Y are the pixel coordinates of the X and Y 3D world # coordinates, so lets take a screenshot of mlab view and open it # with matplotlib so we can check the accuracy img = mlab.screenshot() pl.imshow(img) for i in range(N): print 'Point %d: (x, y) ' % i, disp_coords[:, 0:2][i] pl.plot([disp_coords[:, 0][i]], [disp_coords[:, 1][i]], 'ro') pl.show() # you should check that the printed coordinates correspond to the # proper points on the screen mlab.show() #EOF
def make_frame(t): mlab.clf() # clear the figure (to reset the colors) mlab.mesh(YY,XX,ZZ(2*np.pi*t/duration), figure=fig_myv) return mlab.screenshot(antialiased=True)
from mayavi import mlab mlab.test_plot3d() arr = mlab.screenshot() import pylab as pl pl.imshow(arr) pl.axis('off') pl.show()
def mayaToMatplotlib(ax, figure): from mayavi import mlab screen = mlab.screenshot(figure=figure) ax.imshow(screen) ax.set_xticks([]) ax.set_yticks([])