def show_contrasts(subject, contrasts, side, threshold):

    x, y, z, triangles = get_geometry(subject, side, "inflated")   ## inflated or white
    curv = get_curvature_sign(subject, side)

    f = mlab.figure()
    mlab.clf()

    # anatomical mesh
    mlab.triangular_mesh(x, y, z, triangles, transparent=False,
                         opacity=1., name=subject,
        scalars=curv, colormap="bone", vmin=-1, vmax=2)

    mlab.title(subject)

    cmaps = [colormaps[c.split("-")[0]]['colormap'] for c in contrasts]

    for contrast, colormap in zip(contrasts, cmaps):
        # functional mesh
        data = get_contrast(subject, contrast, side)
        func_mesh = mlab.pipeline.triangular_mesh_source(x, y, z, triangles,
                                                     scalars=data)
            # threshold
        thresh = mlab.pipeline.threshold(func_mesh, low=threshold)

        surf = mlab.pipeline.surface(thresh, colormap='hot', transparent=True,
                          opacity=.8) # diminuer pour avoir plus de transparence
        lut = (np.array([colormap(v) for v in np.linspace(.25, 1., 256)]) * 255
                       ).astype(int)

        surf.module_manager.scalar_lut_manager.lut.table = lut

    mlab.draw()

    return f
示例#2
0
def display(fun_dir, fs_dir, contrast):
    mlab.figure(bgcolor=(1, 1, 1))
    left_mesh = freesurfer.read_geometry(os.path.join(fs_dir, 'lh.inflated'))
    right_mesh = freesurfer.read_geometry(os.path.join(fs_dir, 'rh.inflated'))
    left_curv = os.path.join(fs_dir, 'lh.curv')
    right_curv = os.path.join(fs_dir, 'rh.curv')
    meshes = [left_mesh, right_mesh]
    curves = [left_curv, right_curv]
    for hemisphere, mesh_file, curv_file in zip(['lh', 'rh'], meshes, curves):
        fun_file = os.path.join(fun_dir, '%s_z_map_%s.gii' % (
                contrast, hemisphere))
        coords, triangles = mesh_file
        x, y, z = coords.T

        if hemisphere == 'lh':
            x -= 50
        else:
            x += 50

        curv = freesurfer.read_morph_data(curv_file).astype(np.float)
        tex = np.array([darrays.data for darrays in 
                        read(fun_file).darrays]).ravel()
        print fun_file, tex.min(), tex.max()
        name = ''
        cmin = -1
        cmax = 1
        mlab.triangular_mesh(x, y, z, triangles, transparent=True, opacity=1.,
                             name=name, scalars=curv, colormap="bone",
                             vmin=cmin, vmax=cmax)
        func_mesh = mlab.pipeline.triangular_mesh_source(
            x, y, z, triangles, scalars=tex)
        thresh = mlab.pipeline.threshold(func_mesh, low=THRESHOLD)
        mlab.pipeline.surface(thresh, colormap="hot", vmin=THRESHOLD, vmax=7)
def plot3dformesh(x,cv,f):
    return
    cv = band.toZeroStatic(cv)
    if MPI.COMM_WORLD.rank == 0:
        v2 = cv.getArray()
        pl.figure(bgcolor=(1,1,1),fgcolor=(0.5,0.5,0.5))
        pl.triangular_mesh(x[:,0],x[:,1],x[:,2],f,scalars=v2)
示例#4
0
def display_collada(dae_file):
    """
    Display the DAE mesh. Requires pycollada.
    """
    print("Displaying %s" % dae_file)

    from collada import Collada, DaeUnsupportedError, DaeBrokenRefError
    mesh = Collada(dae_file, ignore=[DaeUnsupportedError, DaeBrokenRefError])

    for geometry in mesh.scene.objects('geometry'):
        for prim in geometry.primitives():
            # use primitive-specific ways to get triangles
            prim_type = type(prim).__name__
            if prim_type == 'BoundTriangleSet':
                triangles = prim
            elif prim_type == 'BoundPolylist':
                triangles = prim.triangleset()
            else:
                # Unsupported mesh type
                triangles = None

            if triangles is not None:
                x = triangles.vertex[:,0]
                y = triangles.vertex[:,1]
                z = triangles.vertex[:,2]

                mlab.triangular_mesh(x, y, z, triangles.vertex_index,
                                     color=(0, 0, 1))
示例#5
0
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()
示例#6
0
文件: tools.py 项目: inducer/modepy
def plot_element_values(n, nodes, values, resample_n=None,
        node_tuples=None, show_nodes=False):
    dims = len(nodes)

    orig_nodes = nodes
    orig_values = values

    if resample_n is not None:
        import modepy as mp
        basis = mp.simplex_onb(dims, n)
        fine_nodes = mp.equidistant_nodes(dims, resample_n)

        values = np.dot(mp.resampling_matrix(basis, fine_nodes, nodes), values)
        nodes = fine_nodes
        n = resample_n

    from pytools import generate_nonnegative_integer_tuples_summing_to_at_most \
            as gnitstam

    if dims == 1:
        import matplotlib.pyplot as pt
        pt.plot(nodes[0], values)
        if show_nodes:
            pt.plot(orig_nodes[0], orig_values, "x")
        pt.show()
    elif dims == 2:
        import mayavi.mlab as mlab
        mlab.triangular_mesh(
                nodes[0], nodes[1], values, submesh(list(gnitstam(n, 2))))
        if show_nodes:
            mlab.points3d(orig_nodes[0], orig_nodes[1], orig_values,
                    scale_factor=0.05)
        mlab.show()
    else:
        raise RuntimeError("unsupported dimensionality %d" % dims)
示例#7
0
文件: plotter.py 项目: SpuqTeam/spuq
 def plotMesh(
     cls, coordinates, triangles=None, values=None, axes=True, displacement=False, newfigure=True, scale=1, **kwargs
 ):
     # http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#mayavi.mlab.triangular_mesh
     if newfigure:
         cls.figure()
     if isinstance(coordinates, Function) and triangles is None:
         coordinates, triangles, values = cls._function_data(coordinates)
     else:
         assert triangles is not None
     x = coordinates[:, 0]
     y = coordinates[:, 1]
     representation = "surface"
     scalars = None
     if displacement:
         representation = "wireframe"
         assert values.shape[1] == 2
         x = coordinates[:, 0] + scale * values[:, 0]
         y = coordinates[:, 1] + scale * values[:, 1]
         scalars = sqrt(sum(values * values, axis=1))
     else:
         assert values is None or len(values.shape) == 1
     if values is None or displacement:
         values = 0 * x
     mlab.triangular_mesh(x, y, values, triangles, representation=representation, scalars=scalars, **kwargs)
     if axes:
         cls.axes()
示例#8
0
def plot(ply):
    '''
    Plot vertices and triangles from a PlyData instance. Assumptions:
        `ply' has a 'vertex' element with 'x', 'y', and 'z'
            properties;

        `ply' has a 'face' element with an integral list property
            'vertex_indices', all of whose elements have length 3.

    '''
    vertex = ply['vertex']

    (x, y, z) = (vertex[t] for t in ('x', 'y', 'z'))

    mlab.points3d(x, y, z, color=(1, 1, 1), mode='point')

    if 'face' in ply:
        tri_idx = ply['face']['vertex_indices']
        idx_dtype = tri_idx[0].dtype

        triangles = numpy.fromiter(tri_idx, [('data', idx_dtype, (3,))],
                                   count=len(tri_idx))['data']

        mlab.triangular_mesh(x, y, z, triangles,
                             color=(1, 0, 0.4), opacity=0.5)
