def showPath(self): px, py, pz, dirx,diry,dirz = [],[],[],[],[],[] print self.path print len(self.z) for node in self.path: px.append(node[0]) py.append(node[1]) pz.append(self.z[node[0]][node[1]]) dirx.append(cos(radians(node[2]))) diry.append(sin(radians(node[2]))) dirz.append(0) px = np.array(px) py = np.array(py) pz = np.array(pz) dirx = np.array(dirx) diry = np.array(diry) dirz = np.array(dirz) mlab.quiver3d(self.x,self.y,self.z,self.gx,self.gy,self.Gt,color=(1,0,0),scale_factor=1) mlab.quiver3d(px,py,pz,dirx,diry,dirz,color=(0,0,0),scale_factor=1) mlab.surf(self.x, self.y, self.z, representation='wireframe') mlab.show()
def draw_min_feed_surface(graph): graph = sim.graph X = [] Y = [] Z = [] for day,sizes in graph.items(): for size,days_const in sizes.items(): days_const, node = sorted(days_const.items())[-1] X.append(day) Y.append(size/10.) Z.append(node.min_rate*10) # for i in range(len(X)): # print ("%d,%f,%f" % (X[i], Y[i], Z[i])) pts = mlab.points3d(X, Y, Z, Z) mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) mlab.xlabel("time") mlab.ylabel("size") mlab.zlabel("rate") mlab.show()
def show_lidar_with_boxes(pc_velo, objects, calib, img_fov=False, img_width=None, img_height=None): ''' Show all LiDAR points. Draw 3d box in LiDAR point cloud (in velo coord system) ''' if 'mlab' not in sys.modules: import mayavi.mlab as mlab from viz_util import draw_lidar_simple, draw_lidar, draw_gt_boxes3d print(('All point num: ', pc_velo.shape[0])) fig = mlab.figure(figure=None, bgcolor=(0,0,0), fgcolor=None, engine=None, size=(1000, 500)) if img_fov: pc_velo = get_lidar_in_image_fov(pc_velo, calib, 0, 0, img_width, img_height) print(('FOV point num: ', pc_velo.shape[0])) draw_lidar(pc_velo, fig=fig) for obj in objects: if obj.type=='DontCare':continue # Draw 3d bounding box box3d_pts_2d, box3d_pts_3d = utils.compute_box_3d(obj, calib.P) box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d) # Draw heading arrow ori3d_pts_2d, ori3d_pts_3d = utils.compute_orientation_3d(obj, calib.P) ori3d_pts_3d_velo = calib.project_rect_to_velo(ori3d_pts_3d) x1,y1,z1 = ori3d_pts_3d_velo[0,:] x2,y2,z2 = ori3d_pts_3d_velo[1,:] draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig) mlab.plot3d([x1, x2], [y1, y2], [z1,z2], color=(0.5,0.5,0.5), tube_radius=None, line_width=1, figure=fig) mlab.show(1)
def PlotHorizon3d(tss): """ Plot a list of horizons. Parameters ---------- tss : list of trappedsurface All the trapped surfaces to visualize. """ from mayavi import mlab cmaps = ['bone', 'jet', 'hot', 'cool', 'spring', 'summer', 'winter'] assert len(cmaps) > len(tss) extents = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] for ts, cm in zip(tss, cmaps): mlab.mesh(ts.X, ts.Y, ts.Z, colormap=cm, opacity=0.4) extents[0] = min(extents[0], np.min(ts.X)) extents[1] = max(extents[1], np.max(ts.X)) extents[2] = min(extents[2], np.min(ts.Y)) extents[3] = max(extents[3], np.max(ts.Y)) extents[4] = min(extents[4], np.min(ts.Z)) extents[5] = max(extents[5], np.max(ts.Z)) mlab.axes(extent=extents) mlab.outline(extent=extents) mlab.show()
def draw_min_cost_surface(graph): graph = sim.graph X = [] Y = [] Z = [] for day,sizes in graph.items(): for size,days_const in sizes.items(): days_const, node = sorted(days_const.items())[0] X.append(day) Y.append(size/10.) Z.append(node.min_cost) pts = mlab.points3d(X, Y, Z, Z) mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) mlab.xlabel("time") mlab.ylabel("size") mlab.zlabel("cost") mlab.show()
def visualizePrices(prices): '''Creates a mayavi visualization of a pd DataFrame containing stock prices Inputs: prices => a pd DataFrame, w/ index: dates; columns: company names ''' #Imports mlab here to delay starting of mayavi engine until necessary from mayavi import mlab #Because of current mayavi requirements, replaces dates and company names with integers x_length, y_length = prices.shape xTime = np.array([list(xrange(x_length)),] * y_length).transpose() yCompanies = np.array([list(xrange(y_length)),] * x_length) #Sort indexed prices by total return on last date lastDatePrices = prices.iloc[-1] lastDatePrices.sort_values(inplace=True) sortOrder = lastDatePrices.index zPrices = prices[sortOrder] #Create mayavi2 object fig = mlab.figure(bgcolor=(.4,.4,.4)) vis = mlab.surf(xTime, yCompanies, zPrices) mlab.outline(vis) mlab.orientation_axes(vis) #mlab.title('S&P 500 Market Data Visualization', size = .25) mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price') mlab.show()
def plot_predicted_labels(points, labels): print '[plot_points] Plotting points!' xs = np.array([int(point._x) for point in points]) ys = np.array([int(point._y) for point in points]) zs = np.array([int(point._z) for point in points]) mlab.points3d(xs, ys, zs, labels, scale_factor = .4, mode='cube') mlab.show()
def main(): parser = argparse.ArgumentParser() parser.add_argument("point_x", help="x coordinate of point.", type=int) parser.add_argument("point_y", help="y coordinate of point.", type=int) parser.add_argument("file", help="The bathymetry file.") parser.add_argument("--halo", help="Size of halo.", type=int, default=50) args = parser.parse_args() f = nc.Dataset(args.file) topo = f.variables['depth'][:] # Calculate the extents of the topo array to show. We don't just add halo to (point_x, point_y) # because it may run off the edge of the map. north_ext = min(args.point_y + args.halo, topo.shape[0]) south_ext = max(args.point_y - args.halo, 0) east_ext = min(args.point_x + args.halo, topo.shape[1]) west_ext = max(args.point_x - args.halo, 0) width = east_ext - west_ext height = north_ext - south_ext # The origin of the figure in global coordinates. origin_x = west_ext + width / 2 origin_y = south_ext + height / 2 point_y = args.point_y - origin_y point_x = args.point_x - origin_x mlab.surf(topo[south_ext:north_ext, west_ext:east_ext], warp_scale=0.005) mlab.points3d([point_y], [point_x], [0], color=(1, 0, 0), scale_factor=1.0) mlab.show()
def vis(): def vis_mesh(mesh, include_wireframe=False, **kwargs): from util3d.mayavi_vis import vis_mesh as vm v, f = (np.array(mesh[k]) for k in ('vertices', 'faces')) vm(v, f, include_wireframe=include_wireframe, **kwargs) example_ids = list(get_example_ids(cat_id, 'eval')) random.shuffle(example_ids) with all_ds: for example_id in example_ids: print(example_id) image, gt_mesh, predictions = all_ds[example_id] meshes = top_k_mesh_fn( *(np.array(predictions[k]) for k in ('probs', 'dp'))) plt.imshow(image) mlab.figure() vis_mesh(gt_mesh, color=(0, 0, 1)) for mesh in meshes: v, f, ov = (mesh[k] for k in ('vertices', 'faces', 'original_vertices')) mlab.figure() vis_mesh({'vertices': v, 'faces': f}, color=(0, 1, 0)) mlab.figure() vis_mesh({'vertices': ov, 'faces': f}, color=(1, 0, 0)) plt.show(block=False) mlab.show() plt.close()
def cluster_show(_3D_chan1, _3D_chan2, _3D_labels, n_clusters_, means, std, hulls): """ :param _3D_chan1: :param _3D_chan2: :param _3D_labels: """ red = (1.0, 0.0, 0.0) green = (0.0, 1.0, 0.1) mlab.pipeline.volume(mlab.pipeline.scalar_field(_3D_chan1), color=green) mlab.pipeline.volume(mlab.pipeline.scalar_field(_3D_chan2), color=red) mlab.show() cm = get_cmap('gist_rainbow') for i in range(0, n_clusters_): re_img = np.zeros(_3D_chan2.shape) re_img[_3D_labels == i] = _3D_chan2[_3D_labels == i] mlab.pipeline.volume(mlab.pipeline.scalar_field(re_img), color=tuple(cm(1.*i/n_clusters_)[:-1])) # mean_arr = np.zeros((n_clusters_, 3)) # std_arr = np.zeros((n_clusters_)) # for i in range(0, n_clusters_): # mean_arr[i, :] = means[i] # std_arr[i] = std[i] # x,y,z = mean_arr.T # mlab.points3d(x,y,z, std_arr) for hull in hulls: x,y,z = hull.points.T triangles = hull.simplices mlab.triangular_mesh(x, y, z, triangles, representation='wireframe', color=(0, 0, 0)) mlab.show()
def main(hdf5_path): with h5py.File(hdf5_path, 'r') as f: all_verts = np.array(f.get('all_verts')) faces = np.array(f.get('faces')) fig = mlab.figure(1, bgcolor=(1, 1, 1)) @mlab.animate(delay=1000, ui=True) def animation(): for i in count(): frame = i % all_verts.shape[2] verts = all_verts[:, :, frame].T mlab.clf() mlab.triangular_mesh( verts[:, 0], verts[:, 1], verts[:, 2], faces, color=(.9, .7, .7)) fig.scene.z_minus_view() mlab.view(azimuth=180) mlab.title('mesh %d' % i, size=0.5, height=0, color=(0, 0, 0)) yield a = animation() mlab.show()
def vis_voxels(model_id, edge_length_threshold, filled, shuffle=False): from mayavi import mlab from util3d.mayavi_vis import vis_voxels from shapenet.core import cat_desc_to_id from template_ffd.inference.voxels import get_voxel_dataset from template_ffd.data.voxels import get_gt_voxel_dataset from template_ffd.model import load_params from template_ffd.data.ids import get_example_ids cat_id = cat_desc_to_id(load_params(model_id)['cat_desc']) gt_ds = get_gt_voxel_dataset(cat_id, filled) inf_ds = get_voxel_dataset(model_id, edge_length_threshold) example_ids = get_example_ids(cat_id, 'eval') if shuffle: example_ids = list(example_ids) example_ids.shuffle with gt_ds: with inf_ds: for example_id in example_ids: gt = gt_ds[example_id].data inf = inf_ds[example_id].data vis_voxels(gt, color=(0, 0, 1)) mlab.figure() vis_voxels(inf, color=(0, 1, 0)) mlab.show()
def showDsweep(): k_s_sweep = [10**(x-5) for x in range(10)] sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)] vol_ratio_sweep = [5.0*(x+1)/100 for x in range(10)] Dmsd = numpy.load(data_dir + "/D_numpy.npy") kDa = 1.660538921e-30; mass = 40.0*kDa; viscosity = 8.9e-4; diameter = 5e-9; T = 300.0; Dbase = k_b*T/(3.0*numpy.pi*viscosity*diameter); Dmsd = Dmsd/Dbase mlab.figure(1, size=(800, 800), fgcolor=(1, 1, 1), bgcolor=(0.5, 0.5, 0.5)) mlab.clf() contours = numpy.arange(0.01,2,0.2).tolist() obj = mlab.contour3d(Dmsd,contours=contours,transparent=True,vmin=contours[0],vmax=contours[-1]) outline = mlab.outline(color=(.7, .7, .7),extent=(0,10,0,20,0,10)) axes = mlab.axes(outline, color=(.7, .7, .7), nb_labels = 5, ranges=(k_s_sweep[0], k_s_sweep[-1], sl_div_diam_sweep[0], sl_div_diam_sweep[-1], vol_ratio_sweep[0], vol_ratio_sweep[-1]), xlabel='spring stiffness', ylabel='step length', zlabel='volume ratio') mlab.colorbar(obj,title='D',nb_labels=5) mlab.show()
def surface_pattern(surface, vertex_colours): """ Plot a surface and colour it based on a vector of length number of vertices (vertex_colours). * How to obtain a pretty picture (from Mayavi's gui): - set surf_mesh color to rgb(237, 217, 221) - add a surface module derived from surf_mesh; set 'Actor' representation to wireframe; colour 'gray'. - enable contours of scalar_surf """ #surf_mesh = plot_surface(surface, name="surface pattern") fig = mlab.figure(figure="surface pattern", fgcolor=(0.5, 0.5, 0.5)) surf_mesh = mlab.triangular_mesh(surface.vertices[:, 0], surface.vertices[:, 1], surface.vertices[:, 2], surface.triangles, figure=fig) sm_obj = surf_mesh.mlab_source scalar_data = surf_mesh.mlab_source.dataset.point_data scalar_data.scalars = vertex_colours scalar_data.scalars.name = 'Scalar data' scalar_data.update() scalar_mesh = mlab.pipeline.set_active_attribute(surf_mesh, point_scalars='Scalar data') scalar_surf = mlab.pipeline.surface(scalar_mesh) mlab.show(stop=True) return sm_obj
def k_COV_plots(k_arr, COV_arr): sig_max_arr = np.zeros((len(k_arr), len(COV_arr))) wmax_arr = np.zeros((len(k_arr), len(COV_arr))) mu_r, mu_tau = 0.01, 0.1 for i, k in enumerate(k_arr): for j, cov in enumerate(COV_arr): Vf = Vf_k(k) loc_r = mu_r * (1 - cov * np.sqrt(3.0)) scale_r = cov * 2 * np.sqrt(3.0) * mu_r loc_tau = mu_tau * (1 - cov * np.sqrt(3.0)) scale_tau = cov * 2 * np.sqrt(3.0) * mu_tau reinf = ContinuousFibers(r=RV('uniform', loc=loc_r, scale=scale_r), tau=RV('uniform', loc=loc_tau, scale=scale_tau), xi=WeibullFibers(shape=7.0, sV0=0.003), V_f=Vf, E_f=200e3, n_int=100) ccb_view.model.reinforcement_lst = [reinf] sig_max, wmax = ccb_view.sigma_c_max sig_max_arr[i, j] = sig_max/Vf wmax_arr[i, j] = wmax ctrl_vars = orthogonalize([np.arange(len(k_arr)), np.arange(len(COV_arr))]) print sig_max_arr print wmax_arr mlab.surf(ctrl_vars[0], ctrl_vars[1], sig_max_arr / np.max(sig_max_arr)) mlab.surf(ctrl_vars[0], ctrl_vars[1], wmax_arr / np.max(wmax_arr)) mlab.show()
def surface_timeseries(surface, data, step=1): """ """ fig = mlab.figure(figure="surface_timeseries", fgcolor=(0.5, 0.5, 0.5)) #Plot an initial surface and colourbar #TODO: Change to use plot_surface function, see below. surf_mesh = mlab.triangular_mesh(surface.vertices[:, 0], surface.vertices[:, 1], surface.vertices[:, 2], surface.triangles, scalars=data[0, :], vmin=data.min(), vmax=data.max(), figure=fig) mlab.colorbar(object=surf_mesh, orientation="vertical") #Handle for the surface object and figure surf = surf_mesh.mlab_source #Time #TODO: Make actual time rather than points, where/if possible. tpts = data.shape[0] time_step = mlab.text(0.85, 0.125, ("0 of %s" % str(tpts)), width=0.0625, color=(1, 1, 1), figure=fig, name="counter") #Movie k = 0 while 1: if abs(k) >= tpts: k = 0 surf.set(scalars=data[k, :]) time_step.set(text=("%s of %s" % (str(k), str(tpts)))) k += step yield mlab.show(stop=True)
def surface_parcellation(cortex_boundaries, colouring, mapping_colours, colour_rgb, interaction=False): """ """ number_of_regions = len(cortex_boundaries.region_neighbours) alpha = 255 lut = numpy.zeros((number_of_regions, 4), dtype=numpy.uint8) for k in range(number_of_regions): lut[k] = numpy.hstack((colour_rgb[mapping_colours[colouring[k]]], alpha)) fig = mlab.figure(figure="surface parcellation", bgcolor=(0.0, 0.0, 0.0), fgcolor=(0.5, 0.5, 0.5)) surf_mesh = mlab.triangular_mesh(cortex_boundaries.cortex.vertices[:, 0], cortex_boundaries.cortex.vertices[:, 1], cortex_boundaries.cortex.vertices[:, 2], cortex_boundaries.cortex.triangles, scalars=cortex_boundaries.cortex.region_mapping, figure=fig) surf_mesh.module_manager.scalar_lut_manager.lut.number_of_colors = number_of_regions surf_mesh.module_manager.scalar_lut_manager.lut.table = lut #TODO: can't get region labels to associate with colorbar... #mlab.colorbar(object=surf_mesh, orientation="vertical") x = cortex_boundaries.boundary[:, 0] y = cortex_boundaries.boundary[:, 1] z = cortex_boundaries.boundary[:, 2] bpts = mlab.points3d(x, y, z, color=(0.25, 0.05, 0.05), scale_factor=1) mlab.show(stop=interaction) return surf_mesh, bpts
def mark_gt_box3d( lidar_dir, gt_boxes3d_dir, mark_dir): os.makedirs(mark_dir, exist_ok=True) fig = mlab.figure(figure=None, bgcolor=(0,0,0), fgcolor=None, engine=None, size=(500, 500)) dummy = np.zeros((10,10,3),dtype=np.uint8) for file in sorted(glob.glob(lidar_dir + '/*.npy')): name = os.path.basename(file).replace('.npy','') lidar_file = lidar_dir +'/'+name+'.npy' boxes3d_file = gt_boxes3d_dir+'/'+name+'.npy' lidar = np.load(lidar_file) boxes3d = np.load(boxes3d_file) mlab.clf(fig) draw_didi_lidar(fig, lidar, is_grid=1, is_axis=1) if len(boxes3d)!=0: draw_didi_boxes3d(fig, boxes3d) azimuth,elevation,distance,focalpoint = MM_PER_VIEW1 mlab.view(azimuth,elevation,distance,focalpoint) mlab.show(1) imshow('dummy',dummy) cv2.waitKey(1) mlab.savefig(mark_dir+'/'+name+'.png',figure=fig)
def main(): from basic_move import Box from enable.api import Container container = Container() box = Box(bounds=[30,30], position=[20,20], padding=5) container.add(box) # Create the mlab test mesh and get references to various parts of the # VTK pipeline m = mlab.test_mesh() scene = mlab.gcf().scene render_window = scene.render_window renderer = scene.renderer rwi = scene.interactor # Create the Enable Window window = EnableVTKWindow(rwi, renderer, component=container, #istyle_class = tvtk.InteractorStyleSwitch, istyle_class = tvtk.InteractorStyle, resizable = "v", bounds = [100, 100], padding_top = 20, padding_bottom = 20, padding_left = 20, ) #rwi.render() #rwi.start() mlab.show() return window, render_window
def make_figures(coor, fun, interp_results, error): '''Produce MayaVi figures for interpolation results''' mlab.figure() vmax, vmin = np.max(fun.fine), np.min(fun.fine) mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z, scalars=fun.fine, vmax=vmax, vmin=vmin) mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse, scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin) mlab.colorbar(title='Spherical Harmonic', orientation='vertical') mlab.savefig('Figures/poorfunctionsphere.png') # Figure showing results of rbf interpolation mlab.figure() mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z, scalars=interp_results, vmax=vmax, vmin=vmin) mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse, scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin) mlab.colorbar(title='Interpolation', orientation='vertical') mlab.savefig('Figures/poorinterpsphere.png') mlab.figure() mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z, scalars=error.errors, vmax=error.max, vmin=-error.max) mlab.colorbar(title='Error', orientation='vertical') # mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, scalars, scale_factor=0.1, scale_mode='none',vmax=vmax, vmin=vmin) mlab.savefig('Figures/poorerrorsphere.png') mlab.show()
def plot_both_mayavi(f, xbounds=(-1, 1), ybounds=(-1, 1), res=401): """ Plot the real and imaginary parts of the function 'f', given the bounds and resolution. """ X, Y, vals = get_vals(f, xbounds, ybounds, res) ml.mesh(X, Y, vals.real) ml.mesh(X, Y, vals.imag) ml.show()
def plot_field(self, **kwargs): "plot scalar field for elf data" if not mayavi_installed: self.__logger.warning("Mayavi is not installed on your device.") return # set parameters vmin = kwargs['vmin'] if 'vmin' in kwargs else 0.0 vmax = kwargs['vmax'] if 'vmax' in kwargs else 1.0 axis_cut = kwargs['axis_cut'] if 'axis_cut' in kwargs else 'z' nct = kwargs['nct'] if 'nct' in kwargs else 5 widths = kwargs['widths'] if 'widths' in kwargs else (1, 1, 1) elf_data, grid = self.expand_data(self.elf_data, self.grid, widths) #create pipeline field = mlab.pipeline.scalar_field(elf_data) # data source mlab.pipeline.volume(field, vmin=vmin, vmax=vmax) # put data into volumn to visualize #cut plane if axis_cut in ['Z', 'z']: plane_orientation = 'z_axes' elif axis_cut in ['Y', 'y']: plane_orientation = 'y_axes' elif axis_cut in ['X', 'x']: plane_orientation = 'x_axes' cut = mlab.pipeline.scalar_cut_plane( field.children[0], plane_orientation=plane_orientation) cut.enable_contours = True # 开启等值线显示 cut.contour.number_of_contours = nct mlab.show() #mlab.savefig('field.png', size=(2000, 2000)) return
def make_figures(coor, fun, interp_results, error): # Figure of harmoinc function on sphere in fine cordinates # Points3d showing interpolation training points coloured to their value mlab.figure() vmax, vmin = np.max(fun.fine), np.min(fun.fine) mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z, scalars=fun.fine, vmax=vmax, vmin=vmin) mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse, scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin) mlab.colorbar(title='Spherical Harmonic', orientation='vertical') # mlab.savefig('interppointssphere.png') # Figure showing results of rbf interpolation mlab.figure() mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z, scalars=interp_results, vmax=vmax, vmin=vmin) mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse, scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin) mlab.colorbar(title='Interpolation', orientation='vertical') # mlab.savefig('interpsphere.png') mlab.figure() mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z, scalars=error.errors, vmax=error.max, vmin=-error.max) mlab.colorbar(title='Error', orientation='vertical') # mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, scalars, scale_factor=0.1, scale_mode='none',vmax=vmax, vmin=vmin) # mlab.savefig('interpsphere.png') mlab.show()
def test_surface_normals(plot=False, skip_asserts=False, write_reference=False): "Test the surface normals of a horseshoe mesh" sim = openmodes.Simulation() mesh = sim.load_mesh(osp.join(mesh_dir, 'horseshoe_rect.msh')) part = sim.place_part(mesh) basis = sim.basis_container[part] r, rho = basis.integration_points(mesh.nodes, triangle_centres) normals = mesh.surface_normals r = r.reshape((-1, 3)) if write_reference: write_2d_real(osp.join(reference_dir, 'surface_r.txt'), r) write_2d_real(osp.join(reference_dir, 'surface_normals.txt'), normals) r_ref = read_2d_real(osp.join(reference_dir, 'surface_r.txt')) normals_ref = read_2d_real(osp.join(reference_dir, 'surface_normals.txt')) if not skip_asserts: assert_allclose(r, r_ref) assert_allclose(normals, normals_ref) if plot: from mayavi import mlab mlab.figure() mlab.quiver3d(r[:, 0], r[:, 1], r[:, 2], normals[:, 0], normals[:, 1], normals[:, 2], mode='cone') mlab.view(distance='auto') mlab.show()
def test3(): import numpy as np from mayavi import mlab sdf = np.load('/Users/yue/data/segment/sdf_diff_3d_1/imseg_iter_100.npz')['sdf'] mlab.contour3d(sdf[0], contours=[0]) # mlab.savefig('/Users/yue/data/segment/sdf_diff_3d_1/imseg_iter_100.png') mlab.show()
def plot_3D( self ): x = self.compute3D_plot[0] y = self.compute3D_plot[1] z = self.compute3D_plot[2] # print x_axis, y_axis, z_axis if self.autowarp_bool: x = x / x[-1] y = y / y[-1] z = z / z[-1] * self.z_scale mlab.surf( x, y , z, representation = 'wireframe' ) engine = Engine() engine.start() if len( engine.scenes ) == 75.5: engine.new_scene() surface = engine.scenes[0].children[0].children[0].children[0].children[0].children[0] surface.actor.mapper.scalar_range = np.array( [ 6.97602671, 8.8533387 ] ) surface.actor.mapper.scalar_visibility = False scene = engine.scenes[0] scene.scene.background = ( 1.0, 1.0, 1.0 ) surface.actor.property.specular_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.ambient_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.color = ( 0.0, 0.0, 0.0 ) surface.actor.property.line_width = 1. scene.scene.isometric_view() mlab.xlabel( self.x_name3D ) mlab.ylabel( self.y_name3D ) mlab.outline() mlab.show()
def main_plot3(): __import__("matplotlib").rcParams.update({'axes.labelsize': 20, 'axes.titlesize': 20}) from pylab import plot, show, imshow, figure, colorbar, xlabel, ylabel from pylab import legend, title, savefig, close, grid from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib import cm from mayavi import mlab names = ['res5.json', 'res24.json', 'res26.json', 'res28.json'] ps = _load_jsons(names, 'ps') ns = _load_jsons(names, 'ns') print(len(ps[0])) T_fine = r_[0:len(ps) - 1] N_fine = r_[:101] T_fine, N_fine = np.meshgrid(T_fine, N_fine) P_all = array([(array(p[:len(p) // 2]) + p[len(p) // 2:]) for p in ps]) P_fine = P_all[T_fine, N_fine] surf = mlab.mesh(N_fine / (len(N_fine) - 1), P_fine, T_fine / (len(ps) - 1), colormap='blue-red') surf.module_manager.scalar_lut_manager.reverse_lut = True ax = mlab.axes(xlabel='State (n)', ylabel="Population", zlabel="Time", nb_labels=6, extent=[0, 1, 0, 1, 0, 1], ranges=[0, len(N_fine) - 1, 0, 1, 0, 1]) ax.label_text_property.font_size = 5 mlab.outline(surf, color=(.7, .7, .7), extent=[0, 1, 0, 1, 0, 1]) mlab.show()
def plot_mcontour(self, ndim0, ndim1, z, show_mode): "use mayavi.mlab to plot contour." if not mayavi_installed: self.__logger.info("Mayavi is not installed on your device.") return #do 2d interpolation #get slice object s = np.s_[0:ndim0:1, 0:ndim1:1] x, y = np.ogrid[s] mx, my = np.mgrid[s] #use cubic 2d interpolation interpfunc = interp2d(x, y, z, kind='cubic') newx = np.linspace(0, ndim0, 600) newy = np.linspace(0, ndim1, 600) newz = interpfunc(newx, newy) #mlab face = mlab.surf(newx, newy, newz, warp_scale=2) mlab.axes(xlabel='x', ylabel='y', zlabel='z') mlab.outline(face) #save or show if show_mode == 'show': mlab.show() elif show_mode == 'save': mlab.savefig('mlab_contour3d.png') else: raise ValueError('Unrecognized show mode parameter : ' + show_mode) return
def plot(self): """Plots the geometry using the package Mayavi.""" print('\nPlot the three-dimensional geometry ...') from mayavi import mlab x_init = self.gather_coordinate('x', position='initial') y_init = self.gather_coordinate('y', position='initial') z_init = self.gather_coordinate('z', position='initial') x = self.gather_coordinate('x') y = self.gather_coordinate('y') z = self.gather_coordinate('z') figure = mlab.figure('body', size=(600, 600)) figure.scene.disable_render = False same = (numpy.allclose(x, x_init, rtol=1.0E-06) and numpy.allclose(y, y_init, rtol=1.0E-06) and numpy.allclose(z, z_init, rtol=1.0E-06)) if not same: mlab.points3d(x_init, y_init, z_init, name='initial', scale_factor=0.01, color=(0, 0, 1)) mlab.points3d(x, y, z, name='current', scale_factor=0.01, color=(1, 0, 0)) mlab.axes() mlab.orientation_axes() mlab.outline() figure.scene.disable_render = True mlab.show()
def plotSpherical(dataset, vertices, triangles, ptitle="", tsize=0.4, theight=0.95): """Plot the spherical data given a data set, triangle set and vertex set. The vertex set defines the direction cosines of the individual samples. The triangle set defines how the surfrace must be structured between the samples. The data set defines, for each direction cosine, the length of the vector. Args: | dataset(numpy.array(double)): array of data set values | vertices(numpy.array([])): array of direction cosine vertices as [x y z] | triangles(numpy.array([])): array of triangles as [] | ptitle(string): title or header for this display | tsize(double): title size (units not quite clear) | theight(double): title height (y value) (units not quite clear) Returns: | provides and mlab figure. Raises: | No exception is raised. """ # calculate a (x,y,z) data set from the direction vectors x = dataset * vertices[:, 0] y = dataset * vertices[:, 1] z = dataset * vertices[:, 2] mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) # Visualize the points pts = mlab.triangular_mesh(x, y, z, triangles) # z, scale_mode='none', scale_factor=0.2) mlab.title(ptitle, size=tsize, height=theight) mlab.show()
def fermi3D(procar, outcar, bands, scale=1, mode='plain', st=False, **kwargs): """ This function plots 3d fermi surface list of acceptable kwargs : plotting_package nprocess face_colors arrow_colors arrow_spin atom orbital spin """ # Initilizing the arguments : if 'plotting_package' in kwargs: plotting_package = kwargs['plotting_package'] else: plotting_package = 'mayavi' if 'nprocess' in kwargs: nprocess = kwargs['nprocess'] else: nprocess = 2 if 'face_colors' in kwargs: face_colors = kwargs['face_colors'] else: face_colors = None if 'cmap' in kwargs: cmap = kwargs['cmap'] else: cmap = 'jet' if 'atoms' in kwargs: atoms = kwargs['atoms'] else: atoms = [-1] # project all atoms if 'orbitals' in kwargs: orbitals = kwargs['orbitals'] else: orbitals = [-1] if 'spin' in kwargs: spin = kwargs['spin'] else: spin = [0] if "mask_points" in kwargs: mask_points = kwargs['mask_points'] else: mask_points = 1 if "energy" in kwargs: energy = kwargs['energy'] else: energy = 0 if "transparent" in kwargs: transparent = kwargs['transparent'] else: transparent = False if "arrow_projection" in kwargs: arrow_projection = kwargs['arrow_projection'] else: arrow_projection = 2 if plotting_package == 'mayavi': try: from mayavi import mlab from tvtk.api import tvtk except: print( "You have selected mayavi as plottin package. please install mayavi or choose a different package" ) return elif plotting_package == 'plotly': try: import plotly.plotly as py import plotly.figure_factory as ff import plotly.graph_objs as go cmap = mpl.cm.get_cmap(cmap) figs = [] except: print( "You have selected plotly as plottin package. please install plotly or choose a different package" ) return elif plotting_package == 'matplotlib': try: import matplotlib.pylab as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection except: print( "You have selected matplotlib as plotting package. please install matplotlib or choose a different package" ) return elif plotting_package == 'ipyvolume': try: import ipyvolume.pylab as ipv except: print( "You have selected ipyvolume as plotting package. please install ipyvolume or choose a different package" ) return permissive = False #get fermi from outcar outcarparser = UtilsProcar() e_fermi = outcarparser.FermiOutcar(outcar) print('Fermi=', e_fermi) e_fermi += energy #get reciprocal lattice from outcar recLat = outcarparser.RecLatOutcar(outcar) #parsing the Procar file procarFile = ProcarParser() procarFile.readFile(procar, permissive) poly = get_wigner_seitz(recLat) # plot brilliouin zone if plotting_package == 'mayavi': brillouin_point = [] brillouin_faces = [] point_count = 0 for iface in poly: single_face = [] for ipoint in iface: single_face.append(point_count) brillouin_point.append(list(ipoint)) point_count += 1 brillouin_faces.append(single_face) polydata_br = tvtk.PolyData(points=brillouin_point, polys=brillouin_faces) mlab.pipeline.surface(polydata_br, representation='wireframe', color=(0, 0, 0), line_width=4, name="BRZ") elif plotting_package == 'plotly': for iface in poly: iface = np.pad(iface, ((0, 1), (0, 0)), 'wrap') x, y, z = iface[:, 0], iface[:, 1], iface[:, 2] plane = go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='black', width=4)) figs.append(plane) elif plotting_package == 'matplotlib': fig = plt.figure() ax = fig.add_subplot(111, projection='3d') brillouin_zone = Poly3DCollection(poly, facecolors=["None"] * len(poly), alpha=1, linewidth=4) brillouin_zone.set_edgecolor("k") ax.add_collection3d(brillouin_zone, zs=0, zdir='z') br_points = [] for iface in poly: for ipoint in iface: br_points.append(ipoint) br_points = np.unique(br_points, axis=0) print('Number of bands: %d' % procarFile.bandsCount) print('Number of koints %d' % procarFile.kpointsCount) print('Number of ions: %d' % procarFile.ionsCount) print('Number of orbitals: %d' % procarFile.orbitalCount) print('Number of spins: %d' % procarFile.ispin) #selecting the data data = ProcarSelect(procarFile, deepCopy=True) if bands == -1: bands = range(data.bands.shape[1]) kvector = data.kpoints kmax = np.max(kvector) kmin = np.min(kvector) if abs(kmax) != abs(kmin): print("The mesh provided is gamma center, symmetrizing data") print("For a better fermi surface, use a non-gamma centered k-mesh") data = symmetrize(data) kvector = data.kpoints kvector_red = data.kpoints.copy() kvector_cart = np.dot(kvector_red, recLat) # This section finds points that are outside of the 1st BZ and and creates those points in the 1st BZ kvector_cart, kvector_red, has_points_out = bring_pnts_to_BZ( recLat, kvector_cart, kvector_red, br_points) # has_points_out = False # getting the mesh grid in each dirrection kx_red = np.unique(kvector_red[:, 0]) ky_red = np.unique(kvector_red[:, 1]) kz_red = np.unique(kvector_red[:, 2]) # getting the lengths between kpoints in each direction klength_x = np.abs(kx_red[-1] - kx_red[-2]) klength_y = np.abs(ky_red[-1] - ky_red[-2]) klength_z = np.abs(kz_red[-1] - kz_red[-2]) klengths = [klength_x, klength_y, klength_z] # getting number of kpoints in each direction with the addition of kpoints needed to sample the 1st BZ fully (in reduced) nkx_red = kx_red.shape[0] nky_red = ky_red.shape[0] nkz_red = kz_red.shape[0] # getting numner of kpoints in each direction provided by vasp nkx_orig = np.unique(kvector[:, 0]).shape[0] nky_orig = np.unique(kvector[:, 1]).shape[0] nkz_orig = np.unique(kvector[:, 2]).shape[0] # Amount of kpoints needed to add on to fully sample 1st BZ padding_x = (nkx_red - nkx_orig) // 2 padding_y = (nky_red - nky_orig) // 2 padding_z = (nkz_red - nkz_orig) // 2 if mode == 'parametric': data.selectIspin(spin) data.selectAtoms(atoms, fortran=False) data.selectOrbital(orbitals) elif mode == 'external': if "color_file" in kwargs: rf = open(kwargs['color_file']) lines = rf.readlines() counter = 0 color_kvector = [] color_eigen = [] for iline in lines: if counter < 2: if 'band' in iline: counter += 1 continue temp = [float(x) for x in iline.split()] color_kvector.append([temp[0], temp[1], temp[2]]) counter = -1 for iline in lines: if 'band' in iline: counter += 1 iband = int(iline.split()[-1]) color_eigen.append([]) continue color_eigen[counter].append(float(iline.split()[-1])) rf.close() color_kvector = np.array(color_kvector) color_kvector_red = color_kvector.copy() color_kvector_cart = np.dot(color_kvector, recLat) if has_points_out: color_kvector_cart, color_kvector_red, temp = bring_pnts_to_BZ( recLat, color_kvector_cart, color_kvector_red, br_points) else: print( "mode selected was external, but no color_file name was provided" ) return if st: dataX = ProcarSelect(procarFile, deepCopy=True) dataY = ProcarSelect(procarFile, deepCopy=True) dataZ = ProcarSelect(procarFile, deepCopy=True) dataX.kpoints = data.kpoints dataY.kpoints = data.kpoints dataZ.kpoints = data.kpoints dataX.spd = data.spd dataY.spd = data.spd dataZ.spd = data.spd dataX.bands = data.bands dataY.bands = data.bands dataZ.bands = data.bands dataX.selectIspin([1]) dataY.selectIspin([2]) dataZ.selectIspin([3]) dataX.selectAtoms(atoms, fortran=False) dataY.selectAtoms(atoms, fortran=False) dataZ.selectAtoms(atoms, fortran=False) dataX.selectOrbital(orbitals) dataY.selectOrbital(orbitals) dataZ.selectOrbital(orbitals) ic = 0 for iband in bands: print("Plotting band %d" % iband) eigen = data.bands[:, iband] # mapping the eigen values on the mesh grid to a matrix mapped_func, kpoint_matrix = mapping_func(kvector, eigen) # adding the points from the 2nd BZ to 1st BZ to fully sample the BZ. Check np.pad("wrap") for more information mapped_func = np.pad(mapped_func, ((padding_x, padding_x), (padding_y, padding_y), (padding_z, padding_z)), 'wrap') # Fourier interpolate the mapped function E(x,y,z) surf_equation = fft_interpolate(mapped_func, scale) # after the FFT we loose the center of the BZ, using numpy roll we bring back the center of the BZ surf_equation = np.roll(surf_equation, (scale) // 2, axis=[0, 1, 2]) try: # creating the isosurface if possible verts, faces, normals, values = measure.marching_cubes_lewiner( surf_equation, e_fermi) except: print("No isosurface for this band") continue # the vertices provided are scaled and shifted to start from zero # we center them to zero, and rescale them to fit the real BZ by multiplying by the klength in each direction for ix in range(3): verts[:, ix] -= verts[:, ix].min() verts[:, ix] -= (verts[:, ix].max() - verts[:, ix].min()) / 2 verts[:, ix] *= klengths[ix] / scale # the vertices need to be transformed to reciprocal spcae from recuded space, to find the points that are # in 2nd BZ, to be removed verts = np.dot(verts, recLat) # identifying the points in 2nd BZ and removing them if has_points_out: args = [] for ivert in range(len(verts)): args.append([br_points, verts[ivert]]) p = Pool(nprocess) results = np.array(p.map(is_outside, args)) p.close() out_verts = np.arange(0, len(results))[results] new_faces = [] # outs_bool_mat = np.zeros(shape=faces.shape,dtype=np.bool) for iface in faces: remove = False for ivert in iface: if ivert in out_verts: remove = True continue if not remove: new_faces.append(iface) faces = np.array(new_faces) print("done removing") # At this point we have the plain Fermi surface, we can color the surface depending on the projection # We create the center of faces by averaging coordinates of corners if mode == 'parametric': character = data.spd[:, iband] centers = np.zeros(shape=(len(faces), 3)) for iface in range(len(faces)): centers[iface, 0:3] = np.average(verts[faces[iface]], axis=0) colors = interpolate.griddata(kvector_cart, character, centers, method="nearest") elif mode == 'external': character = np.array(color_eigen[ic]) ic += 1 centers = np.zeros(shape=(len(faces), 3)) for iface in range(len(faces)): centers[iface, 0:3] = np.average(verts[faces[iface]], axis=0) colors = interpolate.griddata(color_kvector_cart, character, centers, method="nearest") if st: projection_x = dataX.spd[:, iband] projection_y = dataY.spd[:, iband] projection_z = dataZ.spd[:, iband] verts_spin, faces_spin, normals, values = measure.marching_cubes_lewiner( mapped_func, e_fermi) for ix in range(3): verts_spin[:, ix] -= verts_spin[:, ix].min() verts_spin[:, ix] -= (verts_spin[:, ix].max() - verts_spin[:, ix].min()) / 2 verts_spin[:, ix] *= klengths[ix] verts_spin = np.dot(verts_spin, recLat) if has_points_out: args = [] for ivert in range(len(verts_spin)): args.append([br_points, verts_spin[ivert]]) p = Pool(nprocess) results = np.array(p.map(is_outside, args)) p.close() out_verts = np.arange(0, len(results))[results] new_faces = [] for iface in faces_spin: remove = False for ivert in iface: if ivert in out_verts: remove = True continue if not remove: new_faces.append(iface) faces_spin = np.array(new_faces) centers = np.zeros(shape=(len(faces_spin), 3)) for iface in range(len(faces_spin)): centers[iface, 0:3] = np.average(verts_spin[faces_spin[iface]], axis=0) colors1 = interpolate.griddata(kvector_cart, projection_x, centers, method="linear") colors2 = interpolate.griddata(kvector_cart, projection_y, centers, method="linear") colors3 = interpolate.griddata(kvector_cart, projection_z, centers, method="linear") spin_arrows = np.vstack((colors1, colors2, colors3)).T if plotting_package == 'mayavi': polydata = tvtk.PolyData(points=verts, polys=faces) if face_colors != None: mlab.pipeline.surface(polydata, representation='surface', color=face_colors[ic], opacity=1, name='band-' + str(iband)) ic += 1 else: if mode == 'plain': if not (transparent): s = mlab.pipeline.surface(polydata, representation='surface', color=(0, 0.5, 1), opacity=1, name='band-' + str(iband)) elif mode == 'parametric' or mode == 'external': polydata.cell_data.scalars = colors polydata.cell_data.scalars.name = 'celldata' mlab.pipeline.surface(polydata, vmin=0, vmax=colors.max(), colormap=cmap) cb = mlab.colorbar(orientation='vertical') if st: x, y, z = list(zip(*centers)) u, v, w = list(zip(*spin_arrows)) pnts = mlab.quiver3d(x, y, z, u, v, w, line_width=5, mode='arrow', resolution=25, reset_zoom=False, name='spin-' + str(iband), mask_points=mask_points, scalars=spin_arrows[:, arrow_projection], vmin=-1, vmax=1, colormap=cmap) pnts.glyph.color_mode = 'color_by_scalar' pnts.glyph.glyph_source.glyph_source.shaft_radius = 0.05 pnts.glyph.glyph_source.glyph_source.tip_radius = 0.1 elif plotting_package == 'plotly': if mode == 'plain': if not (transparent): x, y, z = zip(*verts) fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, simplices=faces, title="band-%d" % ic) figs.append(fig['data'][0]) elif mode == 'parametric' or mode == 'external': face_colors = cmap(colors) colormap = [ 'rgb(%i,%i,%i)' % (x[0], x[1], x[2]) for x in (face_colors * 255).round() ] x, y, z = zip(*verts) fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, show_colorbar=True, title="band-%d" % ic) figs.append(fig['data'][0]) elif plotting_package == 'matplotlib': if mode == 'plain': x, y, z = zip(*verts) ax.plot_trisurf(x, y, faces, z, linewidth=0.2, antialiased=True) elif mode == 'parametric' or mode == 'external': print( 'coloring the faces is not implemented in matplot lib, please use another plotting package.we recomend mayavi.' ) elif plotting_package == 'ipyvolume': if mode == 'plain': ipv.figure() ipv.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], triangles=faces) elif mode == 'paramteric' or mode == 'external': face_colors = cmap(colors) colormap = [ 'rgb(%i,%i,%i)' % (x[0], x[1], x[2]) for x in (face_colors * 255).round() ] ipv.figure() ipv.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], triangles=faces, color=cmap) if plotting_package == 'mayavi': mlab.colorbar(orientation='vertical') #,label_fmt='%.1f') mlab.show() elif plotting_package == 'plotly': layout = go.Layout(showlegend=False) fig = go.Figure(data=figs, layout=layout) py.iplot(fig) elif plotting_package == 'matplotlib': plt.show() elif plotting_package == 'ipyvolume': ipv.show() return
surf_data_lh = project_volume_data(mri_file, "lh", reg_file) surf_data_rh = project_volume_data(mri_file, "rh", reg_file) qmri_file = '/Volumes/jamalw/MES/prototype/link/scripts/data/searchlight_output/HMM_searchlight_human_bounds_fit_to_all/ttest_results/qstats_map_both_runs.nii.gz' qdata_lh = project_volume_data(qmri_file, "lh", reg_file) surf_data_lh[np.logical_or(qdata_lh > 0.007, surf_data_lh < 0)] = 0 qdata_rh = project_volume_data(qmri_file, "rh", reg_file) surf_data_rh[np.logical_or(qdata_rh > 0.007, surf_data_rh < 0)] = 0 brain.add_overlay(surf_data_lh, min=minval, max=maxval, name="thirty_sec_lh", hemi='lh', sign="pos") brain.add_overlay(surf_data_rh, min=minval, max=maxval, name="thirty_sec_rh", hemi='rh', sign="pos") brain.save_image("human_bounds_match_plots/srmk_30/zstats_ttest_both_runs.png") mlab.show() brain.show_view(view)
def show(self): mlab.show()
exit(0) #---------------------------------------------------------- lidar = dataset.velo[0] objs = objects[0] gt_labels, gt_boxes, gt_boxes3d = obj_to_gt(objs) fig = mlab.figure(figure=None, bgcolor=(0, 0, 0), fgcolor=None, engine=None, size=(1000, 500)) draw_lidar(lidar, fig=fig) draw_gt_boxes3d(gt_boxes3d, fig=fig) mlab.show(1) print('** calling lidar_to_tops() **') if 0: top, top_image = lidar_to_top(lidar) rgb = dataset.rgb[0][0] else: top = np.load('/home/hhs/4T/datasets/dummy_datas/one_frame/top.npy') top_image = cv2.imread( '/home/hhs/4T/datasets/dummy_datas/one_frame/top_image.png') rgb = np.load('/home/hhs/4T/datasets/dummy_datas/one_frame/rgb.npy') rgb = (rgb * 255).astype(np.uint8) rgb = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) # -----------
def show(): mlab.show()
def fig_v2(structure, colors): for i in range(len(structure)): mlab.points3d(structure[i][0], structure[i][1], structure[i][2], mode='point', name='dinosaur', color=colors[i]) mlab.show()
def fig_v1(structure): mlab.points3d(structure[:, 0], structure[:, 1], structure[:, 2], mode= 'point', name = 'dinosaur') mlab.show()
def plot_3d_volume(power_spect): """Generate a 3d plot given a numpy array with Mayavi. This function can be used to plot any three-dimensional field, passed as a np.array. It uses the `mayavi.tools.pipeline.volume` from Mayavi: http://docs.enthought.com/mayavi/mayavi/auto/mlab_pipeline_other_functions.html#volume In the plot it is assumed that the elements of the array are equally spaced. Parameters: power_spect: np.ndarray, shape [n_px, n_py, n_pz] Array containing a three-dimensional quantity (i.e. field). .. codeauthor:: Angelo Ziletti <*****@*****.**> """ try: from mayavi import mlab except ImportError: raise ImportError( "Could not import Mayavi. Mayavi is required for 3d plotting.") mlab.figure(1, bgcolor=(0.5, 0.5, 0.5), size=(800, 800)) mlab.options.offscreen = False mlab.clf() # remove nan and normalize the spectrum for plotting purposes only power_spect_plot = np.nan_to_num(power_spect) power_spect_plot_norm = (power_spect_plot - power_spect_plot.min()) / ( power_spect_plot.max() - power_spect_plot.min()) src = mlab.pipeline.scalar_field(power_spect_plot_norm) field_min = power_spect_plot_norm.min() field_max = power_spect_plot_norm.max() mlab.pipeline.volume(src, vmin=0., vmax=field_min + .5 * (field_max - field_min)) mlab.colorbar(title='Field intensity', orientation='vertical') # insert plane parallel to axis passing through the origin mlab.pipeline.image_plane_widget( src, plane_orientation='x_axes', slice_index=power_spect_plot_norm.shape[0] / 2, ) mlab.pipeline.image_plane_widget( src, plane_orientation='y_axes', slice_index=power_spect_plot_norm.shape[1] / 2, ) mlab.pipeline.image_plane_widget( src, plane_orientation='z_axes', slice_index=power_spect_plot_norm.shape[2] / 2, ) mlab.colorbar(title='Field intensity', orientation='vertical') mlab.show() mlab.close(all=True)
def plot(self, labels=False, show=True): ''' This function plots 2D and 3D models :param labels: :param show: If True, the plots are displayed at the end of this call. If False, plt.show() should be called outside this function :return: ''' if self.k == 3: import mayavi.mlab as mlab predictFig = mlab.figure(figure='predict') errorFig = mlab.figure(figure='error') if self.testfunction: truthFig = mlab.figure(figure='test') dx = 1 pts = 25j X, Y, Z = np.mgrid[0:dx:pts, 0:dx:pts, 0:dx:pts] scalars = np.zeros(X.shape) errscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): errscalars[i][j][k1] = self.predicterr_normalized( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) scalars[i][j][k1] = self.predict_normalized( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) if self.testfunction: tfscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): tfplot = tfscalars[i][j][k1] = self.testfunction( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) plot = mlab.contour3d(tfscalars, contours=15, transparent=True, figure=truthFig) plot.compute_normals = False # obj = mlab.contour3d(scalars, contours=10, transparent=True) plot = mlab.contour3d(scalars, contours=15, transparent=True, figure=predictFig) plot.compute_normals = False errplt = mlab.contour3d(errscalars, contours=15, transparent=True, figure=errorFig) errplt.compute_normals = False if show: mlab.show() if self.k == 2: fig = pylab.figure(figsize=(8, 6)) samplePoints = zip(*self.X) # Create a set of data to plot plotgrid = 61 x = np.linspace(self.normRange[0][0], self.normRange[0][1], num=plotgrid) y = np.linspace(self.normRange[1][0], self.normRange[1][1], num=plotgrid) x = np.linspace(0, 1, num=plotgrid) y = np.linspace(0, 1, num=plotgrid) X, Y = np.meshgrid(x, y) # Predict based on the optimized results zs = np.array([ self.predict([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y)) ]) Z = zs.reshape(X.shape) # Z = (Z*(self.ynormRange[1]-self.ynormRange[0]))+self.ynormRange[0] #Calculate errors zse = np.array([ self.predict_var([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y)) ]) Ze = zse.reshape(X.shape) spx = (self.X[:, 0] * (self.normRange[0][1] - self.normRange[0][0]) ) + self.normRange[0][0] spy = (self.X[:, 1] * (self.normRange[1][1] - self.normRange[1][0]) ) + self.normRange[1][0] contour_levels = 25 ax = fig.add_subplot(222) CS = pylab.contourf(X, Y, Ze, contour_levels) pylab.colorbar() pylab.plot(spx, spy, 'ow') ax = fig.add_subplot(221) if self.testfunction: # Setup the truth function zt = self.testfunction(np.array(zip(np.ravel(X), np.ravel(Y)))) ZT = zt.reshape(X.shape) CS = pylab.contour(X, Y, ZT, contour_levels, colors='k', zorder=2) # contour_levels = np.linspace(min(zt), max(zt),50) if self.testfunction: contour_levels = CS.levels delta = np.abs(contour_levels[0] - contour_levels[1]) contour_levels = np.insert(contour_levels, 0, contour_levels[0] - delta) contour_levels = np.append(contour_levels, contour_levels[-1] + delta) CS = plt.contourf(X, Y, Z, contour_levels, zorder=1) pylab.plot(spx, spy, 'ow', zorder=3) pylab.colorbar() ax = fig.add_subplot(212, projection='3d') # fig = plt.gcf() #ax = fig.gca(projection='3d') ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.4) if self.testfunction: ax.plot_wireframe(X, Y, ZT, rstride=3, cstride=3) if show: pylab.show()
def plot_concentric_shells(vox_by_slices, base_folder, idx_slices=None, create_animation=False): """Plot the concentric shells for a given three-dimensional volumetric shape. The volumetric shape is the three-dimensional diffraction intensity, as calculated by :py:mod:`ai4materials.descriptors.diffraction3d.Diffraction3D`. To plot the concentric shells for different voxel np.ndarray shapes simply change ``x, y, z = np.mgrid[0:176:176j, 0:176:176j, 0:176:176j]`` to your desire meshgrid. Parameters: vox_by_slices: np.ndarray, shape [n_slices, n_px, n_py, n_pz] 4-dimensional array containing each concentric shell obtained from :py:mod:`ai4materials.descriptors.diffraction3d.Diffraction3D`. ``n_px``, ``n_py``, ``n_pz`` are given by the interpolation and the region of the space considered. In our case, ``n_slices=52``, ``n_px=n_py=n_pz=176``. base_folder: str Folder to save the figures generated. The figures are saved in a subfolder folder ``shells_png`` of ``base_folder``. idx_slices: list of int, optional (default=None) List of integers defining which concentric shells to plot. If `None`, all concentric shells are plotted. create_animation: bool, optional (default=True) If `True` create an animation containing all concentric shells. .. codeauthor:: Angelo Ziletti <*****@*****.**> """ try: from mayavi import mlab except ImportError: raise ImportError( "Could not import Mayavi. Mayavi is required for 3d plotting.") if idx_slices is None: idx_slices = range(1, vox_by_slices.shape[0], 1) # create folder for saving files shells_images_folder = os.path.join(base_folder, 'png_shells') if not os.path.exists(shells_images_folder): os.makedirs(shells_images_folder) filename_png_list = [] x, y, z = np.mgrid[0:176:176j, 0:176:176j, 0:176:176j] mlab.clf() for idx_slice in idx_slices: mlab.options.offscreen = False filename_png = os.path.join(shells_images_folder, 'desc_slice_' + str(idx_slice) + '.png') filename_png_list.append(filename_png) scalars = vox_by_slices[idx_slice] c_of_mass = ndimage.measurements.center_of_mass(scalars) logger.info("Center of mass: {}".format(c_of_mass)) logger.info("Max scalar field: {} for shell {}".format( scalars.max(), idx_slice)) expansion = 0.0 x_new = x * (1.0 + expansion * idx_slice) y_new = y * (1.0 + expansion * idx_slice) z_new = z * (1.0 + expansion * idx_slice) obj = mlab.contour3d(x_new, y_new, z_new, scalars, contours=50, opacity=.2) obj.scene.disable_render = True obj.scene.anti_aliasing_frames = 0 mlab.colorbar(title='Field intensity', orientation='vertical') mlab.view() mlab.savefig(filename=filename_png) mlab.show() mlab.close(all=True) if create_animation: pass # import imageio # with imageio.get_writer('/home/ziletti/Documents/calc_xray/rot_inv_3d/png_slices/descriptor.gif', mode='I', # fps=2) as writer: # for filename_png in filename_png_list: # image = imageio.imread(filename_png) # writer.append_data(image) # for filename_png in filename_png_list: # # os.remove(filename_png)
def demo(): import mayavi.mlab as mlab from viz_util import draw_lidar, draw_lidar_simple, draw_gt_boxes3d dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object')) data_idx = 0 # Load data from dataset objects = dataset.get_label_objects(data_idx) objects[0].print_object() img = dataset.get_image(data_idx) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_height, img_width, img_channel = img.shape print(('Image shape: ', img.shape)) pc_velo = dataset.get_lidar(data_idx)[:, 0:3] calib = dataset.get_calibration(data_idx) # Draw lidar in rect camera coord # print(' -------- LiDAR points in rect camera coordination --------') # pc_rect = calib.project_velo_to_rect(pc_velo) # fig = draw_lidar_simple(pc_rect) # raw_input() # Draw 2d and 3d boxes on image print(' -------- 2D/3D bounding boxes in images --------') show_image_with_boxes(img, objects, calib) raw_input() # Show all LiDAR points. Draw 3d box in LiDAR point cloud print( ' -------- LiDAR points and 3D boxes in velodyne coordinate --------') # show_lidar_with_boxes(pc_velo, objects, calib) # raw_input() show_lidar_with_boxes(pc_velo, objects, calib, True, img_width, img_height) raw_input() # Visualize LiDAR points on images print(' -------- LiDAR points projected to image plane --------') show_lidar_on_image(pc_velo, img, calib, img_width, img_height) raw_input() # Show LiDAR points that are in the 3d box print(' -------- LiDAR points in a 3D bounding box --------') box3d_pts_2d, box3d_pts_3d = utils.compute_box_3d(objects[0], calib.P) box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d) box3droi_pc_velo, _ = extract_pc_in_box3d(pc_velo, box3d_pts_3d_velo) print(('Number of points in 3d box: ', box3droi_pc_velo.shape[0])) fig = mlab.figure(figure=None, bgcolor=(0, 0, 0), fgcolor=None, engine=None, size=(1000, 500)) draw_lidar(box3droi_pc_velo, fig=fig) draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig) mlab.show(1) raw_input() # UVDepth Image and its backprojection to point clouds print(' -------- LiDAR points in a frustum from a 2D box --------') imgfov_pc_velo, pts_2d, fov_inds = get_lidar_in_image_fov( pc_velo, calib, 0, 0, img_width, img_height, True) imgfov_pts_2d = pts_2d[fov_inds, :] imgfov_pc_rect = calib.project_velo_to_rect(imgfov_pc_velo) cameraUVDepth = np.zeros_like(imgfov_pc_rect) cameraUVDepth[:, 0:2] = imgfov_pts_2d cameraUVDepth[:, 2] = imgfov_pc_rect[:, 2] # Show that the points are exactly the same backprojected_pc_velo = calib.project_image_to_velo(cameraUVDepth) print(imgfov_pc_velo[0:20]) print(backprojected_pc_velo[0:20]) fig = mlab.figure(figure=None, bgcolor=(0, 0, 0), fgcolor=None, engine=None, size=(1000, 500)) draw_lidar(backprojected_pc_velo, fig=fig) raw_input() # Only display those points that fall into 2d box print(' -------- LiDAR points in a frustum from a 2D box --------') xmin, ymin, xmax, ymax = \ objects[0].xmin, objects[0].ymin, objects[0].xmax, objects[0].ymax boxfov_pc_velo = \ get_lidar_in_image_fov(pc_velo, calib, xmin, ymin, xmax, ymax) print(('2d box FOV point num: ', boxfov_pc_velo.shape[0])) fig = mlab.figure(figure=None, bgcolor=(0, 0, 0), fgcolor=None, engine=None, size=(1000, 500)) draw_lidar(boxfov_pc_velo, fig=fig) mlab.show(1) raw_input()
def show_surf(subject, hemi, type, patch=None, curv=True, freesurfer_subject_dir=None): """Show a surface from a Freesurfer subject directory """ from mayavi import mlab from tvtk.api import tvtk pts, polys, idx = get_surf(subject, hemi, type, patch, freesurfer_subject_dir=freesurfer_subject_dir) if curv: curv = get_curv(subject, hemi, freesurfer_subject_dir=freesurfer_subject_dir) else: curv = idx fig = mlab.figure() src = mlab.pipeline.triangular_mesh_source(pts[:, 0], pts[:, 1], pts[:, 2], polys, scalars=curv, figure=fig) norms = mlab.pipeline.poly_data_normals(src, figure=fig) norms.filter.splitting = False surf = mlab.pipeline.surface(norms, figure=fig) surf.parent.scalar_lut_manager.set(lut_mode='RdBu', data_range=[-1, 1], use_default_range=False) cursors = mlab.pipeline.scalar_scatter([0], [0], [0]) glyphs = mlab.pipeline.glyph(cursors, figure=fig) glyphs.glyph.glyph_source.glyph_source = glyphs.glyph.glyph_source.glyph_dict[ 'axes'] fig.scene.background = (0, 0, 0) fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain() path = os.path.join(os.environ['SUBJECTS_DIR'], subject) def picker_callback(picker): if picker.actor in surf.actor.actors: npts = np.append(cursors.data.points.to_array(), [pts[picker.point_id]], axis=0) cursors.data.points = npts print(picker.point_id) x, y, z = pts[picker.point_id] with open(os.path.join(path, 'tmp', 'edit.dat'), 'w') as fp: fp.write('%f %f %f\n' % (x, y, z)) picker = fig.on_mouse_pick(picker_callback) picker.tolerance = 0.01 mlab.show() return fig, surf
def display_simple_using_mayavi_(vf_list, pointcloud_list, minmax=(-1, 1), mayavi_wireframe=False, opacity=1.0): """ opacity can be either a list of a constant """ from mayavi import mlab if type(opacity) is list: opacities = opacity # 1.0 else: opacities = [opacity] + [0.2] * (len(vf_list) - 1) # 1.0, 0.2 #0.1 i = 0 for vf in vf_list: verts, faces = vf if verts is None: continue if verts.size == 0: print("Warning: empty vertices") continue if faces.size == 0: print("Warning: no faces") continue mlab.triangular_mesh( [vert[0] for vert in verts], [vert[1] for vert in verts], [vert[2] for vert in verts], faces, representation="surface" if not mayavi_wireframe else "wireframe", opacity=opacities[i], scale_factor=100.0) i += 1 color_list = [(1, 0, 0), (0, 0, 0), (1, 1, 0), (0, 0, 1), (0, 1, 0)] i = 0 for c in pointcloud_list: #print c[:,0:3] mlab.points3d(c[:, 0], c[:, 1], c[:, 2], color=color_list[i], scale_factor=0.2) i += 1 del i #if pointcloud_list[0].shape[0] == pointcloud_list[1].shape[0]: # print "PLOT3d" # c0 = pointcloud_list[0][np.newaxis, :, :] # 2 x N x 4 # c1 = pointcloud_list[1][np.newaxis, :, :] # c01 = np.concatenate((c0, c1), axis=0) # for i in range(c01.shape[1]): # #print c01[:,i,0], c01[:,i,1], c01[:,i,3] # mlab.plot3d(c01[:,i,0],c01[:,i,1],c01[:,i,3]) # #exit() # pass # #mlab.plot3d((c01[:,:,0]), (c01[:,:,1]), (c01[:,:,3])) (RANGE_MIN, RANGE_MAX) = minmax x = np.linspace(RANGE_MIN, RANGE_MAX, 2).reshape(2, 1) y = np.zeros((2, 1)) z = np.zeros((2, 1)) mlab.plot3d(x, y, z, line_width=3, name="x-axis") mlab.plot3d(y, x, z, line_width=3, name="y-axis") mlab.plot3d(z, y, x, line_width=3, name="z-axis") mlab.text3d(RANGE_MAX, 0, 0, "x", scale=0.3) mlab.text3d(0, RANGE_MAX, 0, "y", scale=0.3) mlab.text3d(0, 0, RANGE_MAX, "z", scale=0.3) mlab.text3d(RANGE_MIN, 0, 0, "-x", scale=0.3) mlab.text3d(0, RANGE_MIN, 0, "-y", scale=0.3) mlab.text3d(0, 0, RANGE_MIN, "-z", scale=0.3) mlab.show()
def set_interval(self, period, callback, *args): Thread(target=self.call_at_interval, args=(period, callback, args)).start() mlab.show()
def draw_3d(self): """ Draw various 3D plots """ self.init_axes() bb = fb.fil[0]['ba'][0] aa = fb.fil[0]['ba'][1] zz = np.array(fb.fil[0]['zpk'][0]) pp = np.array(fb.fil[0]['zpk'][1]) wholeF = fb.fil[0]['freqSpecsRangeType'] != 'half' # not used f_S = fb.fil[0]['f_S'] N_FFT = params['N_FFT'] alpha = self.diaAlpha.value() / 10. cmap = cm.get_cmap(str(self.cmbColormap.currentText())) if self.chkColormap_r.isChecked(): cmap = cmap.reversed() # use reversed colormap # Number of Lines /step size for H(f) stride, mesh, contour3d: stride = 10 - self.diaHatch.value() NL = 3 * self.diaHatch.value() + 5 surf_enabled = qget_cmb_box(self.cmbMode3D, data=False) in {'Surf', 'Contour'} self.cmbColormap.setEnabled(surf_enabled) self.chkColormap_r.setEnabled(surf_enabled) self.chkLighting.setEnabled(surf_enabled) self.chkColBar.setEnabled(surf_enabled) self.diaAlpha.setEnabled(surf_enabled or self.chkContour2D.isChecked()) #cNorm = colors.Normalize(vmin=0, vmax=values[-1]) #scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) #----------------------------------------------------------------------------- # Calculate H(w) along the upper half of unity circle #----------------------------------------------------------------------------- [w, H] = sig.freqz(bb, aa, worN=N_FFT, whole=True) H = np.nan_to_num(H) # replace nans and inf by finite numbers H_abs = abs(H) H_max = max(H_abs) H_min = min(H_abs) #f = w / (2 * pi) * f_S # translate w to absolute frequencies #F_min = f[np.argmin(H_abs)] plevel_rel = 1.05 # height of plotted pole position relative to zmax zlevel_rel = 0.1 # height of plotted zero position relative to zmax if self.chkLog.isChecked(): # logarithmic scale # suppress "divide by zero in log10" warnings old_settings_seterr = np.seterr() np.seterr(divide='ignore') bottom = np.floor(max(self.zmin_dB, 20 * log10(H_min)) / 10) * 10 top = self.zmax_dB top_bottom = top - bottom zlevel = bottom - top_bottom * zlevel_rel if self.cmbMode3D.currentText( ) == 'None': # "Poleposition" for H(f) plot only plevel_top = 2 * bottom - zlevel # height of displayed pole position plevel_btm = bottom else: plevel_top = top + top_bottom * (plevel_rel - 1) plevel_btm = top np.seterr(**old_settings_seterr) else: # linear scale bottom = max(self.zmin, H_min) # min. display value top = self.zmax # max. display value top_bottom = top - bottom # top = zmax_rel * H_max # calculate display top from max. of H(f) zlevel = bottom + top_bottom * zlevel_rel # height of displayed zero position if self.cmbMode3D.currentText( ) == 'None': # "Poleposition" for H(f) plot only #H_max = np.clip(max(H_abs), 0, self.zmax) # make height of displayed poles same to zeros plevel_top = bottom + top_bottom * zlevel_rel plevel_btm = bottom else: plevel_top = plevel_rel * top plevel_btm = top # calculate H(jw)| along the unity circle and |H(z)|, each clipped # between bottom and top H_UC = H_mag(bb, aa, self.xy_UC, top, H_min=bottom, log=self.chkLog.isChecked()) Hmag = H_mag(bb, aa, self.z, top, H_min=bottom, log=self.chkLog.isChecked()) #=============================================================== ## plot Unit Circle (UC) #=============================================================== if self.chkUC.isChecked(): # Plot unit circle and marker at (1,0): self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, ones(len(self.xy_UC)) * bottom, lw=2, color='k') self.ax3d.plot([0.97, 1.03], [0, 0], [bottom, bottom], lw=2, color='k') #=============================================================== ## plot ||H(f)| along unit circle as 3D-lineplot #=============================================================== if self.chkHf.isChecked(): self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, H_UC, alpha=0.8, lw=4) # draw once more as dashed white line to improve visibility self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, H_UC, 'w--', lw=4) if stride < 10: # plot thin vertical line every stride points on the UC for k in range(len(self.xy_UC[::stride])): self.ax3d.plot([ self.xy_UC.real[::stride][k], self.xy_UC.real[::stride][k] ], [ self.xy_UC.imag[::stride][k], self.xy_UC.imag[::stride][k] ], [ np.ones(len(self.xy_UC[::stride]))[k] * bottom, H_UC[::stride][k] ], linewidth=1, color=(0.5, 0.5, 0.5)) #=============================================================== ## plot Poles and Zeros #=============================================================== if self.chkPZ.isChecked(): PN_SIZE = 8 # size of P/N symbols # Plot zero markers at |H(z_i)| = zlevel with "stems": self.ax3d.plot(zz.real, zz.imag, ones(len(zz)) * zlevel, 'o', markersize=PN_SIZE, markeredgecolor='blue', markeredgewidth=2.0, markerfacecolor='none') for k in range(len(zz)): # plot zero "stems" self.ax3d.plot([zz[k].real, zz[k].real], [zz[k].imag, zz[k].imag], [bottom, zlevel], linewidth=1, color='b') # Plot the poles at |H(z_p)| = plevel with "stems": self.ax3d.plot(np.real(pp), np.imag(pp), plevel_top, 'x', markersize=PN_SIZE, markeredgewidth=2.0, markeredgecolor='red') for k in range(len(pp)): # plot pole "stems" self.ax3d.plot([pp[k].real, pp[k].real], [pp[k].imag, pp[k].imag], [plevel_btm, plevel_top], linewidth=1, color='r') #=============================================================== ## 3D-Plots of |H(z)| clipped between |H(z)| = top #=============================================================== m_cb = cm.ScalarMappable( cmap=cmap) # normalized proxy object that is mappable m_cb.set_array(Hmag) # for colorbar #--------------------------------------------------------------- ## 3D-mesh plot #--------------------------------------------------------------- if self.cmbMode3D.currentText() == 'Mesh': # fig_mlab = mlab.figure(fgcolor=(0., 0., 0.), bgcolor=(1, 1, 1)) # self.ax3d.set_zlim(0,2) self.ax3d.plot_wireframe(self.x, self.y, Hmag, rstride=5, cstride=stride, linewidth=1, color='gray') #--------------------------------------------------------------- ## 3D-surface plot #--------------------------------------------------------------- # http://stackoverflow.com/questions/28232879/phong-shading-for-shiny-python-3d-surface-plots elif self.cmbMode3D.currentText() == 'Surf': if MLAB: ## Mayavi surf = mlab.surf(self.x, self.y, H_mag, colormap='RdYlBu', warp_scale='auto') # Change the visualization parameters. surf.actor.property.interpolation = 'phong' surf.actor.property.specular = 0.1 surf.actor.property.specular_power = 5 # s = mlab.contour_surf(self.x, self.y, Hmag, contour_z=0) mlab.show() else: if self.chkLighting.isChecked(): ls = LightSource(azdeg=0, altdeg=65) # Create light source object rgb = ls.shade( Hmag, cmap=cmap) # Shade data, creating an rgb array cmap_surf = None else: rgb = None cmap_surf = cmap # s = self.ax3d.plot_surface(self.x, self.y, Hmag, # alpha=OPT_3D_ALPHA, rstride=1, cstride=1, cmap=cmap, # linewidth=0, antialiased=False, shade=True, facecolors = rgb) # s.set_edgecolor('gray') s = self.ax3d.plot_surface(self.x, self.y, Hmag, alpha=alpha, rstride=1, cstride=1, linewidth=0, antialiased=False, facecolors=rgb, cmap=cmap_surf, shade=True) s.set_edgecolor(None) #--------------------------------------------------------------- ## 3D-Contour plot #--------------------------------------------------------------- elif self.cmbMode3D.currentText() == 'Contour': s = self.ax3d.contourf3D(self.x, self.y, Hmag, NL, alpha=alpha, cmap=cmap) #--------------------------------------------------------------- ## 2D-Contour plot # TODO: 2D contour plots do not plot correctly together with 3D plots in # current matplotlib 1.4.3 -> disable them for now # TODO: zdir = x / y delivers unexpected results -> rather plot max(H) # along the other axis? # TODO: colormap is created depending on the zdir = 'z' contour plot # -> set limits of (all) other plots manually? if self.chkContour2D.isChecked(): # self.ax3d.contourf(x, y, Hmag, 20, zdir='x', offset=xmin, # cmap=cmap, alpha = alpha)#, vmin = bottom)#, vmax = top, vmin = bottom) # self.ax3d.contourf(x, y, Hmag, 20, zdir='y', offset=ymax, # cmap=cmap, alpha = alpha)#, vmin = bottom)#, vmax = top, vmin = bottom) s = self.ax3d.contourf(self.x, self.y, Hmag, NL, zdir='z', offset=bottom - (top - bottom) * 0.05, cmap=cmap, alpha=alpha) # plot colorbar for suitable plot modes if self.chkColBar.isChecked() and (self.chkContour2D.isChecked() or str(self.cmbMode3D.currentText()) in {'Contour', 'Surf'}): self.colb = self.mplwidget.fig.colorbar(m_cb, ax=self.ax3d, shrink=0.8, aspect=20, pad=0.02, fraction=0.08) #---------------------------------------------------------------------- ## Set view limits and labels #---------------------------------------------------------------------- if not self.mplwidget.mplToolbar.a_lk.isChecked(): self.ax3d.set_xlim3d(self.xmin, self.xmax) self.ax3d.set_ylim3d(self.ymin, self.ymax) self.ax3d.set_zlim3d(bottom, top) else: self._restore_axes() self.ax3d.set_xlabel('Re') #(fb.fil[0]['plt_fLabel']) self.ax3d.set_ylabel( 'Im' ) #(r'$ \tau_g(\mathrm{e}^{\mathrm{j} \Omega}) / T_S \; \rightarrow $') # self.ax3d.set_zlabel(r'$|H(z)|\; \rightarrow $') self.ax3d.set_title( r'3D-Plot of $|H(\mathrm{e}^{\mathrm{j} \Omega})|$ and $|H(z)|$') self.redraw()
H = nx.cycle_graph(20) g = nx.read_gpickle('../data/output_graph/protein_babies_whole/12as_AMP_0.p') # reorder nodes from 0,len(G)-1 G = nx.convert_node_labels_to_integers(g) # 3d spring layout pos = nx.spring_layout(G, dim=3) # numpy array of x,y,z positions in sorted node order xyz = np.array([pos[v] for v in sorted(G)]) # scalar colors scalars = np.array(list(G.nodes())) + 5 mlab.figure(1, bgcolor=(0, 0, 0)) mlab.clf() pts = mlab.points3d(xyz[:, 0], xyz[:, 1], xyz[:, 2], scalars, scale_factor=0.1, scale_mode='none', colormap='Blues', resolution=20) pts.mlab_source.dataset.lines = np.array(list(G.edges())) tube = mlab.pipeline.tube(pts, tube_radius=0.01) mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8)) mlab.savefig('mayavi2_spring.png') mlab.show() # interactive window # plt.show()
def collect_pc(self, grasp, pc, label, vis=False): """ 获取手抓闭合区域中的点云 :param grasp: 扫描仪获取的mesh坐标系下抓取姿态 (grasp_center, grasp_axis, grasp_angle, grasp_width, jaw_width) :param pc: 点云 :param label: 标签 :param vis: 可视化开关 :return: 手抓闭合区域中的点云 """ center, normal, major_pc, minor_pc = grasp.center, grasp.normal, grasp.major_pc, grasp.minor_pc bottom_center = -ags.gripper.hand_depth * normal + center # NOTE: c:center bc:bottom center p:point cloud matrix_p2bc = np.array([normal, major_pc, minor_pc]) # 旋转矩阵: 点云坐标系->底部中心点坐标系 pc_p2bc = (np.dot(matrix_p2bc, (pc - bottom_center).T)).T # 原始坐标系下点云转换到中心点坐标系下 if False: mlab.figure(bgcolor=(1, 1, 1), size=(1000, 800)) mlab.pipeline.surface( mlab.pipeline.open(obj_path + "/processed/mesh.ply")) ags.show_origin() ags.show_points(pc, color='lb') ags.show_grasp_norm_oneside(bottom_center, normal, major_pc, minor_pc, scale_factor=0.001) hand_points = ags.get_hand_points(bottom_center, normal, major_pc) ags.show_grasp_3d(hand_points, color='g') ags.show_points(pc_p2bc, color='b') hand_points = (np.dot(matrix_p2bc, (hand_points - bottom_center).T)).T # 手抓关键点转换到中心点坐标系 ags.show_grasp_3d(hand_points, color='y') mlab.title(str(label), size=0.3, color=(0, 0, 0)) mlab.show() # 获取手抓闭合区域中的点 x_limit = ags.gripper.hand_depth z_limit = ags.gripper.hand_height y_limit = ags.gripper.max_width x1 = pc_p2bc[:, 0] > 0 x2 = pc_p2bc[:, 0] < x_limit y1 = pc_p2bc[:, 1] > -y_limit / 2 y2 = pc_p2bc[:, 1] < y_limit / 2 z1 = pc_p2bc[:, 2] > -z_limit / 2 z2 = pc_p2bc[:, 2] < z_limit / 2 a = np.vstack([x1, x2, y1, y2, z1, z2]) self.in_ind = np.where(np.sum(a, axis=0) == len(a))[0] # 手抓闭合区域中点的索引 if len(self.in_ind) < self.min_point_limit: # 手抓闭合区域内点数太少 if False: # 显示闭合区域点数太少的抓取姿态 print("[INFO] points num", len(self.in_ind)) mlab.figure(bgcolor=(1, 1, 1), size=(1000, 800)) mlab.pipeline.surface( mlab.pipeline.open(obj_path + "/processed/mesh.ply")) ags.show_origin(0.03) # 显示原始坐标系下点云及手抓 ags.show_points(pc, color='lb') ags.show_grasp_norm_oneside(bottom_center, normal, major_pc, minor_pc, scale_factor=0.001) hand_points = ags.get_hand_points(bottom_center, normal, major_pc) ags.show_grasp_3d(hand_points, color='g') pc_c2m_region = (np.dot(matrix_p2bc.T, pc_p2bc[self.in_ind].T) ).T + bottom_center # 扫描仪坐标系下手抓闭合区域中的点云 ags.show_points(pc_c2m_region, color='r', scale_factor=.002) # 显示底部中心点坐标系下点云及手抓(应在世界坐标系原点) ags.show_points(pc_p2bc, color='b') ags.show_points(pc_p2bc[self.in_ind], color='r', scale_factor=.002) # 中心点坐标系下手抓闭合区域中的点云 hand_points = (np.dot(matrix_p2bc, (hand_points - bottom_center).T)).T # 手抓关键点转换到中心点坐标系 ags.show_grasp_3d(hand_points, color='y') mlab.title(str(label), size=0.3, color=(0, 0, 0)) mlab.show() return None if False: # 显示手抓闭合区域内点云 mlab.figure(bgcolor=(1, 1, 1), size=(1000, 800)) mlab.pipeline.surface( mlab.pipeline.open(obj_path + "/processed/mesh.ply")) ags.show_origin(0.03) # 显示原始坐标系下点云及手抓 ags.show_points(pc, color='lb') ags.show_grasp_norm_oneside(bottom_center, normal, major_pc, minor_pc, scale_factor=0.001) hand_points = ags.get_hand_points(bottom_center, normal, major_pc) ags.show_grasp_3d(hand_points, color='g') pc_c2m_region = (np.dot( matrix_p2bc.T, pc_p2bc[self.in_ind].T)).T + bottom_center # 扫描仪坐标系下手抓闭合区域中的点云 ags.show_points(pc_c2m_region, color='r', scale_factor=.002) # 显示底部中心点坐标系下点云及手抓(应在世界坐标系原点) ags.show_points(pc_p2bc, color='b') ags.show_points(pc_p2bc[self.in_ind], color='r', scale_factor=.002) # 中心点坐标系下手抓闭合区域中的点云 hand_points = (np.dot(matrix_p2bc, (hand_points - bottom_center).T)).T # 手抓关键点转换到中心点坐标系 ags.show_grasp_3d(hand_points, color='y') # 显示手抓闭合区域 # x_arr = np.array([-1, 1, 1, -1, -1, 1, 1, -1])/2 # y_arr = np.array([-1, -1, 1, 1, -1, -1, 1, 1])/2 # z_arr = np.array([-1, -1, -1, -1, 1, 1, 1, 1])/2 # x = (x_arr + 0.5) * ags.gripper.hand_depth # 平移半个单位 # y = y_arr * (ags.gripper.hand_outer_diameter-2*ags.gripper.finger_width) # z = z_arr * ags.gripper.hand_height # triangles = [(0, 1, 2), (0, 2, 3), (4, 5, 6), (4, 6, 7), (1, 5, 6), (1, 2, 6), # (0, 4, 7), (0, 3, 7), (2, 3, 6), (3, 6, 7), (0, 1, 5), (0, 4, 5)] # mlab.triangular_mesh(x, y, z, triangles, color=(1, 0, 1), opacity=0.2) mlab.title("label:{} point num:{}".format(label, len(self.in_ind)), size=0.25, color=(0, 0, 0)) mlab.show() return pc_p2bc[self.in_ind] # 返回手抓闭合区域中的点云(手抓底部坐标系下)
def display_frames(): for i in range(11): frame = np.load("./frames/" + str(i) + ".npy") print(frame) mlab.surf(frame) mlab.show()
r''' Construct a general crease pattern configuration, used in the examples below demonstrating the evaluation of goal functions and constraints. ''' from .sim03_map_pattern_to_target_face import create_sim_step if __name__ == '__main__': import mayavi.mlab as m sim_step = create_sim_step() cp = sim_step.cp_state m.figure(bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.6, 0.6, 0.6)) cp.plot_mlab(m, lines=True) m.axes(extent=[0, 1, 0, 1, 0, .5]) m.show() arr = m.screenshot() import pylab as p p.imshow(arr) p.axis('off') p.show()
def omf_plot(x,y,z,mx,my,mz,img_bgcolor=(1,1,1),img_figsize=(1080,720),img_format='png',img_display='cone',img_view=np.array([0,90])\ ,img_line_scale=0.9,img_axis=False,fname=None,fdir=None): #create color map data = color1d(x, y, z, mx, my, mz, img_color, img_color_reverse) #计算箭头的长度 cal_step = lambda i: np.diff(np.sort(list(set(i)))).min() scale_factor = np.sqrt(cal_step(x)**2 + cal_step(y)**2 + cal_step(z)**2) * img_line_scale #开始画图 f = mlab.figure(bgcolor=img_bgcolor, size=img_figsize) #图片的 for i in range(len(data)): #循环画图class_color**3次 color, pf = data[i][0], data[i][ 1] #DataFrame,[x,y,z,mx,my,mz,lx,ly,lz] mlab.quiver3d(pf[0], pf[1], pf[2], pf[3], pf[4], pf[5], color=color, scale_factor=scale_factor, mode=img_display) #cone if img_axis: #创建三个坐标轴方向 maxx, maxy, maxz = np.max(x), np.max(y), np.max(z) #z mlab.quiver3d( 0, 1.0 * maxy, 1.3 * maxz, 0, 0, 1, color=(0, 0, 1), mode='arrow', scale_factor=scale_factor * 2, ) mlab.text3d(0, 1.0 * maxy, 1.3 * maxz + scale_factor * 2, 'z', color=(0, 0, 0), scale=scale_factor * 0.8) #y mlab.quiver3d(0, 1.0 * maxy, 1.3 * maxz, 0, 1, 0, color=(0, 1, 0), mode='arrow', scale_factor=scale_factor * 2) mlab.text3d(0, 1.0 * maxy + scale_factor * 2, 1.3 * maxz, 'y', color=(0, 0, 0), scale=scale_factor * 0.8) #x mlab.quiver3d( 0, 1.0 * maxy, 1.3 * maxz, 1, 0, 0, color=(1, 0, 0), mode='arrow', scale_factor=scale_factor * 2, ) mlab.text3d(scale_factor * 2, 1.0 * maxy, 1.3 * maxz, 'x', color=(0, 0, 0), scale=scale_factor * 0.8) ######################################### for view in img_view: mlab.view(view[0], view[1]) #观察角度 if isinstance(fname, str) and isinstance(fdir, str) and img_save: if GOODGPU: mlab.savefig(os.path.join( fdir, '%s-z%d-x%d.%s' % (fname, view[0], view[1], img_format)), magnification=5) else: mlab.savefig( os.path.join( fdir, '%s-z%d-x%d.%s' % (fname, view[0], view[1], img_format))) if img_show == True: #print u"需手动关掉图片,才会继续画图!!" print("Need to manually turn off the picture, will continue drawing!") mlab.show() #显示图片 if not img_show: mlab.close() #关闭画布
def plot_imag_mayavi(f, xbounds=(-1, 1), ybounds=(-1, 1), res=401): """ Plot the imaginary part of the function 'f' given the bounds and resolution. """ X, Y, vals = get_vals(f, xbounds, ybounds, res) ml.mesh(X, Y, vals.imag) ml.show()
def munster(listofcolors,illuminant,rgbprimary_name,centraltendencymeasure, flag=False,labeling=False,concat=False,lab=True,Screentype='LCD',jmunchips=False,meancoerce=False,adaptype='brad'): if jmunchips==False and concat==False: mflag = False else: mflag = True #if more than one color is entered, with the '3d' option, #mayavi will just graph the munsell chips, unless you want to see all of the points concatenated together ls = [] illum = illuminantlookup(illuminant) # returns a pair- the lab illuminant is [0], the xyz coordinates are [1] #the following returns the rgb primaries: rgbprimaries=rgbprimarylookup(rgbprimary_name) coefficentmatrix = getrgbxyz_coefficents(illum[1],rgbprimaries) #sets up the RGB to XYZ matrix at the begining, so it isn't calculated for every conversion. mchips = [[[],[],[],[],[],[]] for x in xrange(320) ] #converting the munsell chips to lab space with chromatic adaptation so that they can be compared to the xkcd colors' #(for munsell chips only, the conversion goes: Lab->xyz, xyz->chromaticadapt->xyz, xyz->Lab) for i in range(len(mmchips)): # print chip a = altLabXyzConvert(illum[1],float(mmchips[i][3]),float(mmchips[i][4]),float(mmchips[i][5])) b = chromaticadapt(a,illuminantlookup('C')[0],illuminantlookup(illuminant)[0],adaptype) q1 = (b[0]-a[0]) q2 = (b[1]-a[1]) q3 = (b[2]-a[2]) if abs(q1)>.5: print q1 elif abs(q2)>.5: print q2 elif abs(q3)>.5: print q3 dd = munlabconvert(illum[0],([b[0]],[b[1]],[b[2]])) mchips[i][0]=mmchips[i][0] mchips[i][1]=mmchips[i][1] mchips[i][2]=mmchips[i][2] mchips[i][3]=round(dd[0],5) mchips[i][4]=round(dd[1],5) mchips[i][5]=round(dd[2],5) # # # # #Now starts the bulk of the program. # # # # # print listofcolors if centraltendencymeasure == 'mean': #this will 'average' as many colors as you want flag = True a = Mean_calc(illum[0],listofcolors,ls,coefficentmatrix,concat,lab, Screentype,meancoerce) #converts to LAB, runs calculations # print a # print 'ak!' if meancoerce == True: print a[7] print quick_mode_mun_search((a[7],a[8],a[9]),mchips,flag) elif centraltendencymeasure == 'mode': for color in listofcolors: Modal_mun_search(color,illum[0],coefficentmatrix,mchips,flag,Screentype) #the conversions and things are done here #that was most of it, the rest is an in-routine 3d graphing bit elif centraltendencymeasure == '3d': a = len(listofcolors) #formulate munsell chips to be used in 3d. #need all of the L* data from the munsell chips to be in i. i=[] j=[] k=[] ii=[] jj=[] kk=[] #keeping the color like the 'c' illuminant print 'setting up the munsell chips...' for chip in mchips: i.append(float(chip[3])) j.append(float(chip[4])) k.append(float(chip[5])) print 'coloring them' #convert mchips to rgb mchipscolor =[] Imatrix = coefficentmatrix.I #(inverted) for chip in mmchips: ii.append(float(chip[3])) jj.append(float(chip[4])) kk.append(float(chip[5])) print ii[0:5] for p in range(320): #Purely for coloring the chips! tt = (altLabXyzConvert(illum[1],ii[p],jj[p],kk[p])) uu = xyzrgbconvert(tt,Imatrix) r = uu[0] g = uu[1] b = uu[2] if r>1: #takes care of impossible colors outside of the rgb gamut R = 1 print 'rounded' elif r<0: R = 0 print 'rounded' else: R = r if g>1: G = 1 print 'rounded' elif g<0: G = 0 print 'rounded' else: G = g if b>1: B = 1 print 'rounded' elif b<0: B = 0 print 'rounded' else: B = b w = (R,G,B) mchipscolor.append(w) #mchipscolor is now the list of rgb triplets associated with each point d=[] for u in range(a): q=[] qq=[] x=[]#for 3d plotting y=[] z=[] #some null lists. (I should find a cleaner way to do this) print 'fetching from database' print listofcolors[u] #print Screentype c.execute("Select answers.r, answers.g, answers.b from answers inner join users on answers.user_id = users.id where colorname=? and monitor =?", (listofcolors[u][0],Screentype,)) d.extend(c.fetchall()) ixyzconvert(d,q,coefficentmatrix) imun_convert(q,qq,illum[0]) #converts to LAB for a specific illuminant e = len(qq) for u in xrange (e): x.append(qq[u][0]) y.append(qq[u][1]) z.append(qq[u][2]) X=np.array(x) Y=np.array(y) Z=np.array(z) I=np.array(i) J=np.array(j) K=np.array(k) print "about to plot..." if jmunchips : if labeling == True: for i in range(len(mchipscolor)): if i == 48: #labels the focal chips- from WCS (Yellow) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'C9') elif i == 176:#WCS,XKCD (green) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'F17',color=(1,0,1)) elif i == 188:#WCS (blue) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'F29') elif i == 200:#WCS (red) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'G1') else: a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') elif labeling == False: for i in range(len(mchipscolor)): a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') mlab.draw() mlab.show() elif jmunchips == False: if labeling == True: #this is a basic filter for taking a representitive (?) sample of the xkcd colors if e < 2000: s = mlab.points3d(X, Y, Z, colormap="hsv",scale_factor=2) #plots normally elif 1999 < e < 10001: s = mlab.points3d(X, Y, Z, colormap="hsv", mask_points=5, scale_factor=2) #plots 1 out of every 5 points elif e > 10000: s = mlab.points3d(X, Y, Z, colormap="hsv", mask_points=50, scale_factor=2) #plots 1 out of every 50 points elif e> 200000: s = mlab.points3d(X, Y, Z, colormap="hsv", mask_points=65, scale_factor=2) # 1/65. mlab.draw() print 'points plotted, next are the munsell chips' for i in range(len(mchipscolor)): if i == 48: #labels the focal chips- from WCS (Yellow) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'C9') elif i == 176:#WCS,XKCD (green) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'F17',color=(1,0,1)) elif i == 188:#WCS (blue) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'F29') elif i == 200:#WCS (red) a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') b = mlab.text3d(I[i],J[i],K[i],'G1') else: a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') mlab.show() elif labeling == False: if e < 2000: s = mlab.points3d(X, Y, Z, colormap="hsv",scale_factor=1) #plots normally elif 1999 < e < 10001 : s = mlab.points3d(X, Y, Z, colormap="hsv", mask_points=5, scale_factor=1) #plots 1 out of every 5 points elif e > 10000: s = mlab.points3d(X, Y, Z, colormap="hsv", mask_points=50, scale_factor=1) #plots 1 out of every 50 points elif e> 200000: s = mlab.points3d(X, Y, Z, colormap="hsv", mask_points=65, scale_factor=1) # 1/65. print 'points plotted, next are the munsell chips' for i in range(len(mchipscolor)): a = mlab.points3d(I[i],J[i],K[i], color =(mchipscolor[i]),mode='cube',scale_factor=2,scale_mode='none') mlab.draw() mlab.show() else: print "I haven't written that measure of central tendancy yet"
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)]
# for ids in itertools.combinations(np.arange(6),3): # Rc = np.zeros((3,3)) # for l in range(3): # Rc[:,l] = M[:,ids[l]] # if det(Rc) > 0: # Rn = Rc.T.dot(nMean) # anglesToY.append(np.arccos(np.abs(Rn[1]))*180./np.pi) ## print anglesToY[-1], Rn # error[lId,i] = min(anglesToY) error[lId, i] = np.mean( np.arccos(np.max(np.abs(M.T.dot(ns)), axis=0)) * 180. / np.pi) if not np.isnan(error[lId, i]): print "direction of {} surface normals:".format( labels[lId]), " error ", error[lId, i] if False: n = rgbd.getNormals()[rgbd.mask, :] figm = mlab.figure(bgcolor=(1, 1, 1)) mlab.points3d(n[:, 0], n[:, 1], n[:, 2], color=(0.5, 0.5, 0.5), mode="point") plotMF(figm, R) mlab.show(stop=True) # except: # print "Unexpected error:", sys.exc_info()[0] # error[i] = np.nan np.savetxt("./angularObjectDeviations_rtmf_" + mode + ".csv", error)
def showGrayImage(self, img=[]): mlab.imshow(img, colormap='gist_earth') mlab.show()
def plot_real_mayavi(f, xbounds=(-1, 1), ybounds=(-1, 1), res=401): """ Make a surface plot of the real part of the function 'f' given the bounds and resolution. """ X, Y, vals = get_vals(f, xbounds, ybounds, res) ml.mesh(X, Y, vals.real) ml.show()
def _plot_point_cloud(self, pcl: np.ndarray, pcl_r: np.ndarray, labels) -> None: radius = 0.05 color = (1, 0.83, 0) mlab.points3d( pcl[:, 0], pcl[:, 1], pcl[:, 2], # (pcl_r[:, 0] % 85.0) / 85.0, pcl[:, 2], mode="point", colormap="jet", scale_factor=100, line_width=10, figure=mlab.figure(bgcolor=(0, 0, 0), size=(1920, 1080)), ) for label in labels: box = label.box cx = box.center_x cy = box.center_y cz = box.center_z l = box.length # noqa E741 w = box.width h = box.height ry = box.heading x_corners = [l, l, -l, -l, l, l, -l, -l] y_corners = [w, -w, -w, w, w, -w, -w, w] z_corners = [h, h, h, h, -h, -h, -h, -h] R = np.array([[np.cos(ry), -np.sin(ry), 0], [np.sin(ry), np.cos(ry), 0], [0, 0, 1]]) corners3d = np.vstack([x_corners, y_corners, z_corners]) / 2.0 corners3d = (R @ corners3d).T + np.array([cx, cy, cz]) x_corners, y_corners, z_corners = corners3d[:, 0], corners3d[:, 1], corners3d[:, 2] mlab.plot3d( [x_corners[0], x_corners[1]], [y_corners[0], y_corners[1]], [z_corners[0], z_corners[1]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[1], x_corners[2]], [y_corners[1], y_corners[2]], [z_corners[1], z_corners[2]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[2], x_corners[3]], [y_corners[2], y_corners[3]], [z_corners[2], z_corners[3]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[0], x_corners[3]], [y_corners[0], y_corners[3]], [z_corners[0], z_corners[3]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[4], x_corners[5]], [y_corners[4], y_corners[5]], [z_corners[4], z_corners[5]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[5], x_corners[6]], [y_corners[5], y_corners[6]], [z_corners[5], z_corners[6]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[6], x_corners[7]], [y_corners[6], y_corners[7]], [z_corners[6], z_corners[7]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[4], x_corners[7]], [y_corners[4], y_corners[7]], [z_corners[4], z_corners[7]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[0], x_corners[4]], [y_corners[0], y_corners[4]], [z_corners[0], z_corners[4]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[1], x_corners[5]], [y_corners[1], y_corners[5]], [z_corners[1], z_corners[5]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[2], x_corners[6]], [y_corners[2], y_corners[6]], [z_corners[2], z_corners[6]], color=color, tube_radius=radius, ) mlab.plot3d( [x_corners[3], x_corners[7]], [y_corners[3], y_corners[7]], [z_corners[3], z_corners[7]], color=color, tube_radius=radius, ) mlab.show()
def train_one_epoch(sess, ops, train_writer, batch): total_seen = 0 loss_sum = 0 shape_list = sp.get_file_list(DATA_DIR, '.h5') # Shuffle train files train_file_ids = np.arange(0, len(shape_list)) np.random.shuffle(train_file_ids) total_batch = len(shape_list) // BATCH_SIZE for fn in range(0, total_batch): start_id = fn * BATCH_SIZE Data = [] Seg_Label = [] Categroy_Label = [] Temp = [] for sn in range(BATCH_SIZE): shape_temp = os.path.join( DATA_DIR, shape_list[train_file_ids[start_id + sn]]) f = h5py.File(shape_temp) points = f['points'][:] seg_labels = f['seg_labels'][:] category_labels = f['shape_labels'].value - 1 templates = f['shape_temp'][:] f.close() points, seg_labels, _ = pf.shuffle_data(points, seg_labels) Data.append(points) Seg_Label.append(seg_labels) Categroy_Label.append(category_labels) Temp.append(templates) Data = np.array(Data) Seg_Label = np.array(Seg_Label) Categroy_Label = np.array(Categroy_Label) Temp = np.array(Temp) #rotated_data = pf.rotate_point_cloud(Data) #jittered_data = pf.jitter_point_cloud(rotated_data) jittered_data = pf.jitter_point_cloud(Data) batch_val = sess.run(batch) if (IS_SHOW == 'True') & ((batch_val + 1) % 3000 == 1): mlab.figure('points', fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.points3d(10 * Data[0, :, 0], 10 * Data[0, :, 1], 10 * Data[0, :, 2], Seg_Label[0, :], scale_factor=0.2, scale_mode='vector') mlab.show() mlab.figure('temp', fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.points3d(10 * Temp[0, :, 0], 10 * Temp[0, :, 1], 10 * Temp[0, :, 2], color=(0.7, 0.7, 0.7), scale_factor=0.2, scale_mode='vector') mlab.show() feed_dict = { ops['input_shapes']: jittered_data, ops['category_labels']: Categroy_Label, ops['input_shape_labels']: Seg_Label, ops['template_shapes']: Temp, ops['is_training_pl']: 'True' } summary, step, _, loss_val, morhp_shapes, real_seg, fake_seg = sess.run( [ ops['merged'], ops['step'], ops['train_op'], ops['total_loss'], ops['morph_shapes'], ops['real_seg_preds'], ops['fake_seg_preds'] ], feed_dict=feed_dict) real_seg_labels = np.argmax(real_seg, axis=-1) fake_seg_labels = np.argmax(fake_seg, axis=-1) if (IS_SHOW == 'True') & ((batch_val + 1) % 3000 == 1): mlab.figure('real_seg', fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.points3d(10 * Data[0, :, 0], 10 * Data[0, :, 1], 10 * Data[0, :, 2], real_seg_labels[0, :], scale_factor=0.2, scale_mode='vector') mlab.figure('fake_seg', fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.points3d(10 * morhp_shapes[0, :, 0], 10 * morhp_shapes[0, :, 1], 10 * morhp_shapes[0, :, 2], fake_seg_labels[0, :], scale_factor=0.2, scale_mode='vector') mlab.show() mlab.figure('morph_shape', fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.points3d(10 * morhp_shapes[0, :, 0], 10 * morhp_shapes[0, :, 1], 10 * morhp_shapes[0, :, 2], color=(0.7, 0.7, 0.7), scale_factor=0.2, scale_mode='vector') mlab.show() # show the correspondence between the temptation and the morphing shape c = Temp[0, 0, :] sp.vis_correspondance(Temp[0, ...], morhp_shapes[0, ...], Temp[0, ...], morhp_shapes[0, ...], c, if_gt=False, if_save=False, scale_factor=0.03) direct = morhp_shapes[0, ...] - Temp[0, ...] mlab.figure('move', fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.quiver3d(Temp[0, ::20, 0], Temp[0, ::20, 1], Temp[0, ::20, 2], direct[::20, 0], direct[::20, 1], direct[::20, 2], scale_factor=1) mlab.points3d(morhp_shapes[0, :, 0], morhp_shapes[0, :, 1], morhp_shapes[0, :, 2], color=(0.7, 0.7, 0.7), scale_factor=0.02, scale_mode='vector') mlab.show() train_writer.add_summary(summary, step) total_seen += BATCH_SIZE loss_sum += loss_val log_string('batch loss: %f' % (loss_val)) log_string('mean loss: %f' % (loss_sum * BATCH_SIZE / float(total_seen)))
def showClouds(self, orgPC=[], fovPC=[], roadPC=[], vehPC=[], pedPC=[], cycPC=[], make_sparse=True): mlab.figure(bgcolor=self.bcgColor) # make the original point cloud sparse by removing every second point if make_sparse: if len(orgPC): orgPC = np.delete(orgPC, list(range(0, orgPC.shape[0], 2)), axis=0) if len(orgPC): orgPC = np.delete(orgPC, list(range(0, orgPC.shape[0], 2)), axis=0) if len(orgPC): orgPC = np.delete(orgPC, list(range(0, orgPC.shape[0], 2)), axis=0) # colorize point clouds if len(orgPC): mlab.points3d(orgPC[:, 0], orgPC[:, 1], orgPC[:, 2], np.ones(len(orgPC)), color=tuple(self.colorOrgPC), colormap="spectral", scale_factor=self.pointSize) if len(fovPC): mlab.points3d(fovPC[:, 0], fovPC[:, 1], fovPC[:, 2], np.ones(len(fovPC)), color=tuple(self.colorFovPC), colormap="spectral", scale_factor=self.pointSize) if len(roadPC): mlab.points3d(roadPC[:, 0], roadPC[:, 1], roadPC[:, 2], np.ones(len(roadPC)), color=tuple(self.colorRoadPC), colormap="spectral", scale_factor=self.pointSize) if len(vehPC): mlab.points3d(vehPC[:, 0], vehPC[:, 1], vehPC[:, 2], np.ones(len(vehPC)), color=tuple(self.colorVehPC), colormap="spectral", scale_factor=self.pointSize) if len(pedPC): mlab.points3d(pedPC[:, 0], pedPC[:, 1], pedPC[:, 2], np.ones(len(pedPC)), color=tuple(self.colorPedPC), colormap="spectral", scale_factor=self.pointSize) if len(cycPC): mlab.points3d(cycPC[:, 0], cycPC[:, 1], cycPC[:, 2], np.ones(len(cycPC)), color=tuple(self.colorCycPC), colormap="spectral", scale_factor=self.pointSize) mlab.show()
def vis(voxels): from mayavi import mlab from util3d.mayavi_vis import vis_voxels vis_voxels(voxels) mlab.show()