Пример #1
0
def solidTeapot(translation=None, scaling=None, direction=None, rotation=None,
                    axesAdjust=True, axes=None):
    """ solidTeapot(
            translation=None, scaling=None, direction=None, rotation=None,
            axesAdjust=True, axes=None)
    
    Create a model of a teapot (a teapotahedron) with its bottom at the
    origin. Returns an OrientableMesh instance.
    
    Parameters
    ----------
    Note that translation, scaling, and direction can also be given
    using a Point instance.
    translation : (dx, dy, dz), optional
        The translation in world units of the created world object.
    scaling: (sx, sy, sz), optional
        The scaling in world units of the created world object.
    direction: (nx, ny, nz), optional
        Normal vector that indicates the direction of the created world object.
    rotation: scalar, optional
        The anle (in degrees) to rotate the created world object around its
        direction vector.
    axesAdjust : bool
        If True, this function will call axes.SetLimits(), and set
        the camera type to 3D. If daspectAuto has not been set yet, 
        it is set to False.
    axes : Axes instance
        Display the bars in the given axes, or the current axes if not given.
    
    """
    
    # Load mesh data
    bm = vv.meshRead('teapot.ssdf')
    
    # Use current axes?
    if axes is None:
        axes = vv.gca()
    
    # Create Mesh object
    m = vv.OrientableMesh(axes, bm)
    #
    if translation is not None:
        m.translation = translation
    if scaling is not None:
        m.scaling = scaling
    if direction is not None:
        m.direction = direction
    if rotation is not None:
        m.rotation = rotation
    
    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()
    
    # Done
    axes.Draw()
    return m
Пример #2
0
def loadmesh(basedirMesh,
             ptcode=None,
             meshname=None,
             invertZ=True,
             fname=None):
    """ Load Mesh object, flip z and return Mesh
    meshname includes ctcode
    """
    if fname is None:
        try:
            mesh = vv.meshRead(os.path.join(basedirMesh, ptcode, meshname))
        except FileNotFoundError:
            mesh = vv.meshRead(os.path.join(basedirMesh, meshname))
    else:
        try:
            mesh = vv.meshRead(os.path.join(basedirMesh, ptcode, fname))
        except FileNotFoundError:
            mesh = vv.meshRead(os.path.join(basedirMesh, fname))
    if invertZ == True:
        # z is negative, must be flipped to match dicom orientation CT data
        mesh._vertices[:, -1] *= -1
    return mesh
Пример #3
0
def points_from_mesh(mesh, invertZ=True):
    """ Create a point cloud (represented as a PointSet) from a visvis mesh
    object, or from a filename pointing to a .stl or .obj file.
    """
    if isinstance(mesh, str):
        mesh = vv.meshRead(mesh)
    if invertZ == True:
        for vertice in mesh._vertices:
            vertice[-1] = vertice[-1] * -1
    # Create set of tuples to remove duplicates
    pp = set(tuple(p) for p in mesh._vertices)
    # Turn into a pointset
    return PointSet(np.array(list(pp)))
Пример #4
0
    m = vv.Mesh(axes, vertices, faces, normals, values, verticesPerFace)

    # Set colormap or texture
    if values is not None and values.shape[1] == 1:
        if colormap is not None:
            m.colormap = colormap
        if clim is not None and len(clim) == 2:
            m.clim = clim
        else:
            m.clim = values.min(), values.max()
    elif texture is not None and values is not None and values.shape[1] == 2:
        m.SetTexture(texture)

    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()

    # Return
    axes.Draw()
    return m


if __name__ == '__main__':
    # Create BaseMesh object (has no visualization props)
    bm = vv.meshRead('teapot.ssdf')
    # Show it, returning a Mesh object (which does have visualization props)
    m = vv.mesh(bm)
Пример #5
0
    if not os.path.isfile(fname):
        # try loading from the resource dir
        path = vv.core.misc.getResourceDir()
        fname2 = os.path.join(path, fname)
        if os.path.isfile(fname2):
            fname = fname2
        else:
            raise IOError("Mesh file '%s' does not exist." % fname)

    # Use file extension to read file
    if fname.lower().endswith('.stl'):
        import visvis.vvio
        readFunc = visvis.vvio.stl.StlReader.read
    elif fname.lower().endswith('.obj'):
        import visvis.vvio
        readFunc = visvis.vvio.wavefront.WavefrontReader.read
    elif fname.lower().endswith('.ssdf') or fname.lower().endswith('.bsdf'):
        readFunc = ssdfRead
    else:
        raise ValueError('meshRead cannot determine file type.')

    # Read
    return readFunc(fname, check)


