Exemplo n.º 1
0
def loadPolyData(filename):
    '''Load a file and return a vtkPolyData object (not a vtkActor).'''
    if not os.path.exists(filename):
        colors.printc('Error in loadPolyData: Cannot find', filename, c=1)
        return None
    fl = filename.lower()
    if fl.endswith('.vtk') or fl.endswith('.vtp'):
        reader = vtk.vtkPolyDataReader()
    elif fl.endswith('.ply'):
        reader = vtk.vtkPLYReader()
    elif fl.endswith('.obj'):
        reader = vtk.vtkOBJReader()
    elif fl.endswith('.stl'):
        reader = vtk.vtkSTLReader()
    elif fl.endswith('.byu') or fl.endswith('.g'):
        reader = vtk.vtkBYUReader()
    elif fl.endswith('.vtp'):
        reader = vtk.vtkXMLPolyDataReader()
    elif fl.endswith('.vts'):
        reader = vtk.vtkXMLStructuredGridReader()
    elif fl.endswith('.vtu'):
        reader = vtk.vtkXMLUnstructuredGridReader()
    elif fl.endswith('.txt'):
        reader = vtk.vtkParticleReader()  # (x y z scalar)
    elif fl.endswith('.xyz'):
        reader = vtk.vtkParticleReader()
    else:
        reader = vtk.vtkDataReader()
    reader.SetFileName(filename)
    if fl.endswith('.vts'):  # structured grid
        reader.Update()
        gf = vtk.vtkStructuredGridGeometryFilter()
        gf.SetInputConnection(reader.GetOutputPort())
        gf.Update()
        poly = gf.GetOutput()
    elif fl.endswith('.vtu'):  # unstructured grid
        reader.Update()
        gf = vtk.vtkGeometryFilter()
        gf.SetInputConnection(reader.GetOutputPort())
        gf.Update()
        poly = gf.GetOutput()
    else:
        try:
            reader.Update()
            poly = reader.GetOutput()
        except:
            poly = None

    if not poly:
        return None

    cleanpd = vtk.vtkCleanPolyData()
    cleanpd.SetInputData(poly)
    cleanpd.Update()
    return cleanpd.GetOutput()
Exemplo n.º 2
0
def main():
    filename = get_program_parameters()

    # Particles.raw supplied by VTK is big endian encoded
    # Read the file
    reader = vtk.vtkParticleReader()

    reader.SetFileName(filename)
    # if nothing gets displayed or totally wrong, swap the endianness
    reader.SetDataByteOrderToBigEndian()
    reader.Update()

    # Visualize
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(reader.GetOutputPort())
    print("number of pieces:", mapper.GetNumberOfPieces())
    mapper.SetScalarRange(4, 9)

    actor = vtk.vtkActor()

    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(4)

    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)
    renderer.AddActor(actor)

    named_colors = vtk.vtkNamedColors()
    renderer.SetBackground(named_colors.GetColor3d("Azure"))

    render_window.Render()
    render_window_interactor.Start()
