def saveStartLine(self, filename): writer = vtk.vtkStructuredGridWriter() writer.SetFileVersion(42) # write 4.2 VTK files writer.SetFileName(filename) writer.SetInputData(self.startLineGrid) writer.Update()
def _write_vtk_box(box_points, filename, dimensions): """ Private method that writes a vtk file containing FFD control points. :param numpy.ndarray box_points: coordinates of the FFD control points. :param string filename: name of the output file. :param list dimensions: dimension of the lattice in (x, y, z) directions. """ # setup points and vertices points = vtk.vtkPoints() for index in range(0, box_points.shape[1]): ind = points.InsertNextPoint(box_points[0, index], box_points[1, index], box_points[2, index]) grid = vtk.vtkStructuredGrid() grid.SetPoints(points) grid.SetDimensions(dimensions) grid.Modified() writer = vtk.vtkStructuredGridWriter() writer.SetFileName(filename) if vtk.VTK_MAJOR_VERSION <= 5: grid.Update() writer.SetInput(grid) else: writer.SetInputData(grid) writer.Write()
def _write_vtk_box(box_points, filename, dimensions): """ Private method that writes a vtk file containing FFD control points. :param numpy.ndarray box_points: coordinates of the FFD control points. :param string filename: name of the output file. :param list dimensions: dimension of the lattice in (x, y, z) directions. .. warning:: If you want to visualize in paraview the inner points, you have to slice the lattice because paraview does not visualize them automatically even in the wireframe visualization. """ # setup points and vertices points = vtk.vtkPoints() for index in range(0, box_points.shape[1]): points.InsertNextPoint(box_points[0, index], box_points[1, index], box_points[2, index]) grid = vtk.vtkStructuredGrid() grid.SetPoints(points) grid.SetDimensions(dimensions) grid.Modified() writer = vtk.vtkStructuredGridWriter() writer.SetFileName(filename) if vtk.VTK_MAJOR_VERSION <= 5: grid.Update() writer.SetInput(grid) else: writer.SetInputData(grid) writer.Write()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkStructuredGridWriter(), 'Writing vtkStructuredGrid.', ('vtkStructuredGrid',), (), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def cone(c1,h_max,phi,n=100,name='temp'): c1 = np.array(c1) phi = np.radians(phi) r_max = h_max/np.tan(phi) hyp = h_max/np.sin(phi) circ = 2*np.pi*r_max nr = np.round(n*hyp/circ).astype('int') nr1 = nr+1 theta = np.linspace(0,2*np.pi,n+1) h = np.linspace(0,h_max,nr+1) r = h/np.tan(phi) X = np.outer(np.cos(theta), r) Y = np.outer(np.sin(theta), r) Z = np.outer(np.ones(theta.shape[0]), h) gridpoints = np.stack([X.flat, Y.flat, Z.flat], axis=1) gridpoints += c1 points = vtk.vtkPoints() points.SetData(vtknp.numpy_to_vtk(gridpoints)) grid = vtk.vtkStructuredGrid() grid.SetDimensions(nr1, n+1, 1) grid.SetPoints(points) addCoordData(grid,gridpoints) writer = vtk.vtkStructuredGridWriter() writer.SetFileName(name+'.vtk') writer.SetInputData(grid) writer.Write()
def to_vtk(self, file_name): for i, time in enumerate(self.times): file_base, file_ext = os.path.splitext(file_name) if file_ext == ".vtk": writer = vtk.vtkStructuredGridWriter() elif file_ext == ".vts": writer = vtk.vtkXMLStructuredGridWriter() elif file_ext == "": file_name = file_base + ".vts" writer = vtk.vtkXMLStructuredGridWriter() else: msg = "This function can only use the vtk or vts file extension not %s" % file_ext raise ValueError(msg) grid = self.CoordDF.vtkStructuredGrid() if len(self.times) > 1: num_zeros = int(np.log10(len(self.times))) + 1 ext = str(num_zeros).zfill(num_zeros) file_name = os.path.join(file_name, ".%s" % ext) for comp in self.comp: grid.cell_arrays[np.str_(comp)] = self[time, comp].flatten() # pyvista.save_meshio(file_name,grid,file_format="vtk") writer.SetFileName(file_name) if vtk.vtkVersion().GetVTKMajorVersion() <= 5: grid.Update() writer.SetInput(grid) else: writer.SetInputData(grid) writer.Write()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkStructuredGridWriter(), 'Writing vtkStructuredGrid.', ('vtkStructuredGrid', ), (), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def save(self, file_name): self.file_name = os.path.splitext(file_name)[0] file_name_out = self.file_name + ".vtk" writer = vtk.vtkStructuredGridWriter() writer.SetFileName(file_name_out) if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(self.reader.GetOutput()) else: writer.SetInputData(self.reader.GetOutput()) writer.Write() print "|_Vtk_writer.writer file: \'%s\' " % (file_name_out)
def saveVectorField(self): nxv, nyv = 101, 101 vi = mint.VectorInterp() vi.setGrid(self.grid) vi.buildLocator(numCellsPerBucket=100, periodX=0.) xx, yy = numpy.meshgrid( numpy.linspace(self.xymin[0], self.xymax[0], nxv), numpy.linspace(self.xymin[1], self.xymax[1], nyv)) xyz = numpy.zeros((nxv * nyv, 3), numpy.float64) xyz[:, 0] = xx.flat xyz[:, 1] = yy.flat vi.findPoints(xyz) vectors_edge = vi.getEdgeVectors(self.data, placement=mint.CELL_BY_CELL_DATA) vectors_face = vi.getFaceVectors(self.data, placement=mint.CELL_BY_CELL_DATA) ptsData = vtk.vtkDoubleArray() ptsData.SetNumberOfComponents(3) ptsData.SetNumberOfTuples(nxv * nyv) ptsData.SetVoidArray(xyz, nxv * nyv * 3, 1) pts = vtk.vtkPoints() pts.SetData(ptsData) # add vector field vecDataEdge = vtk.vtkDoubleArray() vecDataEdge.SetName('vector_edge') vecDataEdge.SetNumberOfComponents(3) vecDataEdge.SetNumberOfTuples(nxv * nyv) vecDataEdge.SetVoidArray(vectors_edge, nxv * nyv * 3, 1) vecDataFace = vtk.vtkDoubleArray() vecDataFace.SetName('vector_face') vecDataFace.SetNumberOfComponents(3) vecDataFace.SetNumberOfTuples(nxv * nyv) vecDataFace.SetVoidArray(vectors_face, nxv * nyv * 3, 1) sgrid = vtk.vtkStructuredGrid() sgrid.SetDimensions((nxv, nyv, 1)) sgrid.SetPoints(pts) sgrid.GetPointData().AddArray(vecDataEdge) sgrid.GetPointData().AddArray(vecDataFace) writer = vtk.vtkStructuredGridWriter() writer.SetFileName('vectors.vtk') writer.SetInputData(sgrid) writer.Update()
def chooseWriter(self, file_format, vtk_dataset_type): """ Return a writer based on file_format and possibly vtk_dataset_type. @param vtk_dataset_type, None or one of the VTK_DATASET_TYPES """ if file_format == 'ply': return vtk.vtkPLYWriter() # For now we'll just return the POLYDATA writer since methods work # only with that vtk_dataset_type. return vtk.vtkPolyDataWriter() if vtk_dataset_type == 'STRUCTURED_GRID': return vtk.vtkStructuredGridWriter() elif vtk_dataset_type == 'POLYDATA': return vtk.vtkPolyDataWriter() elif vtk_dataset_type == 'UNSTRUCTURED_GRID': return vtk.vtkUnstructuredGridWriter()
def writeSGrid(sgrid, filename, verbose=0): mypy.my_print(verbose, "*** writeSGrid: " + filename + " ***") if ('vtk' in filename): sgrid_writer = vtk.vtkStructuredGridWriter() elif ('vts' in filename): sgrid_writer = vtk.vtkXMLStructuredGridWriter() else: assert 0, "File must be .vtk or .vts. Aborting." sgrid_writer.SetFileName(filename) if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): sgrid_writer.SetInputData(sgrid) else: sgrid_writer.SetInput(sgrid) sgrid_writer.Update() sgrid_writer.Write()
def saveLineVTK(xyz, filename): n = xyz.shape[0] ptsData = vtk.vtkDoubleArray() ptsData.SetNumberOfComponents(3) ptsData.SetNumberOfTuples(n) ptsData.SetVoidArray(xyz, n * 3, 1) pts = vtk.vtkPoints() pts.SetData(ptsData) sgrid = vtk.vtkStructuredGrid() sgrid.SetDimensions((n, 1, 1)) sgrid.SetPoints(pts) writer = vtk.vtkStructuredGridWriter() writer.SetFileName(filename) writer.SetInputData(sgrid) writer.Update()
def save(self, filename, binary=True): """ Writes a structured grid to disk. Parameters ---------- filename : str Filename of grid to be written. The file extension will select the type of writer to use. ".vtk" will use the legacy writer, while ".vts" will select the VTK XML writer. binary : bool, optional Writes as a binary file by default. Set to False to write ASCII. Notes ----- Binary files write much faster than ASCII, but binary files written on one system may not be readable on other systems. Binary can be used only with the legacy writer. """ filename = os.path.abspath(os.path.expanduser(filename)) # Use legacy writer if vtk is in filename if '.vtk' in filename: writer = vtk.vtkStructuredGridWriter() if binary: writer.SetFileTypeToBinary() else: writer.SetFileTypeToASCII() elif '.vts' in filename: writer = vtk.vtkXMLStructuredGridWriter() if binary: writer.SetDataModeToBinary() else: writer.SetDataModeToAscii() else: raise Exception('Extension should be either ".vts" (xml) or' + '".vtk" (legacy)') # Write writer.SetFileName(filename) writer.SetInputData(self) writer.Write()
def _write_vtk_box(box_points, filename, dimensions): """ Private method that writes a vtk file containing FFD control points. :param numpy.ndarray box_points: coordinates of the FFD control points. :param string filename: name of the output file. :param list dimensions: dimension of the lattice in (x, y, z) directions. .. warning:: If you want to visualize in paraview the inner points, you have to slice the lattice because paraview does not visualize them automatically even in the wireframe visualization. """ # setup points and vertices points = vtk.vtkPoints() for index in range(0, box_points.shape[1]): points.InsertNextPoint( box_points[0, index], box_points[1, index], box_points[2, index] ) grid = vtk.vtkStructuredGrid() grid.SetPoints(points) grid.SetDimensions(dimensions) grid.Modified() writer = vtk.vtkStructuredGridWriter() writer.SetFileName(filename) if vtk.VTK_MAJOR_VERSION <= 5: grid.Update() writer.SetInput(grid) else: writer.SetInputData(grid) writer.Write()
def coffeeFilter(c1,c2,h_max,phi1,phi2,n=100,name='temp'): c1 = np.array(c1) c2 = np.array(c2) c2mc1 = c2[:2]-c1[:2] L = np.linalg.norm(c2mc1) phi1 = np.radians(phi1) phi2 = np.radians(phi2) phi = (phi1+phi2)/2 r_max = h_max/np.tan(phi) hyp = h_max/np.sin(phi) circ = np.pi*r_max/2 nr = np.round(n*hyp/circ).astype('int') nL = np.round(n*L/circ).astype('int') nr1 = nr+1 nL1 = nL+1 theta = np.linspace(0,np.pi,n+1) h = np.linspace(0,h_max,nr1) r1 = h/np.tan(phi1) X = np.outer(np.cos(theta), r1) Y = np.outer(np.sin(theta), r1) Z = np.outer(np.ones(theta.shape[0]), h) halfCone = np.stack([X.flat, Y.flat, Z.flat], axis=1) r2 = h/np.tan(phi2) X = np.outer(np.cos(theta), r2) Y = np.outer(np.sin(theta), r2) halfCone2 = np.stack([X.flat, Y.flat, Z.flat], axis=1) R = Rot.from_euler('z', 180, degrees=True) halfCone2 = R.apply(halfCone2) halfCone2[:,1] -= L y = np.linspace(L/2,-L/2,nL1) X = -(np.outer(y/L+0.5, r1)+np.outer(-y/L+0.5, r2)) Y = np.outer(y, np.ones(r1.shape[0])) Z = np.outer(np.ones(nL1), h) plane = np.stack([X.flat, Y.flat, Z.flat], axis=1) y = np.linspace(-L/2,L/2,nL1) X = np.outer(y/L+0.5, r1)+np.outer(-y/L+0.5, r2) Y = np.outer(y, np.ones(r1.shape[0])) Z = np.outer(np.ones(nL1), h) plane2 = np.stack([X.flat, Y.flat, Z.flat], axis=1) plane[:,1] -= L/2 plane2[:,1] -= L/2 gridpoints = np.concatenate([halfCone,plane[nr1:,:],halfCone2[nr1:,:],plane2[nr1:,:]], axis=0) R = Rot.from_euler('z', np.arctan2(c2mc1[1],c2mc1[0]) + np.pi/2) gridpoints = R.apply(gridpoints) gridpoints += c1 points = vtk.vtkPoints() points.SetData(vtknp.numpy_to_vtk(gridpoints)) grid = vtk.vtkStructuredGrid() grid.SetDimensions(nr1, 2*(n+nL)+1, 1) grid.SetPoints(points) addCoordData(grid,gridpoints) writer = vtk.vtkStructuredGridWriter() writer.SetFileName(name+'.vtk') writer.SetInputData(grid) writer.Write()
def save(self, filename): writer = vtk.vtkStructuredGridWriter() writer.SetFileName(filename) writer.SetInputData(self.grid) writer.Update()
def writeLagrangianFieldToVTK(a_RefCoordinates, a_RefNums, a_FTLE_T, a_FTLE_NoT, \ a_Stretch_1, a_Stretch_2, a_Stretch_3, \ a_Strain_1, a_Strain_2, a_Strain_3, a_LagFlags, a_VecFlags, a_OutputFile): xN = a_RefNums[0] yN = a_RefNums[1] zN = a_RefNums[2] vtkGrid = vtk.vtkStructuredGrid() vtkGrid.SetDimensions([xN, yN, zN]) points = vtk.vtkPoints() points.SetNumberOfPoints(xN * yN * zN) if a_LagFlags[0] == True: ftleArr_T = vtk.vtkDoubleArray() ftleArr_T.SetName('FTLE - T') ftleArr_T.SetNumberOfComponents(1) ftleArr_T.SetNumberOfTuples(xN * yN * zN) ftleArr_NoT = vtk.vtkDoubleArray() ftleArr_NoT.SetName('FTLE - No T') ftleArr_NoT.SetNumberOfComponents(1) ftleArr_NoT.SetNumberOfTuples(xN * yN * zN) if a_LagFlags[1] == True: if a_VecFlags[0] == True: stretchArr_1 = vtk.vtkDoubleArray() stretchArr_1.SetName('Stretch: 1') stretchArr_1.SetNumberOfComponents(1) stretchArr_1.SetNumberOfTuples(xN * yN * zN) if a_VecFlags[1] == True: stretchArr_2 = vtk.vtkDoubleArray() stretchArr_2.SetName('Stretch: 2') stretchArr_2.SetNumberOfComponents(1) stretchArr_2.SetNumberOfTuples(xN * yN * zN) if a_VecFlags[2] == True: stretchArr_3 = vtk.vtkDoubleArray() stretchArr_3.SetName('Stretch: 3') stretchArr_3.SetNumberOfComponents(1) stretchArr_3.SetNumberOfTuples(xN * yN * zN) if a_LagFlags[2] == True: if a_VecFlags[0] == True: strainArr_1 = vtk.vtkDoubleArray() strainArr_1.SetName('Strain: 1') strainArr_1.SetNumberOfComponents(1) strainArr_1.SetNumberOfTuples(xN * yN * zN) if a_VecFlags[1] == True: strainArr_2 = vtk.vtkDoubleArray() strainArr_2.SetName('Strain: 2') strainArr_2.SetNumberOfComponents(1) strainArr_2.SetNumberOfTuples(xN * yN * zN) if a_VecFlags[2] == True: strainArr_3 = vtk.vtkDoubleArray() strainArr_3.SetName('Strain: 3') strainArr_3.SetNumberOfComponents(1) strainArr_3.SetNumberOfTuples(xN * yN * zN) for p in range(a_RefCoordinates.shape[0]): xyz = a_RefCoordinates[p, :] points.InsertPoint(p, xyz) if a_LagFlags[0] == True: ftleArr_T.SetTuple1(p, a_FTLE_T[p]) ftleArr_NoT.SetTuple1(p, a_FTLE_NoT[p]) if a_LagFlags[1] == True: if a_VecFlags[0] == True: stretchArr_1.SetTuple1(p, a_Stretch_1[p]) if a_VecFlags[1] == True: stretchArr_2.SetTuple1(p, a_Stretch_2[p]) if a_VecFlags[2] == True: stretchArr_3.SetTuple1(p, a_Stretch_3[p]) if a_LagFlags[2] == True: if a_VecFlags[0] == True: strainArr_1.SetTuple1(p, a_Strain_1[p]) if a_VecFlags[1] == True: strainArr_2.SetTuple1(p, a_Strain_2[p]) if a_VecFlags[2] == True: strainArr_3.SetTuple1(p, a_Strain_3[p]) vtkGrid.SetPoints(points) if a_LagFlags[0] == True: vtkGrid.GetPointData().AddArray(ftleArr_T) vtkGrid.GetPointData().AddArray(ftleArr_NoT) if a_LagFlags[1] == True: if a_VecFlags[0] == True: vtkGrid.GetPointData().AddArray(stretchArr_1) if a_VecFlags[1] == True: vtkGrid.GetPointData().AddArray(stretchArr_2) if a_VecFlags[2] == True: vtkGrid.GetPointData().AddArray(stretchArr_3) if a_LagFlags[2] == True: if a_VecFlags[0] == True: vtkGrid.GetPointData().AddArray(strainArr_1) if a_VecFlags[1] == True: vtkGrid.GetPointData().AddArray(strainArr_2) if a_VecFlags[2] == True: vtkGrid.GetPointData().AddArray(strainArr_3) writer = vtk.vtkStructuredGridWriter() writer.SetFileName(a_OutputFile) writer.SetInputData(vtkGrid) writer.SetFileTypeToBinary() writer.Update() writer.Write()
try: channel = open("combsg.vtk", "wb") channel.close() channel = open("SGridField.vtk", "wb") channel.close() # Create a reader and write out the field comb = vtk.vtkMultiBlockPLOT3DReader() comb.SetXYZFileName(VTK_DATA_ROOT + "/Data/combxyz.bin") comb.SetQFileName(VTK_DATA_ROOT + "/Data/combq.bin") comb.SetScalarFunctionNumber(100) comb.Update() output = comb.GetOutput().GetBlock(0) wsg = vtk.vtkStructuredGridWriter() wsg.SetInputData(output) wsg.SetFileTypeToBinary() wsg.SetFileName("combsg.vtk") wsg.Write() pl3d = vtk.vtkStructuredGridReader() pl3d.SetFileName("combsg.vtk") ds2do = vtk.vtkDataSetToDataObjectFilter() ds2do.SetInputConnection(pl3d.GetOutputPort()) writer = vtk.vtkDataObjectWriter() writer.SetInputConnection(ds2do.GetOutputPort()) writer.SetFileName("SGridField.vtk") writer.Write()
assert(r.GetOutput().GetExtent() == (1,3,1,3,1,3)) sg = vtk.vtkStructuredGrid() extents = (1, 3, 1, 3, 1, 3) sg.SetExtent(extents) ptsa = vtk.vtkFloatArray() ptsa.SetNumberOfComponents(3) ptsa.SetNumberOfTuples(27) # We don't really care about point coordinates being correct for i in range(27): ptsa.InsertNextTuple3(0, 0, 0) pts = vtk.vtkPoints() pts.SetData(ptsa) sg.SetPoints(pts) w = vtk.vtkStructuredGridWriter() w.SetInputData(sg) w.SetFileName("test-dim.vtk") w.Write() r = vtk.vtkStructuredGridReader() r.SetFileName("test-dim.vtk") r.Update() os.remove("test-dim.vtk") assert(r.GetOutput().GetExtent() == (0,2,0,2,0,2)) w.SetInputData(sg) w.SetFileName("test-dim.vtk") w.SetWriteExtent(True)
filename = file0 basefilename = dir ampreader = vtk.vtkStructuredGridReader() ampreader.SetFileName(filename) ampreader.Update() for file0 in os.listdir('.'): if fnmatch.fnmatch(file0, '*PH.rec.vtk'): filename = file0 phreader = vtk.vtkStructuredGridReader() phreader.SetFileName(filename) phreader.Update() pharr = phreader.GetOutput().GetPointData().GetScalars() pharr.SetName("phases") data = ampreader.GetOutput() data.GetPointData().GetScalars().SetName("amps") data.GetPointData().AddArray(pharr) #data.GetPointData().SetActiveAttribute("phases", 0) data.Update() print file0 filename = path + '/Amp-Phase.vtk' print filename gridwriter = vtk.vtkStructuredGridWriter() gridwriter.SetFileName(filename) gridwriter.SetFileTypeToBinary() gridwriter.SetInput(data) gridwriter.Write()
def export(polygon, project, manager, boundary_mode='exterior', rotation_mode='none', coords='utm33n', resolution=None, maxpts=None, format='png', structured=False, colormap='Terrain', invert=False, texture=False, zero_sea_level=True, filename=None, directory=None, axis_align=False): # Sanitize parameters image_mode = is_image_format(format) if not supports_texture(format): texture = False if not supports_structured_choice(format): structured = is_structured_format(format) if format == 'tiff' and coords != 'utm33n': raise ValueError( 'GeoTIFF output for other formats than UTM33N is not supported') manager.report_max(4 if texture else 3) manager.report_message('Generating geometry') if structured: (in_x, in_y), (out_x, out_y), trf = polygon.generate_meshgrid( boundary_mode, rotation_mode, in_coords=project.coords, out_coords=coords, resolution=resolution, maxpts=maxpts, axis_align=axis_align, ) else: (in_x, in_y), (out_x, out_y), tri = polygon.generate_triangulation( in_coords=project.coords, out_coords=coords, resolution=resolution, ) manager.increment_progress() if texture: manager.report_message('Generating texture coordinates') left = np.min(out_x) right = np.max(out_x) down = np.min(out_y) up = np.max(out_y) uvcoords = np.stack([(out_x - left) / (right - left), (out_y - down) / (up - down)], axis=out_x.ndim) manager.increment_progress() manager.report_message('Generating data') data = polygon.interpolate(project, in_x, in_y) if not zero_sea_level: data -= np.min(data) manager.increment_progress() manager.report_message('Saving file') if filename is None: filename = hashlib.sha256(data.data).hexdigest() + '.' + format filename = Path(directory) / filename if image_mode: array_to_image(data, format, filename, cmap=colormap, invert=invert) elif format == 'g2': from splipy import Surface, BSplineBasis from splipy.io import G2 cpts = np.stack([out_x, out_y, data[..., 0]], axis=2) knots = [[0.0] + list(map(float, range(n))) + [float(n - 1)] for n in data.shape[:2]] bases = [BSplineBasis(order=2, knots=kts) for kts in knots] srf = Surface(*bases, cpts, raw=True) with G2(filename) as g2: g2.write(srf) elif format == 'stl': from stl.mesh import Mesh as STLMesh mesh = STLMesh(np.zeros(tri.shape[0], STLMesh.dtype)) mesh.vectors[:, :, 0] = out_x[tri] mesh.vectors[:, :, 1] = out_y[tri] mesh.vectors[:, :, 2] = data[tri, 0] mesh.save(filename) elif format in ('vtk', 'vtu', 'vts'): import vtk import vtk.util.numpy_support as vtknp pointsarray = np.stack([out_x.flat, out_y.flat, data.flat], axis=1) points = vtk.vtkPoints() points.SetData(vtknp.numpy_to_vtk(pointsarray)) if structured: grid = vtk.vtkStructuredGrid() grid.SetDimensions(*out_x.shape[::-1], 1) else: ncells = len(tri) cellarray = np.concatenate( [3 * np.ones((ncells, 1), dtype=int), tri], axis=1) cells = vtk.vtkCellArray() cells.SetCells(ncells, vtknp.numpy_to_vtkIdTypeArray(cellarray.ravel())) grid = vtk.vtkUnstructuredGrid() grid.SetCells(vtk.VTK_TRIANGLE, cells) grid.SetPoints(points) if texture: grid.GetPointData().SetTCoords( vtknp.numpy_to_vtk(uvcoords.reshape(-1, 2))) if format == 'vts': writer = vtk.vtkXMLStructuredGridWriter() elif format == 'vtu': writer = vtk.vtkXMLUnstructuredGridWriter() else: writer = vtk.vtkStructuredGridWriter( ) if structured else vtk.vtkUnstructuredGridWriter() writer.SetFileName(filename) writer.SetInputData(grid) writer.Write() elif format == 'tiff': import tifffile tifffile.imwrite( filename, data[:, ::-1].T, extratags=[ # GeoKeyDirectoryTag ( 34735, 'h', 28, ( 1, 1, 1, 6, # Version and number of geo keys 1024, 0, 1, 1, # GTModelTypeGeoKey (2D projected CRS) 1025, 0, 1, 1, # GTRasterTypeGeoKey (pixels denote areas) 2048, 0, 1, 4258, # GeodeticCRSGeoKey (ETRS89) 2050, 0, 1, 6258, # GeodeticDatumGeoKey (ETRS89) 2051, 0, 1, 8901, # PrimeMeridianGeoKey (Greenwich) 3072, 0, 1, 25833, # ProjectedCRSGeoKey (ETRS89: UTM33N) ), True), # ModelTransformationTag (34264, 'd', 16, tuple(trf.flat), True), ]) manager.increment_progress() return filename
def write_polydata(input_data, filename, datatype=None, file_type="ascii"): """ Write the given input data based on the file name extension. Args: file_type (string): Filetype of output input_data (vtkSTL/vtkPolyData/vtkXMLStructured/ vtkXMLRectilinear/vtkXMLPolydata/vtkXMLUnstructured/ vtkXMLImage/Tecplot): Input data. filename (str): Save path location. datatype (str): Additional parameter for vtkIdList objects. """ # Check filename format fileType = filename.split(".")[-1] if fileType == '': raise RuntimeError('The file does not have an extension') # Get writer if fileType == 'stl': writer = vtk.vtkSTLWriter() elif fileType == 'vtk': # Set reader based on data type if isinstance(input_data, vtk.vtkUnstructuredGrid): writer = vtk.vtkUnstructuredGridWriter() elif isinstance(input_data, vtk.vtkStructuredGrid): writer = vtk.vtkStructuredGridWriter() elif isinstance(input_data, vtk.vtkRectilinearGrid): writer = vtk.vtkRectilinearGridWriter() elif isinstance(input_data, vtk.vtkStructuredPoints) or \ isinstance(input_data, vtk.vtkImageData): writer = vtk.vtkStructuredPointsWriter() elif isinstance(input_data, vtk.vtkPolyData): writer = vtk.vtkPolyDataWriter() if file_type.lower() == "ascii": writer.SetFileType(1) elif file_type.lower() == "binary": writer.SetFileType(0) else: raise ValueError("Invalid file type, can only be ascii or binary") elif fileType == 'vts': writer = vtk.vtkXMLStructuredGridWriter() elif fileType == 'vtr': writer = vtk.vtkXMLRectilinearGridWriter() elif fileType == 'vtp': writer = vtk.vtkXMLPolyDataWriter() elif fileType == 'vtu': writer = vtk.vtkXMLUnstructuredGridWriter() elif fileType == "vti": writer = vtk.vtkXMLImageDataWriter() elif fileType == "np" and datatype == "vtkIdList": output_data = np.zeros(input_data.GetNumberOfIds()) for i in range(input_data.GetNumberOfIds()): output_data[i] = input_data.GetId(i) output_data.dump(filename) return else: raise RuntimeError('Unknown file type %s' % fileType) # Set filename and input writer.SetFileName(filename) writer.SetInputData(input_data) writer.Update() # Write writer.Write()