从原始 VTK (.vtu) 文件中读取数据

Man*_*bit 1 numpy vtk python-3.x

我想使用 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">
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下 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))
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个程序打印NoneType为输出,我不确定我需要更改什么才能提取potential数组中的数据存储?

Mat*_*hal 6

您没有使用正确的阅读器,这是一个.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")
Run Code Online (Sandbox Code Playgroud)


Nic*_*mer 5

A more lightweight solution would be to use meshio (which I authored). It has no required dependencies except numpy. Install with

pip install meshio
Run Code Online (Sandbox Code Playgroud)

and read the file with

pip install meshio
Run Code Online (Sandbox Code Playgroud)