示例#9
0
文件: mesh.py 项目: kinnala/sp.fem
    def draw(self, test=None, u=None):
        """Draw all tetrahedra."""
        if test is not None:
            xs = 1./4.*(self.p[0, self.t[0, :]] +
                        self.p[0, self.t[1, :]] +
                        self.p[0, self.t[2, :]] +
                        self.p[0, self.t[3, :]])
            ys = 1./4.*(self.p[1, self.t[0, :]] +
                        self.p[1, self.t[1, :]] +
                        self.p[1, self.t[2, :]] +
                        self.p[1, self.t[3, :]])
            zs = 1./4.*(self.p[2, self.t[0, :]] +
                        self.p[2, self.t[1, :]] +
                        self.p[2, self.t[2, :]] +
                        self.p[2, self.t[3, :]])
            tset = np.nonzero(test(xs, ys, zs))[0]
        else:
            tset = range(self.t.shape[1])

        fset = np.unique(self.t2f[:, tset].flatten())

        if u is None:
            u = self.p[2, :]

        if OPT_MAYAVI:
            mlab.triangular_mesh(self.p[0, :], self.p[1, :], self.p[2, :],
                                 self.facets[:, fset].T, scalars=u)
            mlab.triangular_mesh(self.p[0, :], self.p[1, :], self.p[2, :],
                                 self.facets[:, fset].T,
                                 representation='wireframe', color=(0, 0, 0))
        else:
            raise ImportError("Mayavi not supported "
                              "by the host system!")
示例#10
0
def plot_inverse_operator(subject, fnout_img=None, verbose=None):
    """"Reads in and plots the inverse solution."""

    # get name of inverse solution-file
    subjects_dir = os.environ.get('SUBJECTS_DIR')
    fname_dir_inv = os.path.join(subjects_dir,
                                 subject)

    for files in os.listdir(fname_dir_inv):
        if files.endswith(",cleaned_epochs_avg-7-src-meg-inv.fif"):
            fname_inv = os.path.join(fname_dir_inv,
                                     files)
            break

    try:
        fname_inv
    except NameError:
        print "ERROR: No forward solution found!"
        sys.exit()


    # read inverse solution
    inv = min_norm.read_inverse_operator(fname_inv)

    # print some information if desired
    if verbose is not None:
        print "Method: %s" % inv['methods']
        print "fMRI prior: %s" % inv['fmri_prior']
        print "Number of sources: %s" % inv['nsource']
        print "Number of channels: %s" % inv['nchan']


    # show 3D source space
    lh_points = inv['src'][0]['rr']
    lh_faces = inv['src'][0]['tris']
    rh_points = inv['src'][1]['rr']
    rh_faces = inv['src'][1]['tris']

    # create figure and plot results
    fig_inverse = mlab.figure(size=(1200, 1200),
                              bgcolor=(0, 0, 0))

    mlab.triangular_mesh(lh_points[:, 0],
                         lh_points[:, 1],
                         lh_points[:, 2],
                         lh_faces)

    mlab.triangular_mesh(rh_points[:, 0],
                         rh_points[:, 1],
                         rh_points[:, 2],
                         rh_faces)

    # save result
    if fnout_img is not None:
        mlab.savefig(fnout_img,
                     figure=fig_inverse,
                     size=(1200, 1200))

    mlab.close(all=True)
def plot(ply):
    '''
    Plot vertices and triangles from a PlyData instance. Assumptions:
        `ply' has a 'vertex' element with 'x', 'y', and 'z'
            properties;

        `ply' has a 'face' element with an integral list property
            'vertex_indices', all of whose elements have length 3.

    '''
    vertex = ply['vertex']

    (x, y, z) = (vertex[t] for t in ('x', 'y', 'z'))

    # mlab.points3d(x, y, z, color=(1, 1, 1), mode='point')

    if 'face' in ply:
        tri_idx = ply['face']['vertex_indices']
        print type(tri_idx)
        idx_dtype = tri_idx[0].dtype
        print "idx_dtype" , idx_dtype
        triangles = numpy.fromiter(tri_idx, [('data', idx_dtype, (3,))],
                                   count=len(tri_idx))['data']
        k = triangles.byteswap()
        # p.from_array(numpy.array([[1,2,3],[3,4,5]], dtype=numpy.float32))
        p.from_array((triangles.byteswap().newbyteorder().astype('<f4')))
        # p1.add_points_from_input_cloud()
        p1.set_input_cloud(p)
        fil = p.make_moving_least_squares()

        # cloud_filtered = fil.filter()
        # fil = p1.make_statistical_outlier_filter()
        fil.set_mean_k(20)
        fil.set_std_dev_mul_thresh(0.1)
        # pointx = triangles[:,0]

        # k = pcl.PassThroughFilter(p)
        
        # print k.set_filter_field_name ("x");
        # print k.set_filter_limits(3.0,10.0)
        # print k.filter()

        pc_1 = pcl.PointCloud()
        pc_1 = p
        pc_2 = pcl.PointCloud()
        pc_2 = p
        kd = pcl.KdTreeFLANN(pc_1)
        print('pc_1:')
        print type(triangles)
        # file1 = open("values.txt",'w')
        # file1.write(str(triangles[:]))

        # mlab.mesh(x,y,z)
        print numpy.shape(p)
        print numpy.shape(z)
        print numpy.shape(y)
        print numpy.shape(x)
        # mlab.contour3d(x, y, z, p)
        mlab.triangular_mesh(x, y, z, fil,color=(1, 0.3, 0.9), opacity=0.5,colormap='cool')
示例#12
0
 def _render_mesh(self):
     import mayavi.mlab as mlab
     mlab.triangular_mesh(self.points[:, 0],
                          self.points[:, 1],
                          self.points[:, 2],
                          self.trilist,
                          color=(0.5, 0.5, 0.5),
                          figure=self.figure)
示例#13
0
 def draw_mesh(self, mesh, color=WHITE, opacity=0.7):
     x, y, z, triangles = self._get_triangular_mesh(mesh)
     mlab.triangular_mesh(x, y, z, triangles, color=color,
                          opacity=opacity, representation='surface')
     #mlab.triangular_mesh(x, y, z, triangles, colormap='bone',
     #                     opacity=0.8, representation='surface')
     mlab.triangular_mesh(x, y, z, triangles, color=(0, 0, 0),
                          line_width=1.0, representation='wireframe')
示例#14
0
文件: 4test.py 项目: epsilony/imptri
def plotc(cs,before=None,representation='wireframe',color=(0.5,1,1)):
    mlab.clf()
    if None is not before:
        before()
    mlab.triangular_mesh(*cs.get_triangles(),color=color,representation=representation)
    plot_ale(cs)
    if cs.ale:
        plot_edge(cs.ale[-1])
        plot_edge(cs.ale[-1].succ,color=(1,0,1))
def plot_big(MH, MHexam, points_proj, points_projal, skel_projal, ViewP, proj_type, plot_type="normal", fnum=1):
  
    # Plotting
    print "Plot figure z-axis reversed (because z=0 is top of scan)"
    mlab.figure(fnum, bgcolor=(1,1,1), size=(800,800))
    mlab.clf()
    #airway plot    
    mlab.triangular_mesh(MH.vertices[:,0], MH.vertices[:,1], MH.vertices[:,2]*(-1), 
                         MH.faces, colormap='Blues', representation='wireframe', 
                         line_width=0.5)
    try:
        mlab.triangular_mesh(MHexam.vertices[:,0], MHexam.vertices[:,1], 
                             MHexam.vertices[:,2]*(-1), MHexam.faces,
                             colormap='Greens', representation='surface',
                             opacity=0.2)
    except:
        print "Example mesh not plotted"
    #airway axes
    #mlab.axes('off') #extent=([-200, 200, -200,200, 200,-200])) 
    #points on the airway
    mlab.points3d(MH.silvert1[:,0], MH.silvert1[:,1], MH.silvert1[:,2]*(-1), 
                  scale_factor=1, color=(0,0,0))
#    #projected points
    mlab.points3d(points_proj[:,0], points_proj[:,1], points_proj[:,2]*(-1), 
                  scale_factor=1, color=(0,0,0))  
    
    if plot_type is "normal":        
