def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkGenericDataObjectWriter(), 'Writing vtkGenericDataObject.', ('vtkGenericDataObject',), (), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def LabelToSurface(label_path, surface_path, lcc=False, smoothIterations=15,relaxationFactor=0.1): tqdm.write("Converting segmentation label to surface file: {}".format(label_path)) # binary path if platform == "linux" or platform == "linux2": bin_path = "/home/jacky/Projects/CFD_intraranial/cxx/label_to_mesh/build_linux/LabelToMesh" elif platform == "darwin": return elif platform == "win32": bin_path = "D:/projects/CFD_intracranial/cxx/label_to_mesh/build/Release/LabelToMesh.exe" # convert to binary file command = bin_path + " " + label_path + " " + surface_path + " 1 1" # print(command) os.system(command) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(surface_path) reader.Update() surface = reader.GetOutput() transform = vtk.vtkTransform() transform.Scale(-1,-1,1) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(surface) transformFilter.SetTransform(transform) transformFilter.Update() surface = transformFilter.GetOutput() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(surface) smoothFilter.SetNumberOfIterations(smoothIterations); smoothFilter.SetRelaxationFactor(relaxationFactor); smoothFilter.FeatureEdgeSmoothingOff(); smoothFilter.BoundarySmoothingOn(); smoothFilter.Update(); surface = smoothFilter.GetOutput() if lcc: connectedFilter = vtk.vtkConnectivityFilter() connectedFilter.SetInputData(surface) connectedFilter.Update() surface = connectedFilter.GetOutput() if pathlib.Path(surface_path).suffix == ".vtk": writer = vtk.vtkGenericDataObjectWriter() elif pathlib.Path(surface_path).suffix == ".vtp": writer = vtk.vtkXMLPolyDataWriter() elif pathlib.Path(surface_path).suffix == ".stl": writer = vtk.vtkSTLWriter() writer.SetFileName(surface_path) writer.SetInputData(surface) writer.Update() tqdm.write("Convert segmentation label to surface file complete: {}".format(label_path))
def LabelToSurface(label_path, surface_path, lcc=False): print("Converting segmentation label to surface file:", label_path) # binary path bin_path = "D:/Dr_Simon_Yu/CFD_intracranial/code/cxx/label_to_mesh/build/Release/LabelToMesh.exe" # convert to binary file command = bin_path + " " + label_path + " " + surface_path + " 1 1" # print(command) os.system(command) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(surface_path) reader.Update() surface = reader.GetOutput() transform = vtk.vtkTransform() transform.Scale(-1, -1, 1) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(surface) transformFilter.SetTransform(transform) transformFilter.Update() surface = transformFilter.GetOutput() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(surface) smoothFilter.SetNumberOfIterations(15) smoothFilter.SetRelaxationFactor(0.1) smoothFilter.FeatureEdgeSmoothingOff() smoothFilter.BoundarySmoothingOn() smoothFilter.Update() surface = smoothFilter.GetOutput() if lcc: connectedFilter = vtk.vtkConnectivityFilter() connectedFilter.SetInputData(surface) connectedFilter.Update() surface = connectedFilter.GetOutput() writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(surface_path) writer.SetInputData(surface) writer.Update()
def write_vtk_to_file(filename, vtkdata): """ Write VTK file. Parameters ---------- filename : str Name of the VTK file. vtkdata : VTK object Mesh, scalar, vector and tensor data. """ writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(filename) if vtk_version < 6: writer.SetInput(vtkdata) else: writer.SetInputData(vtkdata) writer.Update()
u = bgridreader.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(u) GeomFilt2.Update() y = GeomFilt2.GetOutput() append = vtk.vtkAppendPolyData() append.AddInput(x) append.AddInput(y) data = append.GetOutput() d = vtk.vtkDelaunay3D() d.SetInput(data) d.Update d.BoundingTriangulationOff() d.SetTolerance(0.01) d.SetAlpha(0) d.Update() z = d.GetOutput() return z if __name__ == '__main__': z = Create_topo() writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName("test31.vtu") writer.SetInput(z) writer.Update() writer.Write()
def Extrude(Slope,Extrusion,Plane,Model,Sediment,Start_time,End_time,Time_step,Mesh): ugrid1 = vtk.vtkUnstructuredGrid() #1.import sloped sediment and change to polydata gridreader1=vtk.vtkUnstructuredGridReader() gridreader1.SetFileName(Slope) #.pvd gridreader1.Update() ugrid1 = gridreader1.GetOutput() GeomFilt1 = vtk.vtkGeometryFilter() GeomFilt1.SetInput(ugrid1) GeomFilt1.Update() y1 = GeomFilt1.GetOutput() Extrude = vtk.vtkLinearExtrusionFilter() #2. extrude the polydata and save it again as polydata Extrude.SetInput(y1) Extrude.SetExtrusionTypeToVectorExtrusion() Extrude.SetVector(0,0,-1) PreliminaryExtrusion = Extrude.GetOutput() PE = vtk.vtkPolyData() PE = PreliminaryExtrusion PE.Update() ugrid2 = vtk.vtkUnstructuredGrid() #3. import in the top surface of the sediment below gridreader2=vtk.vtkXMLUnstructuredGridReader() gridreader2.SetFileName(Plane) # 000000.vtu gridreader2.Update() ugrid2 = gridreader2.GetOutput() ExtrudedPoints = PE.GetPoints() #4. take points from the extruded polydata PlanePoints = ugrid2.GetPoints() #5. get points from surface below nPoints = PE.GetNumberOfPoints() #6. for first half of points determine if above or below last surface Begin = nPoints/2 #7. if below set as the same as bottom surface (slightly above?) #8. set second half counter = 0 uPoints = ugrid2.GetPoints() for p in range(Begin,nPoints): y = uPoints.GetPoint(counter)[2:] x = ExtrudedPoints.GetPoint(p)[:2] + y ExtrudedPoints.SetPoint(p,x) counter += 1 PE.Update() writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(Model) writer.SetInput(PE) writer.Update() writer.Write() ################################################################################################################# t = Start_time dt = Time_step ET = End_time et = ET-1 Save = Sediment + str(t) +'000000.vtu' Import = Sediment + str(t)+ '_sed_slope.pvd' NewSave = Sediment + str(t)+ 'extruded_sed_slope.pvd' SedimentGrid1 = vtk.vtkUnstructuredGrid() #1.import sloped sediment and change to polydata SedimentGridreader1=vtk.vtkUnstructuredGridReader() SedimentGridreader1.SetFileName(Import) #.pvd SedimentGridreader1.Update() SedimentGrid1 = SedimentGridreader1.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(SedimentGrid1) GeomFilt2.Update() ExtrudeInput1 = GeomFilt2.GetOutput() ExtrudeSed1 = vtk.vtkLinearExtrusionFilter() #2. extrude the polydata and save it again as polydata ExtrudeSed1.SetInput(ExtrudeInput1) ExtrudeSed1.SetExtrusionTypeToVectorExtrusion() ExtrudeSed1.SetVector(0,0,-1) PreliminarySedExtrusion1 = ExtrudeSed1.GetOutput() PSE1 = vtk.vtkPolyData() PSE1 = PreliminarySedExtrusion1 PSE1.Update() PreSurface1 = vtk.vtkUnstructuredGrid() #3. import in the top surface of the sediment below PSreader1=vtk.vtkGenericDataObjectReader() PSreader1.SetFileName(Slope) # 000000.vtu PSreader1.Update() PreSurface1 = PSreader1.GetOutput() ExtrudedSedPoints1 = PSE1.GetPoints() #4. take points from the extruded polydata PSPoints1 = PreSurface1.GetPoints() #5. get points from surface below SedPoints1 = PSE1.GetNumberOfPoints() #6. for first half of points determine if above or below last surface BeginSed1 = nPoints/2 EndSed1 = BeginSed1 - 1 #7. if below set as the same as bottom surface (slightly above? sedcounter1 = 0 #8. set second half sedcounter2 = BeginSed1 for p in range(BeginSed1,SedPoints1): y = PSPoints1.GetPoint(sedcounter1)[2:] x = ExtrudedSedPoints1.GetPoint(p)[:2] + y ExtrudedSedPoints1.SetPoint(p,x) sedcounter1 += 1 writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(NewSave) writer.SetInput(PSE1) writer.Update() writer.Write() ##################################################################################################################### while t <= et: t += dt pre = t -1 Previous = Sediment +str(pre) + '_sed_slope.pvd' PreviousSave = Sediment + str(pre)+ 'extruded_sed_slope.pvd' Import = Sediment + str(t)+ '_sed_slope.pvd' NewSave = Sediment + str(t)+ 'extruded_sed_slope.pvd' SedimentGrid2 = vtk.vtkUnstructuredGrid() SedimentGridreader2=vtk.vtkUnstructuredGridReader() SedimentGridreader2.SetFileName(Import) #.pvd SedimentGridreader2.Update() SedimentGrid2 = SedimentGridreader2.GetOutput() GeomFilt3 = vtk.vtkGeometryFilter() GeomFilt3.SetInput(SedimentGrid2) GeomFilt3.Update() ExtrudeInput = GeomFilt3.GetOutput() ExtrudeInput2 = GeomFilt3.GetOutput() ExtrudeSed2 = vtk.vtkLinearExtrusionFilter() ExtrudeSed2.SetInput(ExtrudeInput2) ExtrudeSed2.SetExtrusionTypeToVectorExtrusion() ExtrudeSed2.SetVector(0,0,-1) PreliminarySedExtrusion2 = ExtrudeSed2.GetOutput() PSE2 = vtk.vtkPolyData() PSE2 = PreliminarySedExtrusion2 PSE2.Update() PreSurface2 = vtk.vtkUnstructuredGrid() PSreader2=vtk.vtkGenericDataObjectReader() PSreader2.SetFileName(PreviousSave) # 000000.vtu PSreader2.Update() PreSurface2 = PSreader2.GetOutput() Append = vtk.vtkAppendPolyData() Append.AddInput(PreSurface2) Append.AddInput(PSE2) DD = Append.GetOutput() DD.Update() ExtrudedSedPoints = PSE2.GetPoints() PSPoints = PreSurface2.GetPoints() SedPoints = PSE2.GetNumberOfPoints() BeginSed = nPoints/2 EndSed = BeginSed - 1 sedcounter3 = 0 sedcounter4 = BeginSed Data = DD.GetPoints() mesh = Mesh m = (mesh+1)**2 c = t while c != 0: c = (c -1) e = int((c*m)*2) ee = int(e + m) for p in range(e,ee): A = Data.GetPoint(p+(2*m))[2:] #New sediment height B = Data.GetPoint(p)[2:] # old sediment height C = Data.GetPoint(p+m)[2:] # old sediment bottom if A < B: #If new sediment height is less than old sediment height y = (Data.GetPoint(p)[:2] + Data.GetPoint(p+(2*m))[2:]) Data.SetPoint(p,y) if A < C: x = Data.GetPoint(p+m)[:2] + Data.GetPoint(p)[2:] Data.SetPoint((p+m),x) f = int((t*m)*2+m) ff = int(f + m) for p in range(f,ff): y = Data.GetPoint((p-3*m))[2:] x = Data.GetPoint(p)[:2] + y Data.SetPoint(p,x) writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(NewSave) writer.SetInput(DD) writer.Update() writer.Write()
def apply_filters(fname, df, sf, surf_type): """Apply the decimation and smoothing filters using the VTK library and the user specified refinement factors. Decimation uses the vtkDecimatePro method. Smoothing uses the vtkWindowSincPolyDataFilter method. Both refinement processes maintain boundary vertices and topology. If both filters are applied, smoothing will be applied first. Input: ------ fname: string, name of the surface vtk file that will be refined df: float or None, factor for target reduction in the decimation process. Must be between 0 and 1. If set to None, no decimation will be applied. A higher value indicates a greater reduction in the number of surface triangles. sf: float or None, smoothing factor for the smoothing process. Must be between 0 and 1. If set to None, no smoothing will be applied. A higher value indicates more smoothing. surf_type: str, 'interior' or 'exterior', used to indicate if the surface being refined is an interior or exterior surface. Only interior surfaces will have smoothing applied if smoothing is requested. Return: ------- outfile: string, name of the output file from VTK after refinement """ # read in surface w/ vtk as an unstructured grid usg = vtk.vtkUnstructuredGridReader() usg.SetFileName(fname) usg.Update() usgport = usg.GetOutputPort() # convert USG to polydata gf = vtk.vtkGeometryFilter() gf.SetInputConnection(usgport) gf.Update() pdport = gf.GetOutputPort() # only apply smoothing filter to interior surfaces to avoid smoothing # the corners of the geometry if sf is not None and surf_type == 'interior': smoothfilter = vtk.vtkWindowedSincPolyDataFilter() smoothfilter.SetInputConnection(pdport) smoothfilter.SetNumberOfIterations(20) smoothfilter.BoundarySmoothingOff # don't apply to boundaries smoothfilter.NonManifoldSmoothingOff() # don't collapse topology/vols smoothfilter.Update() pdport = smoothfilter.GetOutputPort() if df is not None: # setup decimate operator decifilter = vtk.vtkDecimatePro() decifilter.SetInputConnection(pdport) # set decimate options decifilter.SetTargetReduction(df) # target reduction # preserve topology (splitting or hole elimination not allowed) decifilter.SetPreserveTopology(True) decifilter.SetSplitting(False) # no mesh splitting allowed # no boundary vertex (edge/curve) deletion allowed decifilter.SetBoundaryVertexDeletion(False) decifilter.Update() pdport = decifilter.GetOutputPort() # convert polydata back to USG appendfilter = vtk.vtkAppendFilter() appendfilter.SetInputConnection(pdport) appendfilter.Update() usg_new = vtk.vtkUnstructuredGrid() usg_new.ShallowCopy(appendfilter.GetOutput()) outfile = fname.split('.')[0] + '_refined.vtk' writer1 = vtk.vtkGenericDataObjectWriter() writer1.SetFileName(outfile) writer1.SetInputData(usg_new) writer1.Update() writer1.Write() return outfile
def write_data_to_vtk(self, filename, datasets, volume_normalization=True): """Map data to the unstructured mesh element centroids to create a VTK point-cloud dataset. Parameters ---------- filename : str Name of the VTK file to write. datasets : dict Dictionary whose keys are the data labels and values are the data sets. volume_normalization : bool Whether or not to normalize the data by the volume of the mesh elements """ import vtk from vtk.util import numpy_support as vtk_npsup if self.centroids is None: raise RuntimeError("No centroid information is present on this " "unstructured mesh. Please load this " "information from a relevant statepoint file.") if self.volumes is None and volume_normalization: raise RuntimeError("No volume data is present on this " "unstructured mesh. Please load the " " mesh information from a statepoint file.") # check that the data sets are appropriately sized for label, dataset in datasets.items(): if isinstance(dataset, np.ndarray): assert dataset.size == self.n_elements else: assert len(dataset) == self.n_elements cv.check_type('label', label, str) # create data arrays for the cells/points cell_dim = 1 vertices = vtk.vtkCellArray() points = vtk.vtkPoints() for centroid in self.centroids: # create a point for each centroid point_id = points.InsertNextPoint(centroid) # create a cell of type "Vertex" for each point cell_id = vertices.InsertNextCell(cell_dim, (point_id, )) # create a VTK data object poly_data = vtk.vtkPolyData() poly_data.SetPoints(points) poly_data.SetVerts(vertices) # strange VTK nuance: # data must be held in some container # until the vtk file is written data_holder = [] # create VTK arrays for each of # the data sets for label, dataset in datasets.items(): dataset = np.asarray(dataset).flatten() if volume_normalization: dataset /= self.volumes.flatten() array = vtk.vtkDoubleArray() array.SetName(label) array.SetNumberOfComponents(1) array.SetArray(vtk_npsup.numpy_to_vtk(dataset), dataset.size, True) data_holder.append(dataset) poly_data.GetPointData().AddArray(array) # set filename if not filename.endswith(".vtk"): filename += ".vtk" writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(filename) writer.SetInputData(poly_data) writer.Write()
reader = vtk.vtkStructuredPointsReader() reader.SetFileName("fMag.0001.vtk") reader.Update() vtk_data = reader.GetOutput() scalar_data = numpy_support.vtk_to_numpy(vtk_data.GetPointData().GetScalars()) mesh_shape = vtk_data.GetDimensions() origin = vtk_data.GetOrigin() spacing = vtk_data.GetSpacing() scalar_data_vtk = numpy_support.numpy_to_vtk(scalar_data) scalar_data_vtk.SetName('fMag') vtk_obj = vtk.vtkStructuredPoints() vtk_obj.SetDimensions(mesh_shape) vtk_obj.SetOrigin(origin) vtk_obj.SetSpacing(spacing) vtk_obj.GetPointData().SetScalars(scalar_data_vtk) writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName("test_out.vtk") writer.SetInputDataObject(vtk_obj) writer.Update() writer.Write() # returns 1 on success, 0 on failure ### STRUCTURED_POINTS - VECTORS ### reader = vtk.vtkStructuredPointsReader() reader.SetFileName("u.0001.vtk") reader.Update() vtk_data = reader.GetOutput() # return an n x 3 array of vectors vector_data = numpy_support.vtk_to_numpy(vtk_data.GetPointData().GetVectors()) mesh_shape = vtk_data.GetDimensions() origin = vtk_data.GetOrigin() spacing = vtk_data.GetSpacing()
def main(): # input file (vtk isosurface geom) fname = sys.argv[1] # unstructured grid vtk file # read unstructured grid usg = vtk.vtkUnstructuredGridReader() usg.SetFileName(fname) usg.Update() usgport = usg.GetOutputPort() # convert USG to polydata gf = vtk.vtkGeometryFilter() gf.SetInputConnection(usgport) gf.Update() pdport = gf.GetOutputPort() # setup decimate operator deci = vtk.vtkDecimatePro() deci.SetInputConnection(pdport) # set decimate options target = 0.9 deci.SetTargetReduction(target) # target reduction deci.SetPreserveTopology( True) # preserve topology (splitting or hole elimination not allowed) deci.SetSplitting(False) # no mesh splitting allowed deci.SetBoundaryVertexDeletion( False) # no boundary vertex (eddge/curve) deletion allowed deci.Update() deciport = deci.GetOutputPort() # convert polydata back to USG appendfilter = vtk.vtkAppendFilter() appendfilter.SetInputConnection(deciport) appendfilter.Update() usg_new = vtk.vtkUnstructuredGrid() usg_new.ShallowCopy(appendfilter.GetOutput()) # write file (USG) - needed for pymoab outfile = fname.split('.')[0] + '-decimate-out-usg.vtk' writer1 = vtk.vtkGenericDataObjectWriter() writer1.SetFileName(outfile) writer1.SetInputData(usg_new) writer1.Update() writer1.Write() # write out polydata too outpoly = fname.split('.')[0] + '-decimate-out-poly.vtk' writer2 = vtk.vtkGenericDataObjectWriter() writer2.SetFileName(outpoly) writer2.SetInputConnection(deciport) writer2.Update() writer2.Write() # try reading file in w/ pymoab again mb = core.Core() mb.load_file(outfile) rs = mb.get_root_set() # get entities w/ dim=2 (should be facets) all_facets = mb.get_entities_by_dimension(rs, 2) print(all_facets) print(len(all_facets)) # confirm facet type (should by tris, not polygons) facet_type = mb.type_from_handle(all_facets[0]) print(facet_type) tris1 = mb.get_entities_by_type(rs, facet_type) tris2 = mb.get_entities_by_type(rs, types.MBTRI) polys = mb.get_entities_by_type(rs, types.MBPOLYGON) print(tris1, len(tris1)) print(tris2, len(tris2)) print(polys, len(polys))