Exemplo n.º 3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkParticleReader(), 'Reading vtkParticle.',
         (), ('vtkParticle',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 4
0
def loadPoly(filename):
    '''Return a vtkPolyData object, NOT a vtkActor'''
    if not os.path.exists(filename):
        vc.printc(('Error in loadPoly: Cannot find', filename), c=1)
        return None
    fl = filename.lower()
    if '.vtk' in fl: reader = vtk.vtkPolyDataReader()
    elif '.ply' in fl: reader = vtk.vtkPLYReader()
    elif '.obj' in fl: reader = vtk.vtkOBJReader()
    elif '.stl' in fl: reader = vtk.vtkSTLReader()
    elif '.byu' in fl or '.g' in fl: reader = vtk.vtkBYUReader()
    elif '.vtp' in fl: reader = vtk.vtkXMLPolyDataReader()
    elif '.vts' in fl: reader = vtk.vtkXMLStructuredGridReader()
    elif '.vtu' in fl: reader = vtk.vtkXMLUnstructuredGridReader()
    elif '.txt' in fl: reader = vtk.vtkParticleReader()  # (x y z scalar)
    elif '.xyz' in fl: reader = vtk.vtkParticleReader()
    else: reader = vtk.vtkDataReader()
    reader.SetFileName(filename)
    reader.Update()
    if '.vts' in fl:  # structured grid
        gf = vtk.vtkStructuredGridGeometryFilter()
        gf.SetInputConnection(reader.GetOutputPort())
        gf.Update()
        poly = gf.GetOutput()
    elif '.vtu' in fl:  # unstructured grid
        gf = vtk.vtkGeometryFilter()
        gf.SetInputConnection(reader.GetOutputPort())
        gf.Update()
        poly = gf.GetOutput()
    else:
        poly = reader.GetOutput()

    if not poly:
        vc.printc(('Unable to load', filename), c=1)
        return False

    cleanpd = vtk.vtkCleanPolyData()
    vu.setInput(cleanpd, poly)
    cleanpd.Update()
    return cleanpd.GetOutput()
Exemplo n.º 5
0
def _load_file(filename, c, alpha, threshold, spacing, unpack):
    fl = filename.lower()

    ################################################################# other formats:
    if fl.endswith(".xml") or fl.endswith(".xml.gz") or fl.endswith(".xdmf"):
        # Fenics tetrahedral file
        actor = loadDolfin(filename)
    elif fl.endswith(".neutral") or fl.endswith(".neu"):  # neutral tetrahedral file
        actor = loadNeutral(filename)
    elif fl.endswith(".gmsh"):  # gmesh file
        actor = loadGmesh(filename)
    elif fl.endswith(".pcd"):  # PCL point-cloud format
        actor = loadPCD(filename)
        actor.GetProperty().SetPointSize(2)
    elif fl.endswith(".off"):
        actor = loadOFF(filename)
    elif fl.endswith(".3ds"):  # 3ds format
        actor = load3DS(filename)
    elif fl.endswith(".wrl"):
        importer = vtk.vtkVRMLImporter()
        importer.SetFileName(filename)
        importer.Read()
        importer.Update()
        actors = importer.GetRenderer().GetActors() #vtkActorCollection
        actors.InitTraversal()
        wacts = []
        for i in range(actors.GetNumberOfItems()):
            act = actors.GetNextActor()
            wacts.append(act)
        actor = Assembly(wacts)

        ################################################################# volumetric:
    elif fl.endswith(".tif") or fl.endswith(".slc") or fl.endswith(".vti") \
        or fl.endswith(".mhd") or fl.endswith(".nrrd") or fl.endswith(".nii") \
        or fl.endswith(".dem"):
        img = loadImageData(filename, spacing)
        if threshold is False:
            if c is None and alpha == 1:
                c = ['b','lb','lg','y','r'] # good for blackboard background
                alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1)
            actor = Volume(img, c, alpha)
        else:
            actor = Volume(img).isosurface(threshold=threshold)
            actor.color(c).alpha(alpha)

        ################################################################# 2D images:
    elif fl.endswith(".png") or fl.endswith(".jpg") or fl.endswith(".bmp") or fl.endswith(".jpeg"):
        if ".png" in fl:
            picr = vtk.vtkPNGReader()
        elif ".jpg" in fl or ".jpeg" in fl:
            picr = vtk.vtkJPEGReader()
        elif ".bmp" in fl:
            picr = vtk.vtkBMPReader()
        picr.SetFileName(filename)
        picr.Update()
        actor = Picture()  # object derived from vtk.vtkImageActor()
        actor.SetInputData(picr.GetOutput())
        if alpha is None:
            alpha = 1
        actor.SetOpacity(alpha)

        ################################################################# multiblock:
    elif fl.endswith(".vtm") or fl.endswith(".vtmb"):
        read = vtk.vtkXMLMultiBlockDataReader()
        read.SetFileName(filename)
        read.Update()
        mb = read.GetOutput()
        if unpack:
            acts = []
            for i in range(mb.GetNumberOfBlocks()):
                b =  mb.GetBlock(i)
                if isinstance(b, (vtk.vtkPolyData,
                                  vtk.vtkImageData,
                                  vtk.vtkUnstructuredGrid,
                                  vtk.vtkStructuredGrid,
                                  vtk.vtkRectilinearGrid)):
                    acts.append(b)
            return acts
        else:
            return mb

        ################################################################# numpy:
    elif fl.endswith(".npy"):
        acts = loadNumpy(filename)
        if unpack == False:
            return Assembly(acts)
        return acts

    elif fl.endswith(".geojson") or fl.endswith(".geojson.gz"):
        return loadGeoJSON(fl)

        ################################################################# polygonal mesh:
    else:
        if fl.endswith(".vtk"): # read all legacy vtk types

            #output can be:
            # PolyData, StructuredGrid, StructuredPoints, UnstructuredGrid, RectilinearGrid
            reader = vtk.vtkDataSetReader()
            reader.ReadAllScalarsOn()
            reader.ReadAllVectorsOn()
            reader.ReadAllTensorsOn()
            reader.ReadAllFieldsOn()
            reader.ReadAllNormalsOn()
            reader.ReadAllColorScalarsOn()

        elif fl.endswith(".ply"):
            reader = vtk.vtkPLYReader()
        elif fl.endswith(".obj"):
            reader = vtk.vtkOBJReader()
        elif fl.endswith(".stl"):
            reader = vtk.vtkSTLReader()
        elif fl.endswith(".byu") or fl.endswith(".g"):
            reader = vtk.vtkBYUReader()
        elif fl.endswith(".foam"):  # OpenFoam
            reader = vtk.vtkOpenFOAMReader()
        elif fl.endswith(".pvd"):
            reader = vtk.vtkXMLGenericDataObjectReader()
        elif fl.endswith(".vtp"):
            reader = vtk.vtkXMLPolyDataReader()
        elif fl.endswith(".vts"):
            reader = vtk.vtkXMLStructuredGridReader()
        elif fl.endswith(".vtu"):
            reader = vtk.vtkXMLUnstructuredGridReader()
        elif fl.endswith(".vtr"):
            reader = vtk.vtkXMLRectilinearGridReader()
        elif fl.endswith(".pvtk"):
            reader = vtk.vtkPDataSetReader()
        elif fl.endswith(".pvtr"):
            reader = vtk.vtkXMLPRectilinearGridReader()
        elif fl.endswith("pvtu"):
            reader = vtk.vtkXMLPUnstructuredGridReader()
        elif fl.endswith(".txt") or fl.endswith(".xyz"):
            reader = vtk.vtkParticleReader()  # (format is x, y, z, scalar)
        elif fl.endswith(".facet"):
            reader = vtk.vtkFacetReader()
        else:
            return None

        reader.SetFileName(filename)
        reader.Update()
        routput = reader.GetOutput()

        if not routput:
            colors.printc("~noentry Unable to load", filename, c=1)
            return None

        actor = Actor(routput, c, alpha)
        if fl.endswith(".txt") or fl.endswith(".xyz"):
            actor.GetProperty().SetPointSize(4)

    actor.filename = filename
    return actor