#    #alignment points
        mlab.points3d(MH.points[:,0], MH.points[:,1], MH.points[:,2]*(-1), 
                      scale_factor=2, color=(0,1,0))
        
        #skeleton
        mlab.points3d(MH.skel[:,0], MH.skel[:,1], MH.skel[:,2]*(-1), 
                      scale_factor=0.5, color=(0.5,0.5,1))
    #    #alignment points
        mlab.points3d(points_projal[:,0], points_projal[:,1], points_projal[:,2]*(-1), 
                      scale_factor=2, color=(0,1,0))
        
    try:
        mlab.points3d(skel_projal[:,0], skel_projal[:,1], skel_projal[:,2]*(-1), 
                      scale_factor=0.5, color=(0.5,0.5,1))
    except:
        print "skeleton not plotted"
    #view direction
    #if proj_type=="Lodox":
    #    ViewL=np.array([ViewP, ViewP])
    #    ViewL[0,2]=30; ViewL[1,2]=-30        
    #    
    #    mlab.plot3d(ViewL[:,0]/10, ViewL[:,1], ViewL[:,2]*(-1), 
    #                color=(0,0,0), 
    #                tube_radius=1, opacity=1)
    
    #elif proj_type=="normal":
    #    mlab.points3d(ViewP[0]/10, ViewP[1], ViewP[2]*(-1), 
    #                  scale_factor=4, color=(1,0,0))
    
    mlab.view(elevation=80,azimuth=20)
示例#16
0
    def plot_mesh(self,):
        '''
        Plot the mesh that has been created

        SRH: 12 July2013
        '''
        from mayavi import mlab
        mlab.triangular_mesh(self.vertices[:,0], self.vertices[:,1], self.vertices[:,2],self.faces)
        mlab.triangular_mesh(self.vertices[:,0], self.vertices[:,1], self.vertices[:,2],self.faces,representation='wireframe',color=(0,0,0))
    def plot_beam(self,Z=1,xrot=None,yrot=None,zrot=None): #modified from
        n = BEAMN
        t = np.linspace(-np.pi, np.pi, n)
        z = np.exp(1j * t)
        x = z.real.copy()*BEAMR
        y = z.imag.copy()*BEAMR
        z = np.zeros_like(x)

        triangles = [(0, i, i + 1) for i in range(1, n)]
        x = np.r_[0, x]
        y = np.r_[0, y]
        z = np.r_[Z, z] - Z
        xcap = np.copy(x)
        ycap = np.copy(y)
        zcap = np.zeros_like(x)-Z
        t = np.r_[0, t]

        if xrot != 0.0 or yrot != 0.0 or zrot != 0.0:
            pts = np.matrix(np.vstack((x,y,z)))
            R = np.identity(3)
            if xrot != 0.0:
                c = cos(xrot)
                s = sin(xrot)
                R = np.matrix([[1,0,0],[0,c,-s],[0,s,c]])*R
            if yrot != 0.0:
                c = cos(yrot)
                s = sin(yrot)
                R = np.matrix([[c,0,s],[0,1,0],[-s,0,c]])*R
            if zrot != 0.0:
                c = cos(zrot)
                s = sin(zrot)
                R = np.matrix([[c,-s,0],[s,c,0],[0,0,1]])*R
            



            for i in range(len(x)):
                x[i],y[i],z[i] = R*pts[:,i]
            #x,y,z = R*pts
            #x = np.array(x).flatten()
            #y = np.array(y).flatten()
            #z = np.array(z).flatten()
            #print R*pts
            #print np.shape(np.array(x).flatten()),y,z
            #raise SystemExit
            ptscap = np.matrix(np.vstack((xcap,ycap,zcap)))
            for i in range(len(x)):
                xcap[i],ycap[i],zcap[i] = R*ptscap[:,i]
            #xcap,ycap,zcap = R*ptscap
            #xcap = np.array(xcap).flatten()
            #ycap = np.array(ycap).flatten()
            #zcap = np.array(zcap).flatten()
        

        beam = mlab.triangular_mesh(x+self.xp, y+self.yp, z+self.zp, triangles,color=COLOR_BEAM)
        cap = mlab.triangular_mesh(xcap+self.xp, ycap+self.yp, zcap+self.zp, triangles,color=COLOR_BEAM)
        return beam,cap
示例#18
0
 def plotSurfaces(self, X, T, scalars=None, color=None, rep='surface'):
     
     if self.autoRemove: self.removeSurfaces()
     
     if color==None: color=(1,0,0)
     if scalars==None:
         self.surfaces.append(mlab.triangular_mesh(X[:,0], X[:,1], X[:,2], T, color=color, representation=rep))
     else:
         self.surfaces.append(mlab.triangular_mesh(X[:,0], X[:,1], X[:,2], T, scalars=scalars))
示例#19
0
    def show(self, using='maya', fit_ellipse=False, show_hull=False):
        """
        A simple scatter-plot to represent the aggregate - either using mpl
        or mayavi
        """

        if fit_ellipse:

            (center, radii, rotation) = self.fit_ellipse()

            u = np.linspace(0.0, 2.0 * np.pi, 100)
            v = np.linspace(0.0, np.pi, 100)

            # cartesian coordinates that correspond to the spherical angles:
            x = radii[0] * np.outer(np.cos(u), np.sin(v))
            y = radii[1] * np.outer(np.sin(u), np.sin(v))
            z = radii[2] * np.outer(np.ones_like(u), np.cos(v))
            # rotate accordingly
            for i in range(len(x)):
                for j in range(len(x)):
                    [x[i,j],y[i,j],z[i,j]] = np.dot([x[i,j],y[i,j],z[i,j]], rotation) + center

        if show_hull:
            hull = self.chull()
            hull_x = hull.points[:,0]
            hull_y = hull.points[:,1]
            hull_z = hull.points[:,2]

        if using=='mpl':

            from mpl_toolkits.mplot3d import Axes3D
            fig = plt.figure()
            # ax = fig.add_subplot(111, projection='3d'
            ax = Axes3D(fig) 
            # ax.set_aspect('equal')
            h = ax.scatter(self.pos[:,0], self.pos[:,1], self.pos[:,2], s=100.)

            if fit_ellipse:
                ax.plot_wireframe(x, y, z,  rstride=4, cstride=4, color='k', alpha=0.2)
            plt.show()

        elif using=='maya':
            import mayavi.mlab as mlab
            fig = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
            h = mlab.points3d(self.pos[:,0], self.pos[:,1], self.pos[:,2], self.radius, scale_factor=2, resolution=16)

            if fit_ellipse:
                mlab.mesh(x,y,z, opacity=0.25, color=(1,1,1))

            if show_hull:
                mlab.triangular_mesh(hull_x, hull_y, hull_z, hull.simplices, representation='wireframe', color=(1,1,1))

        else:
            print('ERROR: using= must ne either mpl or maya')

        return h
示例#20
0
文件: Figures.py 项目: jessebett/USRA
def makecoarsegrid():
    coor=make_uni_coor(100)
    sphere= make_sphere(coor)


    mlab.figure()
    mlab.points3d(coor.x, coor.y, coor.z, 
                      scale_factor=0.1)
    mlab.triangular_mesh(coor.x,coor.y,coor.z,sphere.faces)
    savefig('coarsegrid.png')
示例#21
0
 def plot(self, color=None, facevec=None):
     from mayavi import mlab
     q = self.vertices.mean(axis=0) * 0
     x, y, z = (self.vertices + q / 4).T
     mlab.triangular_mesh(x, y, z, self.faces, scalars=color)
     # mlab.triangular_mesh(x, y, z, t, color=(0, 0, 0), representation='wireframe')
     if facevec is not None:
         centroids = self.face_centroids()
         mlab.quiver3d(*np.concatenate([centroids, facevec], axis=1).T)
     mlab.show()
示例#22
0
文件: mesh.py 项目: kinnala/sp.fem
 def draw_edges(self):
     """Draw all edges in a wireframe representation."""
     # use mayavi
     if OPT_MAYAVI:
         mlab.triangular_mesh(self.p[0, :], self.p[1, :], self.p[2, :],
                              self.facets.T, representation='wireframe',
                              color=(0, 0, 0))
     else:
         raise ImportError("Mayavi not supported "
                           "by the host system!")
示例#23
0
文件: plots.py 项目: rirze/gravpy
def mag_map(x,y,mag,simplices):

    # TODO: currently broken and does not work
    import mayavi.mlab as m
    cutoff_log = -2
    scaled_mag = np.log10(mag) #so invalid values aren't raised, shouldn't affect visulization
#    scaled_mag[np.isnan(scaled_mag)] = cutoff_log
#    scaled_mag[scaled_mag<cutoff_log] = cutoff_log
    scaled_mag = np.nan_to_num(scaled_mag)
    m.triangular_mesh(x,y,scaled_mag,simplices)
    m.show()
