问题
Question:
How do I extract a dataset array from a VTK in Python and save it in a new file? e.g. for a VTK with data sets for magnitudes force, displacement and current extract only displacement and save it in a smaller file.
Problem:
I have hundreds of 4GB VTK files in a remote server and I want to extract one of the several data sets that are generated for different magnitudes. In these data sets I have Scalars and Vectors.
I wrote the following VTK Python code where I read the unstructured grid and I get the second array of data to save it later using a "vtkArrayWriter".
import vtk
Filename = 'file.vtk'
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName(Filename)
reader.ReadAllScalarsOn()
reader.ReadAllVectorsOn()
reader.Update()
obj = reader.GetOutput().GetPointData().GetArray(1)
writer = vtk.vtkArrayWriter()
writer.SetInputData(obj)
writer.SetFileName('test.vtk')
writer.Update()
The code gives me to following output:
TypeError: SetInputData argument 1: method requires a vtkDataObject, a vtkFloatArray was provided.
I did not manage to cast "vtkFloatArray" to "vtkDataObject" or to find an specific method that supports "vtkFloatArray" as input. I did not find many related codes but may be I googled the wrong keywords. At this point I got stuck.
Note:
This is the same procedure that can be achieved by applying the filter "PassArays" in Paraview and then saving but, given the size and characteristics of my problem, this is not a feasible solution.
回答1:
VTK has a vtkPassArrays
filter whose documentation is here. You need to know the name of the array that you want in the output file and whether the array is a Point/Cell/Field Data.
import vtk as v
Filename = 'file.vtk'
reader = v.vtkUnstructuredGridReader()
reader.SetFileName(Filename)
reader.ReadAllScalarsOn()
reader.ReadAllVectorsOn()
pa = v.vtkPassArrays()
pa.SetInputConnection(reader.GetOutputPort())
pa.AddArray( 0, 'Array1Name' ) # 0 for PointData, 1 for CellData, 2 for FieldData
writer = v.vtkDataSetWriter()
writer.SetFileName('test.vtk')
writer.SetInputConnection(pa.GetOutputPort())
writer.Update()
writer.Write()
The output file test.vtk
will contain all the points and the cells but only the array name you specify will be included. If instead you only want the array and not the points or the cells then the following solution is possible using VTK NumPy integration and numpy.savetxt.
import numpy as np
import vtk as v
from vtk.numpy_interface import dataset_adapter as dsa
reader = v.vtkUnstructuredGridReader()
reader.SetFileName(Filename)
reader.ReadAllScalarsOn()
reader.ReadAllVectorsOn()
reader.Update()
usg = dsa.WrapDataObject( reader.GetOutput() )
array1 = usg.PointData['Array1Name'] # Assuming you know the name of the array
# array1 is a child class type of numpy.ndarray type
np.savetxt('array1.dat', array1, fmt='%4.5f' )
来源:https://stackoverflow.com/questions/51043815/save-an-array-of-data-from-a-vtk-in-python