if __name__ == '__main__':
    # Create BaseMesh object (has no visualization props)
    bm = vv.meshRead('bunny.ssdf')
    # Show it, returning a Mesh object (which does have visualization props)
    m = vv.mesh(bm)
Пример #6
0
			vv.figure()
			ax1 = vv.subplot(121)
			ax2 = vv.subplot(122)
			t1 = vv.imshow(im, axes=ax1)
			t2 = vv.imshow(imgArray, axes=ax2)
			app = vv.use()
			app.Run()
			
			P = mcTSystem()
			P.fromBinaryArray(imgArrayT)
			P.doThinning(absT, relT)
			result = P.cellArray[::2,::2].astype(np.uint8)*255 + 255 - 255*imgArrayT
			Image.fromarray(result).show()
		elif ext.lower() in supportedMeshFormats:
			P = mcTSystem()
			bm = vv.meshRead(fileName)
			m = vv.mesh(bm)
			app = vv.use()
			app.Run()
			P.fromMesh(fileName, resolution)
			if absT is None:
				absT = 5 * max(P.shape) / 100
				relT = 0.5
			P.doThinning(absT, relT)
			tFileName = ''.join(os.path.splitext(fileName)[:-1] + ('-thinned.binvox'))
			tVoxelModel = binvox_rw.Voxels(
				data=P.cellArray[::2, ::2, ::2].astype(np.bool),
				dims=self.voxelModel.dims,
				translate=self.voxelModel.translate,
				scale=self.voxelModel.scale,
				axis_order=self.voxelModel.axis_order
Пример #7
0
      * The SSDF format (.ssdf or .bsdf) is the most efficient in terms
        of memory and speed, but is not widely available.
    
    """
    
    # Use file extension to read file
    if fname.lower().endswith('.stl'):
        writeFunc = vv.io.stl.StlWriter.write
    elif fname.lower().endswith('.obj'):
        writeFunc = vv.io.wavefront.WavefrontWriter.write
    elif fname.lower().endswith('.ssdf') or fname.lower().endswith('.bsdf'):
        writeFunc = ssdfWrite
    else:
        raise ValueError('meshWrite cannot determine file type.')
    
    # Read
    return writeFunc(fname, mesh, name, bin)


if __name__ == '__main__':
    
    bm = vv.meshRead('/home/almar/projects/teapot2.obj')
    fname = '/home/almar/projects/test.obj'
    meshWrite(fname, bm, bin=False)
    bm = vv.meshRead(fname)
    
    vv.figure(1); vv.clf()
    a = vv.subplot(121)
    m = vv.mesh(bm)
    #a.SetLimits()
    
Пример #8
0
def solidTeapot(translation=None,
                scaling=None,
                direction=None,
                rotation=None,
                axesAdjust=True,
                axes=None):
    """ solidTeapot(
            translation=None, scaling=None, direction=None, rotation=None,
            axesAdjust=True, axes=None)
    
    Create a model of a teapot (a teapotahedron) with its bottom at the
    origin. Returns an OrientableMesh instance.
    
    Parameters
    ----------
    Note that translation, scaling, and direction can also be given
    using a Point instance.
    translation : (dx, dy, dz), optional
        The translation in world units of the created world object.
    scaling: (sx, sy, sz), optional
        The scaling in world units of the created world object.
    direction: (nx, ny, nz), optional
        Normal vector that indicates the direction of the created world object.
    rotation: scalar, optional
        The anle (in degrees) to rotate the created world object around its
        direction vector.
    axesAdjust : bool
        If True, this function will call axes.SetLimits(), and set
        the camera type to 3D. If daspectAuto has not been set yet, 
        it is set to False.
    axes : Axes instance
        Display the bars in the given axes, or the current axes if not given.
    
    """

    # Load mesh data
    bm = vv.meshRead('teapot.ssdf')

    # Use current axes?
    if axes is None:
        axes = vv.gca()

    # Create Mesh object
    m = vv.OrientableMesh(axes, bm)
    #
    if translation is not None:
        m.translation = translation
    if scaling is not None:
        m.scaling = scaling
    if direction is not None:
        m.direction = direction
    if rotation is not None:
        m.rotation = rotation

    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()

    # Done
    axes.Draw()
    return m
Пример #9
0
# Load ssdf
s = loadvol(basedir, ptcode, ctcode, cropname, 'avgreg')
volavg = s.vol
origin = volavg.origin  # z y x

# Load deformations (apply forward for mesh)
s = loadvol(basedir, ptcode, ctcode, cropname, 'deforms')
deforms = [s['deform%i' % (i * 10)] for i in range(10)]
deforms = [[field[::2, ::2, ::2] for field in fields] for fields in deforms]
deforms_f = [pirt.DeformationFieldForward(*f) for f in deforms]

# Load mesh
basedir2 = select_dir(r'C:\MedData\LSPEAS_Mimics', r'F:\LSPEAS_Mimics_backup',
                      r'E:\LSPEAS_Mimics_backup')
mesh = vv.meshRead(os.path.join(basedir2, ptcode + '_' + ctcode, meshfile))
# z is negative, must be flipped to match dicom orientation
for vertice in mesh._vertices:
    vertice[-1] = vertice[-1] * -1
#mesh = vv.meshRead(r'D:\Profiles\koenradesma\Desktop\001_preavgreg 20150522 test itk.stl')
# x and y values of vertices are negative (as in original dicom), flip to match local coordinates
#mesh._vertices = mesh._vertices*-1  # when stl from itksnap

## Start vis
f = vv.figure(1)
vv.clf()
f.position = 8.00, 31.00, 944.00, 1001.00
a = vv.gca()
a.axis.axisColor = 1, 1, 1
a.axis.visible = False
a.bgcolor = 0, 0, 0
Пример #10
0
    m = vv.Mesh(axes, vertices, faces, normals, values, verticesPerFace)
    
    # Set colormap or texture
    if values is not None and values.shape[1] == 1:
        if colormap is not None:
            m.colormap = colormap
        if clim is not None and len(clim) == 2:
            m.clim = clim
        else:
            m.clim = values.min(), values.max()
    elif texture is not None and values is not None and values.shape[1] == 2:
        m.SetTexture(texture)
    
    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()
    
    # Return
    axes.Draw()
    return m


if __name__ == '__main__':
    # Create BaseMesh object (has no visualization props)
    bm = vv.meshRead('teapot.ssdf')
    # Show it, returning a Mesh object (which does have visualization props)
    m = vv.mesh(bm)
Пример #11
0
    
    Notes on formats
    ----------------
      * The STL format (.stl) is rather limited in the definition of the
        faces; smooth shading is not possible on an STL mesh.
      * The Wavefront format (.obj) is widely available.
      * The SSDF format (.ssdf or .bsdf) is the most efficient in terms
        of memory and speed, but is not widely available.
    
    """
    
    # Use file extension to read file
    if fname.lower().endswith('.stl'):
        import visvis.vvio
        writeFunc = vv.vvio.stl.StlWriter.write
    elif fname.lower().endswith('.obj'):
        import visvis.vvio
        writeFunc = vv.vvio.wavefront.WavefrontWriter.write
    elif fname.lower().endswith('.ssdf') or fname.lower().endswith('.bsdf'):
        writeFunc = ssdfWrite
    else:
        raise ValueError('meshWrite cannot determine file type.')
    
    # Read
    return writeFunc(fname, mesh, name, bin)


if __name__ == '__main__':
    bm = vv.meshRead('bunny.ssdf')
    vv.meshWrite('bunny.obj', bm)
Пример #12
0
def test_mesh_read_write():
    import visvis as vv
    m = vv.meshRead('bunny.ssdf')
    assert isinstance(m, vv.BaseMesh)
    vv.meshWrite(os.path.expanduser('~/bunny2.stl'), m)
Пример #13
0
        of memory and speed, but is not widely available.
    
    """

    # Use file extension to read file
    if fname.lower().endswith('.stl'):
        writeFunc = vv.io.stl.StlWriter.write
    elif fname.lower().endswith('.obj'):
        writeFunc = vv.io.wavefront.WavefrontWriter.write
    elif fname.lower().endswith('.ssdf') or fname.lower().endswith('.bsdf'):
        writeFunc = ssdfWrite
    else:
        raise ValueError('meshWrite cannot determine file type.')

    # Read
    return writeFunc(fname, mesh, name, bin)


if __name__ == '__main__':

    bm = vv.meshRead('/home/almar/projects/teapot2.obj')
    fname = '/home/almar/projects/test.obj'
    meshWrite(fname, bm, bin=False)
    bm = vv.meshRead(fname)

    vv.figure(1)
    vv.clf()
    a = vv.subplot(121)
    m = vv.mesh(bm)
    #a.SetLimits()