示例#24
0
文件: tools.py 项目: inducer/modepy
def estimate_lebesgue_constant(n, nodes, visualize=False):
    """Estimate the
    `Lebesgue constant
    <https://en.wikipedia.org/wiki/Lebesgue_constant_(interpolation)>`_
    of the *nodes* at polynomial order *n*.

    :arg nodes: an array of shape *(dims, nnodes)* as returned by
        :func:`modepy.warp_and_blend_nodes`.
    :arg visualize: visualize the function that gives rise to the
        returned Lebesgue constant. (2D only for now)
    :return: the Lebesgue constant, a scalar

    .. versionadded:: 2013.2
    """
    from modepy.matrices import vandermonde
    from modepy.modes import simplex_onb

    dims = len(nodes)
    basis = simplex_onb(dims, n)
    vdm = vandermonde(basis, nodes)

    from pytools import generate_nonnegative_integer_tuples_summing_to_at_most \
            as gnitstam
    huge_n = 30*n
    equi_node_tuples = list(gnitstam(huge_n, dims))
    tons_of_equi_nodes = (
            np.array(equi_node_tuples, dtype=np.float64)
            / huge_n * 2 - 1).T

    eq_vdm = vandermonde(basis, tons_of_equi_nodes)
    eq_to_out = la.solve(vdm.T, eq_vdm.T).T

    lebesgue_worst = np.sum(np.abs(eq_to_out), axis=1)
    lebesgue_constant = np.max(lebesgue_worst)

    if visualize:
        print("Lebesgue constant: %g" % lebesgue_constant)
        from modepy.tools import submesh

        import mayavi.mlab as mlab
        mlab.figure(bgcolor=(1, 1, 1))
        mlab.triangular_mesh(
                tons_of_equi_nodes[0],
                tons_of_equi_nodes[1],
                lebesgue_worst / lebesgue_constant,
                submesh(equi_node_tuples))

        x, y = np.mgrid[-1:1:20j, -1:1:20j]
        mlab.mesh(x, y, 0*x, representation="wireframe", color=(0.4, 0.4, 0.4),
                line_width=0.6)

        mlab.show()

    return lebesgue_constant
示例#25
0
def preview(vertices, triangles):
    try:
        logging.info("Plotting mesh for preview...")
        from mayavi import mlab
        mlab.triangular_mesh(
            vertices[:, 0], vertices[:, 1], vertices[:, 2],
            triangles)
        print "Done."
        mlab.show()
    except ImportError:
        logging.error("Could not import mayavi. Interactive demo not available.")
示例#26
0
def show_surface(pth):
    """
    show surface from a h5
    """
    mlab.figure()
    cap = h5py.File(pth)
    v = numpy.array(cap['vertices'])
    t = numpy.array(cap['triangles'])

    mlab.triangular_mesh(v[:,0], v[:,1], v[:,2], t)
    mlab.axes()
示例#27
0
 def plot(self):
   dots = np.zeros((2*(n_gen+1), 3))
   dots[0:n_gen+1] = self.origin + self.support + self.gen
   dots[n_gen+1:] = self.origin + self.support
   triangles = np.zeros((2*(n_gen+1), 3))
   for i in np.arange(0, n_gen):
       triangles[i] = np.array([i, i + n_gen, i + n_gen + 1])
       triangles[i + n_gen] = np.array([i, i + 1, i + n_gen + 1])
   #print(dots.shape)
   #print(triangles.shape)
   import mayavi.mlab as mlab
   mlab.triangular_mesh(dots[:,0], dots[:,1], dots[:,2], triangles)
示例#28
0
 def _render_mesh(self, mesh_type, line_width, colour, marker_size,
                  marker_resolution, marker_style, step, alpha):
     import mayavi.mlab as mlab
     marker_size = _parse_marker_size(marker_size, self.points)
     colour = _parse_colour(colour)
     mlab.triangular_mesh(self.points[:, 0], self.points[:, 1],
                          self.points[:, 2], self.trilist,
                          figure=self.figure, line_width=line_width,
                          representation=mesh_type, color=colour,
                          scale_factor=marker_size, mask_points=step,
                          resolution=marker_resolution, mode=marker_style,
                          opacity=alpha, tube_radius=None)
示例#29
0
def vis(b, p, dp, faces, gt_mesh, image, duration=5, fps=2):
    import matplotlib.pyplot as plt
    plt.imshow(image)
    mlab.figure()
    v, f = (np.array(gt_mesh[k]) for k in ('vertices', 'faces'))
    x, z, y = v.T
    mlab.triangular_mesh(x, y, z, f, color=(0, 0, 1), opacity=0.2)
    mlab.figure()
    vis_anim(b, p, dp, faces, duration, fps)
    plt.show(block=False)
    mlab.show()
    plt.close()
示例#30
0
def plot_forward_operator(subject, fnout_img=None):
    """"Reads in and plots the forward solution."""

    # get name of inverse solution-file
    subjects_dir = os.environ.get('SUBJECTS_DIR')
    fname_dir_fwd = os.path.join(subjects_dir,
                                 subject)

    for files in os.listdir(fname_dir_fwd):
        if files.endswith(",cleaned_epochs_avg-7-src-fwd.fif"):
            fname_fwd = os.path.join(fname_dir_fwd,
                                     files)
            break

    try:
        fname_fwd
    except NameError:
        print "ERROR: No forward solution found!"
        sys.exit()


    # read inverse solution
    add_geom = True # include high resolution source space
    src = mne.read_source_spaces(fname_fwd,
                                 add_geom=add_geom)

    # 3D source space (high sampling)
    lh_points = src[0]['rr']
    lh_faces = src[0]['tris']
    rh_points = src[1]['rr']
    rh_faces = src[1]['tris']

    # create figure and plot results
    fig_forward = mlab.figure(size=(1200, 1200),
                              bgcolor=(0, 0, 0))
    mlab.triangular_mesh(lh_points[:, 0],
                         lh_points[:, 1],
                         lh_points[:, 2],
                         lh_faces)

    mlab.triangular_mesh(rh_points[:, 0],
                         rh_points[:, 1],
                         rh_points[:, 2],
                         rh_faces)

    # save image if desired
    if fnout_img is not None:
        mlab.savefig(fnout_img,
                     figure=fig_forward,
                     size=(1200, 1200))

    mlab.close(all=True)
示例#31
0
def create_random_section_2_points(strat, facies, thalweg_z, h, scale, ve,
                                   color_mode, colors, x1, x2, y1, y2, s1, dx,
                                   bottom, export):
    r, c, ts = np.shape(strat)
    dist = dx * ((x2 - x1)**2 + (y2 - y1)**2)**0.5
    s2 = s1 * dx + dist
    num = int(dist / float(dx))
    cmap = matplotlib.cm.get_cmap('viridis')
    norm = matplotlib.colors.Normalize(vmin=0.0, vmax=ts - 1)
    Xrand, Yrand, Srand = np.linspace(x1, x2, num), np.linspace(
        y1, y2, num), np.linspace(s1 * dx, s2, num)
    base = scipy.ndimage.map_coordinates(strat[:, :, 0],
                                         np.vstack((Yrand, Xrand)))
    vertices, triangles = create_section(base, dx, bottom)
    gray = (0.6, 0.6, 0.6)  # color for plotting basal part of panel
    mlab.triangular_mesh(scale * np.hstack((dx * Xrand, dx * Xrand[::-1])),
                         scale * np.hstack((dx * Yrand, dx * Yrand[::-1])),
                         scale * ve * vertices[:, 1],
                         triangles,
                         color=gray)
    for layer_n in range(0, ts - 1):
        update_progress(layer_n / (ts - 1))
        vmin = thalweg_z[layer_n]  # minimum elevation (for colormap)
        vmax = vmin + h  # maximum elevation (for colormap)
        top = scipy.ndimage.map_coordinates(strat[:, :, layer_n + 1],
                                            np.vstack((Yrand, Xrand)))
        base = scipy.ndimage.map_coordinates(strat[:, :, layer_n],
                                             np.vstack((Yrand, Xrand)))
        if np.max(top - base) > 1e-6:
            Points, Inds = triangulate_layers(top, base, dx)
            for i in range(len(Points)):
                vertices = Points[i]
                inds = Inds[i]
                triangles, scalars = create_triangles(vertices)
                X1 = scale * dx * Xrand[inds]
                Y1 = scale * dx * Yrand[inds]
                Z1 = scale * vertices[:, 1]
                plot_layers_on_one_side(layer_n, facies, color_mode, colors,
                                        X1, Y1, Z1, ve, triangles, vertices,
                                        scalars, cmap, norm, vmin, vmax,
                                        export)
