Example #1
0
def getReaderWriter(file_name, out_dir=None):
    r = vtk.vtkDataReader()
    r.SetFileName(file_name)
    f_base = os.path.splitext(file_name)[0]
    r.Update()
    reader = None
    writer = None
    xmlsuffix = '.xml'
    map = {'StructuredPoints': '.vti', 'StructuredGrid': '.vts',
           'RectilinearGrid': '.vtr', 'UnstructuredGrid': '.vtu',
           'PolyData': '.vtp'}
    for i in ['StructuredPoints', 'StructuredGrid', 'RectilinearGrid',
              'UnstructuredGrid', 'PolyData']:
        if eval('r.IsFile%s()'%i):
            reader = eval('vtk.vtk%sReader()'%i)
            if i == 'StructuredPoints':
                writer = eval('vtk.vtkXMLImageDataWriter()')
            else:
                writer = eval('vtk.vtkXML%sWriter()'%i)
            xmlsuffix = map[i]
            break
    if not reader:
        return None, None
    
    reader.SetFileName(file_name)
    reader.Update()

    out_file = f_base + xmlsuffix
    if out_dir:
        out_file = os.path.join(out_dir,
                                os.path.basename(f_base) + xmlsuffix)
    writer.SetFileName(out_file)
    return reader, writer
 def read_vtk(self, to_polydata=False):
     # Read the source file.
     reader = vtk.vtkDataReader()
     reader.SetFileName('.'.join([self.filename, self.input_type]))
     reader.Update()
     print('Case ID : {}, input type: {}'.format(self.filename,
                                                 self.input_type))
     if reader.IsFileUnstructuredGrid():
         print('Reading Unstructured Grid...')
         reader = vtk.vtkUnstructuredGridReader()
     elif reader.IsFilePolyData():
         print('Reading Polygonal Mesh...')
         reader = vtk.vtkPolyDataReader()
     elif reader.IsFileStructuredGrid():
         print('Reading Structured Grid...')
         reader = vtk.vtkStructuredGridReader()
     elif reader.IsFileStructuredPoints():
         print('Reading Structured Points...')
         reader = vtk.vtkStructuredPointsReader()
     elif reader.IsFileRectilinearGrid():
         print('Reading Rectilinear Grid...')
         reader = vtk.vtkRectilinearGridReader()
     else:
         print('Data format unknown...')
     reader.SetFileName(self.filename + '.' + self.input_type)
     reader.Update()  # Needed because of GetScalarRange
     scalar_range = reader.GetOutput().GetScalarRange()
     if to_polydata and not reader.IsFilePolyData():
         print('Transform to Polygonal Mesh')
         reader = self.unstructured_grid_to_poly_data(reader)
     print('Scalar range: \n{}'.format(scalar_range))
     return reader, scalar_range
Example #3
0
    def can_load(self):
        generic_reader = vtkDataReader()
        generic_reader.GlobalWarningDisplayOff()
        generic_reader.SetFileName(self.filename)

        return (generic_reader.OpenVTKFile() and generic_reader.ReadHeader()
                and generic_reader.IsFileStructuredPoints()
                and generic_reader.GetNumberOfTensorsInFile() > 0)
Example #4
0
def readvtk_single(infile):
    """
    read an arbitrary vtk/vtkXML file to a dictionary containing its data
    """
    xml_checker = vtkXMLFileReadTester()
    xml_checker.SetFileName(infile)
    is_xml = bool(xml_checker.TestReadFile())
    if is_xml:
        # check for vtk-XML-type
        xml_type = xml_checker.GetFileDataType()
        if xml_type in XMLreader_dict:
            reader = XMLreader_dict[xml_type]
        else:
            print(infile + ": XML file not valid (Type '" + str(xml_type) +
                  "')")
            if xml_type == "Collection":
                print("...try the 'readpvd' function")
            return {}
    else:
        # check for vtk-type
        checker = vtkDataReader()
        checker.SetFileName(infile)
        # get the right reader depending on the datasettype
        reader_found = False
        for datasettype in vtkreader_dict:
            if checker.IsFileValid(datasettype):
                reader = vtkreader_dict[datasettype]
                reader_found = True
                break
        if not reader_found:
            print(infile + ": vtk file not valid")
            checker.CloseVTKFile()
            return {}
        checker.CloseVTKFile()

    # read in the vtk object
    vtk_reader = reader[0]()
    vtk_reader.SetFileName(infile)
    if not is_xml:
        # https://stackoverflow.com/a/35018175/6696397
        vtk_reader.ReadAllScalarsOn()
        vtk_reader.ReadAllVectorsOn()
        vtk_reader.ReadAllNormalsOn()
        vtk_reader.ReadAllTensorsOn()
        vtk_reader.ReadAllColorScalarsOn()
        vtk_reader.ReadAllTCoordsOn()
        vtk_reader.ReadAllFieldsOn()
    vtk_reader.Update()
    file_obj = vtk_reader.GetOutput()

    # convert vtk object to a dictionary of numpy arrays
    output = reader[1](file_obj)
    if not is_xml:
        output["header"] = vtk_reader.GetHeader()
    else:
        output["header"] = "vtk-XML file"

    return output
Example #5
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()
Example #6
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()
Example #7
0
    def load_object_3d(self, path, viewer_3d):
        generic_reader = vtkDataReader()
        generic_reader.SetFileName(path)

        if generic_reader.OpenVTKFile() and generic_reader.ReadHeader():
            if generic_reader.IsFileStructuredPoints():
                raise Exception("Cannot read VTK structured points")
            elif generic_reader.IsFilePolyData():
                reader = vtkPolyDataReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            elif generic_reader.IsFileStructuredGrid():
                reader = vtkStructuredGridReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            elif generic_reader.IsFileUnstructuredGrid():
                reader = vtkUnstructuredGridReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            elif generic_reader.IsFileRectilinearGrid():
                reader = vtkRectilinearGridReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            else:
                raise Exception("Cannot read VTK file containing type %i" %
                                generic_reader.GetFileType())
            viewer_3d.objects_3d.append(object_3d)
        else:
            importer = vtkVRMLImporter()
            importer.SetFileName(path)
            importer.Update()
            actors = importer.GetRenderer().GetActors()
            number_of_actors = actors.GetNumberOfItems()
            actors.InitTraversal()
            for i in range(number_of_actors):
                actor = actors.GetNextItem()
                object_3d = Object3D(path + ", %i" % i)
                object_3d.actor.SetProperty(actor.GetProperty())
                object_3d.actor.SetMapper(actor.GetMapper())
                viewer_3d.objects_3d.append(object_3d)
 def importFile(self, filename):
     pipeline = []
     pipeline.append(vtk.vtkDataReader())
     pipeline[0].SetFileName(filename)
     pipeline[0].SetMerging(1)
     return vtk2Blend(pipeline[0].GetOutput(), None)