我想使用Python VTK模块从.vtu文件中提取数据数组。该文件如下所示(文件末尾的原始数据被省略):
<?xml version="1.0"?>
<VTKFile type="UnstructuredGrid" version="0.1" byte_order="LittleEndian">
<UnstructuredGrid>
<Piece NumberOfPoints="10471" NumberOfCells="64892">
<PointData>
<DataArray type="Float64" Name="potential" NumberOfComponents="1" format="appended" offset="0"/>
<DataArray type="Float64" Name="electric field" NumberOfComponents="3" format="appended" offset="83772"/>
</PointData>
<CellData>
<DataArray type="Int32" Name="GeometryIds" format="appended" offset="335080"/>
</CellData>
<Points>
<DataArray type="Float64" NumberOfComponents="3" format="appended" offset="594652"/>
</Points>
<Cells>
<DataArray type="Int32" Name="connectivity" format="appended" offset="845960"/>
<DataArray type="Int32" Name="offsets" format="appended" offset="1865068"/>
<DataArray type="Int32" Name="types" format="appended" offset="2124640"/>
</Cells>
</Piece>
</UnstructuredGrid>
<AppendedData encoding="raw">
我尝试使用以下python代码提取数据:
import numpy
from vtk import vtkUnstructuredGridReader
from vtk.util import numpy_support as VN
reader = vtkUnstructuredGridReader()
reader.SetFileName("charged_wire.vtu")
reader.ReadAllVectorsOn()
reader.ReadAllScalarsOn()
reader.Update()
data = reader.GetOutput()
potential = data.GetPointData().GetScalars("potential")
print(type(potential))
不幸的是,该程序将NoneType
打印为输出,并且我不确定是否需要更改以提取potential
数组中的数据存储区吗?
答案 0 :(得分:2)
更轻巧的解决方案是使用meshio(我编写)。除numpy外,它没有必需的依赖项。使用
安装pip install meshio
并使用
读取文件import meshio
mesh = meshio.read("foo.vtu")
# mesh.points, mesh.cells, mesh.point_data, ...
答案 1 :(得分:1)
您使用的阅读器不正确,这是一个.vtu
文件,您必须使用vtkXMLUnstructuredGridReader
。
import vtk.vtk
# The source file
file_name = "path/to/your/file.vtu"
# Read the source file.
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName(file_name)
reader.Update() # Needed because of GetScalarRange
output = reader.GetOutput()
potential = output.GetPointData().GetArray("potential")