示例#32
0
def plot_element_values(n,
                        nodes,
                        values,
                        resample_n=None,
                        node_tuples=None,
                        show_nodes=False):
    dims = len(nodes)

    orig_nodes = nodes
    orig_values = values

    if resample_n is not None:
        import modepy as mp
        basis = mp.simplex_onb(dims, n)
        fine_nodes = mp.equidistant_nodes(dims, resample_n)

        values = np.dot(mp.resampling_matrix(basis, fine_nodes, nodes), values)
        nodes = fine_nodes
        n = resample_n

    from pytools import generate_nonnegative_integer_tuples_summing_to_at_most \
            as gnitstam

    if dims == 1:
        import matplotlib.pyplot as pt
        pt.plot(nodes[0], values)
        if show_nodes:
            pt.plot(orig_nodes[0], orig_values, "x")
        pt.show()
    elif dims == 2:
        import mayavi.mlab as mlab
        mlab.triangular_mesh(nodes[0], nodes[1], values,
                             submesh(list(gnitstam(n, 2))))
        if show_nodes:
            mlab.points3d(orig_nodes[0],
                          orig_nodes[1],
                          orig_values,
                          scale_factor=0.05)
        mlab.show()
    else:
        raise RuntimeError("unsupported dimensionality %d" % dims)
示例#33
0
 def view_step(self):
     from mayavi import mlab
     if self.figure is None:
         self.figure = mlab.triangular_mesh(self.pts[:, 0],
                                            self.pts[:, 1],
                                            self.pts[:, 2],
                                            self.polys,
                                            representation='wireframe')
     self.step()
     self.figure.mlab_source.set(x=self.pts[:, 0],
                                 y=self.pts[:, 1],
                                 z=self.pts[:, 2])
示例#34
0
def visualize_current_modes(
    mesh, vl, Nmodes, scale, contours=True, colormap="bwr", dist=0.5
):
    """
    Visualizes current modes up to Nmodes.

    Parameters
    ----------
    mesh: Trimesh mesh object
        The surface mesh
    vl: Nvertices x Nvertices array
        The normalized eddy-current modes vl[:,i]
    Nmodes: int
        Number of modes to be plotted
    scale: float
        Scaling factor
    contours: boolean
        If True, show contours
    colormap: string
        Which (matplotlib) colormap to use

    """
    from mayavi import mlab

    N1 = np.floor(np.sqrt(Nmodes))
    dx = (mesh.vertices[:, 0].max() - mesh.vertices[:, 0].min()) * (1 + dist)
    dy = (mesh.vertices[:, 1].max() - mesh.vertices[:, 1].min()) * (1 + dist)

    i = 0
    j = 0
    for n in range(Nmodes):
        print(i, j)
        points = mesh.vertices.copy()
        points[:, 0] += i * dx
        points[:, 1] += j * dy
        s = mlab.triangular_mesh(
            *points.T, mesh.faces, scalars=vl[:, n], colormap=colormap
        )

        limit = np.max(np.abs(vl[:, n]))

        s.module_manager.scalar_lut_manager.number_of_colors = 256
        s.module_manager.scalar_lut_manager.data_range = np.array([-limit, limit])
        s.actor.mapper.interpolate_scalars_before_mapping = True
        s.enable_contours = contours

        if i < N1:
            i += 1
        else:
            j += 1
            i = 0

    return s
示例#35
0
def plot_triangular_mesh(verts,
                         triangles,
                         fig,
                         representation='wireframe',
                         color=None):
    if color is None:
        color = tuple(np.random.rand(1, 3)[0])
    # Generate arrays.
    x = verts[:, 0]
    y = verts[:, 1]
    try:
        z = verts[:, 2]
    except IndexError:
        z = np.zeros(x.shape, dtype=np.float64)
    mlab.triangular_mesh(x,
                         y,
                         z,
                         triangles,
                         figure=fig,
                         representation=representation,
                         color=color)
 def __plot_mesh(self, triangle_mesh):
     mesh = mlab.triangular_mesh(triangle_mesh.vertices[:, 0],
                                 triangle_mesh.vertices[:, 1],
                                 triangle_mesh.vertices[:, 2],
                                 triangle_mesh.faces,
                                 colormap="bone",
                                 opacity=1.0)
     lut = mesh.module_manager.scalar_lut_manager.lut.table.to_array()
     lut[:, 0] = 255
     lut[:, 1] = 255
     lut[:, 2] = 255
     mesh.module_manager.scalar_lut_manager.lut.table = lut
示例#37
0
def PlotMesh(v, f):
    # plot a surface (vert & faces) as a 3D patch (trisurf)
    fig = mlab.figure(1, bgcolor=(0, 0, 0))
    pts = mlab.triangular_mesh(v[:, 0],
                               v[:, 1],
                               v[:, 2],
                               f,
                               color=(1, 1, 1),
                               opacity=0.3)
    mlab.get_engine().scenes[0].scene.x_plus_view()
    mlab.view(0., 0.)
    return pts, fig  #ax, p3dcollec, fig
示例#38
0
def test_triangular_mesh():
    """An example of a cone

    http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#triangular-mesh
    """
    n = 8
    t = np.linspace(-np.pi, np.pi, n)
    z = np.exp(1j * t)
    x = z.real.copy()
    y = z.imag.copy()
    z = np.zeros_like(x)

    triangles = [(0, i, i + 1) for i in range(1, n)]
    x = np.r_[0, x]
    y = np.r_[0, y]
    z = np.r_[1, z]
    t = np.r_[0, t]

    mlab.triangular_mesh(x, y, z, triangles)
    mlab.show()
    return 0
示例#39
0
def plot_rg():
    '''Now mark r_g for one grating for explain coordinate system'''
    gratingcoords = np.array(instrums[0].elements[2].elements[0].elem_pos)[:, :3, 3]
    # lower sector
    ind = (gratingcoords[:, 2] < np.mean(gratingcoords[:, 2])).nonzero()[0]
    # furthest form yz plane for visibility
    indmax = np.argmax(gratingcoords[ind, 0])
    rgx, rgy, rgz = gratingcoords[ind[indmax], :]
    # plane for grating coords
    r = np.sqrt(rgx**2 + rgy**2 + rgz**2)
    out = mlab.triangular_mesh(np.zeros_like(alpha),
                               np.array([0., 0., rgy]),
                               np.zeros(3),
                               [[0, 1, 2]],
                               opacity=0.7,
                               color=(0., 0., 1.))
    out = mlab.triangular_mesh(np.array([0., rgx, rgx]),
                               np.array([0., 0., rgy]),
                               np.array([rgz, rgz, rgz]),
                               [[0, 1, 2]],
                               opacity=0.7,
                               color=(0., 0., 1.))

    out = mlab.triangular_mesh(np.array([0., 0., rgx]),
                               np.array([0., 0., rgy]),
                               np.array([0., rgz, rgz]),

                               [[0, 1, 2]],
                               opacity=0.7,
                               color=(.5, .5, .5))
    # Draw a line projecting grating coord to the xy plane
    lines = np.array([[[rgx, rgy, rgz], [0, rgy, rgz]],
                      [[rgx, rgy, rgz], [0, rgy, rgz]],
                      [[rgx, rgy, rgz], [0, 0, 0]]])
    out = marxs.visualization.mayavi.plot_rays(lines,
                                               scalar=np.zeros(3),
                                               kwargssurface={'opacity': 1.,
                                                              'line_width': 3,
                                                              'colormap': 'blue-red'})
    return rgx, rgy, rgz