Exemplo n.º 6
0
# tex = "D:\\images.jpg"
# readertex = vtk.vtkJPEGReader()
# readertex.SetFileName(tex)
# texture = vtk.vtkTexture()
# texture.SetInputConnection(readertex.GetOutputPort())
############################################################

# readers
readerSTL = vtk.vtkSTLReader()
readerSTL.SetFileName(filenameBoat)
# reader.Update()

readerWSTL = vtk.vtkSTLReader()
readerWSTL.SetFileName(filenameWaterSTL)

readerP = vtk.vtkParticleReader()
readerP.SetFileName(filenameWater)  # filenameWater #filenameCover
readerP.SetDataByteOrderToBigEndian()
readerP.Update()

# mappers
mapperSTL = vtk.vtkPolyDataMapper()
mapperSTL.SetInputConnection(readerSTL.GetOutputPort())

mapperWSTL = vtk.vtkPolyDataMapper()
mapperWSTL.SetInputConnection(readerWSTL.GetOutputPort())

mapperP = vtk.vtkPolyDataMapper()
mapperP.SetInputConnection(readerP.GetOutputPort())
mapperP.SetScalarRange(0.0, 999.9)  # (0.0, 999.9) #(0.1, 1.0)
Exemplo n.º 7
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
reader = vtk.vtkParticleReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/Particles.raw")
reader.SetDataByteOrderToBigEndian()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(reader.GetOutputPort())
mapper.SetScalarRange(4,9)
mapper.SetPiece(1)
mapper.SetNumberOfPieces(2)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetPointSize(2.5)
# Add the actors to the renderer, set the background and size
#
ren1.AddActor(actor)
ren1.SetBackground(0,0,0)
renWin.SetSize(200,200)
# Get handles to some useful objects
#
Exemplo n.º 8
0
__license__ = "BSD <http://opensource.org/licenses/bsd-license.php>"

from glob import glob
from optparse import OptionParser
from os import name, path
from vtk import vtkParticleReader, vtkXMLPolyDataWriter

def get_filenames():
    """Return a list of filenames to process."""
    parser = OptionParser(usage='%prog INPUT_FILES',
                          description=' '.join(__doc__.split()),
                          version=__version__)
    (opts, args) = parser.parse_args()
    if name == 'nt':
        args = glob(args[0])
    return args


if __name__ == '__main__':
    for in_filename in get_filenames():
        out_filename = '.'.join([path.splitext(path.split(in_filename)[-1])[0],
                                'vtp'])
        reader = vtkParticleReader()
        reader.SetFileName(in_filename)
        
        writer = vtkXMLPolyDataWriter()
        writer.SetFileName(out_filename)
        writer.SetInputConnection(reader.GetOutputPort())
        writer.Write()
        print "Saved file: %s" % out_filename