示例#40
0
def blobplotMayvi(blobs, latv, lonv, cmap, ib=[1], opacity=0.3, R=1.0):
    '''
    Renders an interactive MayaVi scene which contains the subset of blobs defined by the list ib.
    
    Default is to just plot the first blob.
    
    Colours are defined by a mpc.ListedColormap
    
    '''
    from mayavi import mlab

    for j, i in enumerate(ib):

        #extract data for this blob
        wdata = np.where(blobs[0] == i)

        #assign a color to this blob according to id number
        bcol = cmap(j)

        #inner loop over the time steps dts (need to adjust R by dz each time)
        dts = np.unique(wdata[0])
        Rin = R
        for t in dts:

            wtdata = np.where(wdata[0] == t)
            widata = np.take(wdata[1], wtdata)
            latvnn = np.take(
                latv, widata,
                axis=0)[0]  #extract verts for this blob for this time
            lonvnn = np.take(lonv, widata, axis=0)[0]

            res = trimesh(latvnn, lonvnn, R)
            R = res[0][4] + res[0][
                5]  #adjust radius to next level (nb not perfect since this changes with lat - maybe refine?)
            resFlat = flattenTrimesh(res)

            #assing a color to this blob according to id number
            bcol = cmap(j)
            x = resFlat[0]
            y = resFlat[1]
            z = resFlat[2]
            triangles = resFlat[3]
            s = mlab.triangular_mesh(x,
                                     y,
                                     z * (-1),
                                     triangles,
                                     color=bcol[0:3],
                                     opacity=opacity)  #nb need to flip z
        R = Rin
    mlab.show()

    return (R)
示例#41
0
def plot_mesh(mesh, cam_trafo=np.eye(4), mesh_pose=np.eye(4)):
    """
    Plots mesh in mesh_pose from 

    Arguments:
        mesh {trimesh.base.Trimesh} -- input mesh, e.g. gripper

    Keyword Arguments:
        cam_trafo {np.ndarray} -- 4x4 transformation from world to camera coords (default: {np.eye(4)})
        mesh_pose {np.ndarray} -- 4x4 transformation from mesh to world coords (default: {np.eye(4)})
    """

    homog_mesh_vert = np.pad(mesh.vertices, (0, 1),
                             'constant',
                             constant_values=(0, 1))
    mesh_cam = homog_mesh_vert.dot(mesh_pose.T).dot(cam_trafo.T)[:, :3]
    mlab.triangular_mesh(mesh_cam[:, 0],
                         mesh_cam[:, 1],
                         mesh_cam[:, 2],
                         mesh.faces,
                         colormap='Blues',
                         opacity=0.5)
    def test_trimesh_reset_twice_with_fewer_points(self):
        # Given
        x, y, z = np.random.random((3, 100))
        cells = np.random.randint(0, 100, 300)
        cells.resize((100, 3))
        surf = mlab.triangular_mesh(x, y, z, cells)

        # When/Then
        x, y, z = np.random.random((3, 5))
        cells = np.random.randint(0, 5, 15)
        cells.resize((5, 3))
        # If this works without a segfault, we are good.
        surf.mlab_source.reset(x=x, y=y, z=z, triangles=cells)
示例#43
0
文件: icosphere.py 项目: jstraub/js
 def Plot(self, level, figm, color=None):
     if level + 1 >= len(self.tri_levels):
         print "Cannot plot this level in the IcoSphere"
         return
     mlab.triangular_mesh(
         self.vertices[:, 0],
         self.vertices[:, 1],
         self.vertices[:, 2],
         self.tri[self.tri_levels[level]:self.tri_levels[level + 1], :],
         color=(0.6, 0.6, 0.6))
     if color is None:
         color = (level / float(self.depth), 1 - level / float(self.depth),
                  1.)
     tri = self.tri[self.tri_levels[level]:self.tri_levels[level + 1], :]
     for i in range(tri.shape[0]):
         for comb in combinations(range(3), 2):
             a = self.vertices[tri[i, comb[0]], :]
             b = self.vertices[tri[i, comb[1]], :]
             mlab.plot3d([a[0], b[0]], [a[1], b[1]], [a[2], b[2]],
                         tube_radius=0.02,
                         color=color)
     return
def showTriMeshUsingMatlot(TriVs,
                           TriFace,
                           mlab,
                           colormap=colorMaps[2],
                           opacity=1.0):
    """
    用mayavi 绘制三角面
    :param TriVs: 顶点
    :param TriFace: 点序
    :return:
    """
    if isinstance(TriVs, list):
        TriVs = np.array(TriVs, dtype=np.float32)
    if isinstance(TriFace, list):
        TriFace = np.array(TriFace, dtype=np.int32)
    mlab.triangular_mesh(TriVs[:, 0],
                         TriVs[:, 1],
                         TriVs[:, 2],
                         TriFace - 1,
                         colormap=colormap,
                         opacity=opacity)  # 注意索引值从0开始
    return mlab
示例#45
0
def plot(ply):
    '''
    Plot vertices and triangles from a PlyData instance. Assumptions:
        `ply' has a 'vertex' element with 'x', 'y', and 'z'
            properties;

        `ply' has a 'face' element with an integral list property
            'vertex_indices', all of whose elements have length 3.

    '''
    vertex = ply['vertex']

    (x, y, z) = (vertex[t] for t in ('x', 'y', 'z'))

    mlab.points3d(x, y, z, color=(1, 1, 1), mode='point')

    print(ply['face'])
    print(ply['face']['vertex_indices'])
    print(len(ply['face']['vertex_indices']))

    if 'face' in ply:
        tri_idx = ply['face']['vertex_indices']
        idx_dtype = tri_idx[0].dtype
        print(idx_dtype)

        # triangles = numpy.fromiter(tri_idx, [('data', idx_dtype, (3,))],
        #                           count=len(tri_idx))['data']
        triangles = [
            (0, 1, 2),
            (0, 1, 3),
            (1, 2, 3),
        ]

        mlab.triangular_mesh(x,
                             y,
                             z,
                             triangles,
                             color=(1, 0, 0.4),
                             opacity=0.5)
示例#46
0
def plot_poly(mat, alpha):
    cols = [np.array([c]) for c in zip(*mat)]
    mlab.points3d(*cols, scale_factor=0.01)

    tri = ConvexHull(mat)

    surf = mlab.triangular_mesh(cols[0],
                                cols[1],
                                cols[2],
                                tri.simplices,
                                opacity=alpha,
                                colormap='copper')
    return surf
def main():
    pathdcm = "/Users/Parth/Downloads/1.nii.gz"

    voxelData, spacing = getArray(pathdcm)
    print voxelData.shape
    voxelData /= np.amax(voxelData)
    # voxelData *=255
    # voxelData = np.uint8(voxelData)

    ConstPixelSpacing = (spacing[2], spacing[1], spacing[0])
    thresh = 0
    # voxelData[voxelData<thresh] = 0
    for i in range(voxelData.shape[2]):
        # voxelData[:, :, i] = largest_connected_component(voxelData[:,:,i])
        # print i
        # voxelData[:, :, i] = binary_fill_holes(voxelData[:,:,i])
        # for i in range(voxelData.shape[1]):
        voxelData[:, i] = filters.gaussian(voxelData[:, i], sigma=2)
        thresh = image.otsu(voxelData[:, :, i])
        voxelData[voxelData < thresh] = 0
    # for i in range(voxelData.shape[0]):
    # voxelData[i] = filters.gaussian(voxelData[i],sigma=2)

    # thresh += filters.threshold_mean(voxelData[:, :, i])

    # print thresh
    # img = voxelData[:, :, i]
    # img[img < thresh] = 0
    # voxelData[:, :, i] = img

    thresh /= voxelData.shape[2]
    # thresh = 0.01
    # voxelData[voxelData<thresh] = 0

    # print thresh
    verts, faces, _, _ = measure.marching_cubes_lewiner(
        voxelData, 0, ConstPixelSpacing)
    mlab.triangular_mesh(verts[:, 0], verts[:, 1], verts[:, 2], faces)
    mlab.show()
示例#48
0
def avgplot(r_labels, nSubjects, r_vertices, r_faces, nCluster):
    labels = np.zeros(r_labels.shape[0], dtype=float)
    for i in range(r_labels.shape[0]):
        labels[i] = np.sum(r_labels[i]) / nSubjects
    mlab.figure(size=(1024, 768), \
                bgcolor=(1, 1, 1),fgcolor=(0.5,0.5,0.5))
    mlab.triangular_mesh(r_vertices[:, 0],
                         r_vertices[:, 1],
                         r_vertices[:, 2],
                         r_faces,
                         representation='surface',
                         opacity=1,
                         scalars=np.float64(labels))
    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=0, elevation=90)
    mlab.colorbar(orientation='vertical')
    mlab.show()
    #mlab.close()
    labels = np.zeros(r_labels.shape[0], dtype=float)
    freq = np.zeros(r_labels.shape[0], dtype=float)
    for i in range(r_labels.shape[0]):
        mode, count = stats.mode(r_labels[i])
        labels[i] = mode[0]
        freq[i] = count
    mlab.figure(size=(1024, 768), \
                bgcolor=(1, 1, 1),fgcolor=(0.5,0.5,0.5))
    mlab.triangular_mesh(r_vertices[:, 0],
                         r_vertices[:, 1],
                         r_vertices[:, 2],
                         r_faces,
                         representation='surface',
                         opacity=1,
                         scalars=np.float64(labels))
    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=0, elevation=10)
    mlab.colorbar(orientation='vertical')
    mlab.show()
    #mlab.close()
    return labels, freq
示例#49
0
 def plot(self,
          surface,
          points,
          borderpoints_no,
          point_scale_factor=1.0,
          colormap='Accent'):
     if points is None:
         mlab.figure(bgcolor=(1, 1, 1))
         m = mlab.triangular_mesh(surface.V[:, 0],
                                  surface.V[:, 1],
                                  surface.V[:, 2],
                                  surface.F,
                                  color=(0.6, 0.6, 0.6),
                                  representation='surface')
         mlab.show()
     else:
         cols = range(1, points[borderpoints_no:, 0].shape[0] + 1)
         f = mlab.figure(bgcolor=(1, 1, 1))
         m = mlab.triangular_mesh(surface.V[:, 0],
                                  surface.V[:, 1],
                                  surface.V[:, 2],
                                  surface.F,
                                  color=(0.5, 0.5, 0.5),
                                  representation='surface')
         b = mlab.points3d(points[:borderpoints_no, 0],
                           points[:borderpoints_no, 1],
                           points[:borderpoints_no, 2],
                           color=(0, 0, 0),
                           scale_factor=point_scale_factor,
                           scale_mode='none')
         #p = mlab.points3d(points[borderpoints_no:,0], points[borderpoints_no:,1], points[borderpoints_no:,2], cols, colormap = colormap, scale_factor = point_scale_factor, scale_mode = 'none')
         p = mlab.points3d(points[borderpoints_no:, 0],
                           points[borderpoints_no:, 1],
                           points[borderpoints_no:, 2],
                           color=(1, 0, 0),
                           scale_factor=point_scale_factor,
                           scale_mode='none')
         mlab.show()
     return None
示例#50
0
def visualize_point_cloud(X, faces=None, mv=None, mlab_obj=None):
    """
    Visualize two point clouds
        visualize_point_cloud(X)

    Inputs:
    ------------
    X    
        matrix of point clouds of dimensions Nx3

    faces 
        if different than None is a 3xN matrix indicating which verts are connected
    mv
        MeshViewer

    Outputs
    ------------
    
    Mesh visualization
    """
    use_meshviewer = False
    if use_meshviewer:
        from body.mesh import Mesh
        import types
        mesh1 = Mesh(v=X, f=faces)
        mesh2 = Mesh(v=Y, f=faces)
        mesh2.set_vertex_colors('SeaGreen')
        if isinstance(mv, types.ListType):
            mv[0][0].set_dynamic_meshes([mesh1, mesh2])
            mv[0][1].set_dynamic_meshes([mesh1])
        else:
            mv.set_dynamic_meshes([mesh1, mesh2])
    else:
        #!/usr/local/bin/ipython --gui=wx
        from mayavi.mlab import triangular_mesh, figure, clf
        import numpy as np
        from os.path import join
        fig = mv
        verts1 = X.T
        if mlab_obj is None:
            clf(fig)
            mlab_obj = triangular_mesh(verts1[0],
                                       verts1[1],
                                       verts1[2],
                                       faces,
                                       color=(.7, .7, .9),
                                       figure=fig)
            fig.scene.reset_zoom()
        else:
            mlab_obj.mlab_source.set(x=verts1[0], y=verts1[1], z=verts1[2])
        return mlab_obj
示例#51
0
def vismesh(pts,
            tris,
            color=None,
            edge_visibility=False,
            shader=None,
            triangle_scalars=None,
            colors=None,
            nan_color=None,
            **kwargs):
    if 'scalars' in kwargs and np.asarray(kwargs['scalars']).ndim == 2:
        colors = kwargs['scalars']
        del kwargs['scalars']
    # VTK does not allow bool arrays as scalars normally, so convert to float
    if 'scalars' in kwargs and np.asarray(kwargs['scalars']).dtype == np.bool:
        kwargs['scalars'] = kwargs['scalars'].astype(np.float)

    tm = mlab.triangular_mesh(pts[:, 0],
                              pts[:, 1],
                              pts[:, 2],
                              tris,
                              color=color,
                              **kwargs)
    if shader is not None:
        tm.actor.property.load_material(shader)
        tm.actor.actor.property.shading = True
    diffuse = 1.0 if colors is not None else 0.8
    tm.actor.actor.property.set(edge_visibility=edge_visibility,
                                line_width=1,
                                specular=0.0,
                                specular_power=128.,
                                diffuse=diffuse)
    if triangle_scalars is not None:
        tm.actor.mapper.input.cell_data.scalars = triangle_scalars
        tm.actor.mapper.set(scalar_mode='use_cell_data',
                            use_lookup_table_scalar_range=False,
                            scalar_visibility=True)
        if "vmin" in kwargs and "vmax" in kwargs:
            tm.actor.mapper.scalar_range = kwargs["vmin"], kwargs["vmax"]
    if colors is not None:
        # this basically is a hack which doesn't quite work,
        # we have to completely replace the polydata behind the hands of mayavi
        tm.mlab_source.dataset.point_data.scalars = colors.astype(np.uint8)
        normals = tvtk.PolyDataNormals(splitting=False)
        configure_input_data(normals, tm.mlab_source.dataset)
        configure_input(tm.actor.mapper, normals)
    if nan_color is not None:
        if len(nan_color) == 3:
            nan_color = list(nan_color) + [1]
        tm.module_manager.scalar_lut_manager.lut.nan_color = nan_color
        tm.update_pipeline()
    return tm
示例#52
0
文件: core.py 项目: vatthaphon/brede
    def _plot_mayavi(self, *args, **kwargs):
        """Plot surface with Mayavi.

        The x-axis is switched to account for the Mayavi's right-handed
        coordinate system and Talairach's left-handed coordinate system.

        Parameters
        ----------
        title : str
            String to use as title in the plot

        """
        # Delayed import of Mayavi
        from mayavi.mlab import title as mlab_title, triangular_mesh

        title = kwargs.pop('title', None)

        if self._vertex_values is None:
            handle = triangular_mesh(
                self._vertices[:, 0],
                self._vertices[:, 1],
                self._vertices[:, 2],
                self._faces,
                scalars=self._vertex_values,
                *args, **kwargs)
        else:
            handle = triangular_mesh(
                self._vertices[:, 0],
                self._vertices[:, 1],
                self._vertices[:, 2],
                self._faces,
                scalars=self._vertex_values,
                *args, **kwargs)

        if title is not None:
            mlab_title(title)

        return handle
示例#53
0
def multi_view(fig, vert_coords, faces, morphometry_data):
    """
    Experimental, ignore.

    Copy the original mesh, then rotate and translate it to get another view. Fakes a very simple and stupid multi-view in a single view.
    """
    mesh_in_central_position = bv.brain_morphometry_view(
        fig, vert_coords, faces, morphometry_data)
    x, y, z = st.coords_a2s(vert_coords)

    # Create lateral view
    x1, y1, z1 = st.rotate_3D_coordinates_around_axes(x, y, z, st.deg2rad(90),
                                                      0, 0)
    mayavi_mesh_m1 = mlab.triangular_mesh(x1,
                                          y1,
                                          z1,
                                          faces,
                                          scalars=morphometry_data,
                                          color=(1, 0, 0))
    dt._print_mlab_view()

    x2, y2, z2 = st.rotate_3D_coordinates_around_axes(x, y, z, st.deg2rad(90),
                                                      0, 0)
    x2, y2, z2 = st.scale_3D_coordinates(x2, y2, z2, 1.5)
    # = rotate_3D_coordinates_around_axes(x, y, z, rotx, roty, rotz)
    # = scale_3D_coordinates(x, y, z, x_scale_factor, y_scale_factor=None, z_scale_factor=None)
    # = mirror_3D_coordinates_at_axis(x, y, z, axis, mirror_at_axis_coordinate=None)
    # = point_mirror_3D_coordinates(x, y, z, point_x, point_y, point_z):
    x2, y2, z2 = st.translate_3D_coordinates_along_axes(x, y, z, 200, 0, 0)
    mayavi_mesh_m2 = mlab.triangular_mesh(x2,
                                          y2,
                                          z2,
                                          faces,
                                          scalars=morphometry_data,
                                          color=(0, 0, 1))
    dt._print_mlab_view()
    meshes = [mayavi_mesh_m1, mayavi_mesh_m2]
    return meshes
示例#54
0
def mesh(outfile=None, points=None, triangles=None, potentials=None, **kwds):
    """
    Visualize a triangular mesh.
    """

    xyz = points.T
    tm = mlab.triangular_mesh(xyz[0],
                              xyz[1],
                              xyz[2],
                              triangles,
                              scalars=potentials)
    if outfile:
        mlab.savefig(outfile)
    return tm
示例#55
0
    def plot(self, background=True, contours=False, **kwargs):
        """
        Plot the stream function
        """
        from mayavi import mlab

        mesh = self.mesh_conductor.mesh
        scalars = self.vert
        if "vmin" not in kwargs.keys():
            kwargs["vmin"] = -np.max(abs(scalars))
        if "vmax" not in kwargs.keys():
            kwargs["vmax"] = np.max(abs(scalars))

        s = plot_data_on_vertices(mesh, scalars, **kwargs)
        if contours:
            s.enable_contours = True
            s.contour.number_of_contours = contours
            if background:
                mlab.triangular_mesh(
                    *mesh.vertices.T, mesh.faces, color=(0.5, 0.5, 0.5), opacity=0.2
                )

        return s
示例#56
0
def viz_volume(volumeimg, sampling=1, cmap='gray', opacity=0.5, thresh=10):

    from mayavi import mlab
    from skimage import measure
    import numpy as np

    verts, faces, _, vals = measure.marching_cubes_lewiner(volumeimg,
                                                           thresh,
                                                           spacing=(1, 1, 1),
                                                           step_size=sampling)
    world_centre = np.mean(verts, axis=0)  # compute the world centre coords.

    mlab.triangular_mesh(verts[:, 0] - world_centre[0],
                         verts[:, 1] - world_centre[1],
                         verts[:, 2] - world_centre[2],
                         faces,
                         scalars=vals,
                         colormap=cmap,
                         opacity=opacity)

    mlab.show()

    return []
示例#57
0
def plot_reconstruction(patch_uvs, patch_tx, patch_models, scale=1.0):
    from mayavi import mlab

    with torch.no_grad():
        for i in range(len(patch_models)):
            n = 128
            translate_i, scale_i, rotate_i = patch_tx[i]
            uv_i = utils.meshgrid_from_lloyd_ts(patch_uvs[i].cpu().numpy(),
                                                n,
                                                scale=scale).astype(np.float32)
            uv_i = torch.from_numpy(uv_i).to(patch_uvs[0])
            y_i = patch_models[i](uv_i)

            mesh_v = ((y_i.squeeze() @ rotate_i.transpose(0, 1)) / scale_i -
                      translate_i).cpu().numpy()
            mesh_f = utils.meshgrid_face_indices(n)
            mlab.triangular_mesh(mesh_v[:, 0],
                                 mesh_v[:, 1],
                                 mesh_v[:, 2],
                                 mesh_f,
                                 color=(0.2, 0.2, 0.8))

        mlab.show()
示例#58
0
def display_simple_using_mayavi_vf1(verts,
                                    faces,
                                    minmax=(-1, 1),
                                    mayavi_wireframe=False):
    from mayavi import mlab
    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=1,
        scale_factor=100.0)

    (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.show()  # figure=fig,
示例#59
0
    def draw_scene2(self):
        mlab.clf(figure=self.scene2.mayavi_scene)
        mlab.triangular_mesh(self.ny_head.cortex[0, :],
                             self.ny_head.cortex[1, :],
                             self.ny_head.cortex[2, :],
                             self.ny_head.cortex_tri.T,
                             color=self.head_color,
                             figure=self.scene2.mayavi_scene)

        # Draw x,y,z-lines through dipole position
        # mlab.plot3d([x_lim[0], dipole_pos[0], x_lim[1]],
        #             [dipole_pos[1], dipole_pos[1], dipole_pos[1]],
        #             [dipole_pos[2], dipole_pos[2], dipole_pos[2]],
        #             color=(1,0,0), tube_radius=0.5, figure=self.scene2.mayavi_scene)
        #
        # mlab.plot3d([dipole_pos[0], dipole_pos[0], dipole_pos[0]],
        #             [y_lim[0], dipole_pos[1], y_lim[1]],
        #             [dipole_pos[2], dipole_pos[2], dipole_pos[2]],
        #             color=(0,1,0), tube_radius=0.5, figure=self.scene2.mayavi_scene)
        #
        # mlab.plot3d([dipole_pos[0], dipole_pos[0], dipole_pos[0]],
        #             [dipole_pos[1], dipole_pos[1], dipole_pos[1]],
        #             [z_lim[0], dipole_pos[2], z_lim[1]],
        #             color=(0,0,1), tube_radius=0.5, figure=self.scene2.mayavi_scene)

        # Draw dipole direction
        print(self.ny_head.dipole_moment[0])
        mlab.quiver3d(np.array([self.ny_head.dipole_pos[0]]),
                      np.array([self.ny_head.dipole_pos[1]]),
                      np.array([self.ny_head.dipole_pos[2]]),
                      np.array(self.ny_head.dipole_moment[0]),
                      np.array(self.ny_head.dipole_moment[1]),
                      np.array(self.ny_head.dipole_moment[2]),
                      scale_factor=40,
                      line_width=5,
                      color=(0, 0, 0),
                      figure=self.scene2.mayavi_scene)
示例#60
0
def plot_mesh(coord_array, tri_array, figure_name='Mesh'):
    """ plot_mesh plots an unsorted triangular part mesh from xyz coordinates and triangle connectivity
    :param coord_array: xyz coordinates per vertex in array of shape=(#points, 3)
    :param tri_array: vertex connection indices of the part in array of shape=(#triangles, 3)
    :return:
    """

    mlab.figure(figure=figure_name,
                bgcolor=(1, 1, 1),
                fgcolor=(0, 0, 0),
                size=(1500, 1250))

    # Create black wireframe mesh
    wire_mesh = mlab.triangular_mesh(coord_array[:, 0],
                                     coord_array[:, 1],
                                     coord_array[:, 2],
                                     tri_array,
                                     scalars=None,
                                     line_width=0.1,
                                     representation='wireframe',
                                     color=(0, 0, 0),
                                     opacity=0.1)

    # Create face coloring
    wire_mesh.mlab_source.dataset.cell_data
    wire_mesh.mlab_source.dataset.cell_data.scalars = np.ones(
        shape=(tri_array.shape[0]))
    wire_mesh.mlab_source.dataset.cell_data.scalars.name = 'Cell data'
    wire_mesh.mlab_source.update()

    mesh = mlab.pipeline.set_active_attribute(wire_mesh,
                                              cell_scalars='Cell data')
    surf = mlab.pipeline.surface(mesh, colormap='jet')

    # Retrieve the LUT colormap of the surf object. (256x4)
    # this is an array of (R, G, B, A) values (each in range 0-255)
    lut = surf.module_manager.scalar_lut_manager.lut.table.to_array()

    # Modify lut for single green color
    lut[:, 0] = np.ones((lut.shape[0])) * 75
    lut[:, 1] = np.ones((lut.shape[0])) * 173
    lut[:, 2] = np.ones((lut.shape[0])) * 137
    lut[:, 3] = np.ones((lut.shape[0])) * 255

    # Now use this colormap
    surf.module_manager.scalar_lut_manager.lut.table = lut

    # Show plot
    mlab.show()