首页 > 解决方案 > 如何使用 pyvtk 将 3D 矢量场从 numpy 数组导出到 *.vtk 文件?

问题描述

我正在努力将一些 3D 矢量数组(numpy 数组)从 python 导出到 *.vtk 文件以供以后在 ParaView 中使用。

我有三个 3D MR 测速图像,每个 100x100x200 体素包含 x、y 和 z 中的速度分量。我想要的是使用 pyvtk-module from here将此向量场导出到 *.vtk 文件。

不幸的是,我不明白它是如何工作的:-(

到目前为止我尝试了什么:

from pyvtk import *

vectors = [flow['vx'], flow['vy'], flow['vz']]

dim=flow['vx'].shape

pointdata=PointData(Vectors([flow['vx'],flow['vy'],flow['vz']]))

vtk=VtkData(StructuredPoints(dim[0],dim[1],dim[2]), pointdata)

其中 flow['...'] 包含向量分量。我收到以下错误:

ValueError: DataSet (size=100) and PointData (size=3) have different sizes

Yeeees,它想告诉我什么?好吧,猜猜尺寸不匹配之类的东西,但是我该如何正确设置我的输入呢?

任何帮助,将不胜感激。提前致谢

标签: pythonnumpyvtk

解决方案


我为我的问题找到了一个合适的解决方案,使用 TVTK 而不是 PyVTK。因此,每个有兴趣的人,可能的解决方法如下:

from tvtk.api import tvtk, write_data
# Unpack velocity information

vx=flow['vx']
vy=flow['vy']
vz=flow['vz']

dim=vx.shape

# Generate the grid
xx,yy,zz=np.mgrid[0:dim[0],0:dim[1],0:dim[2]]
pts = empty(vx.shape + (3,), dtype=int)
pts[..., 0] = xx
pts[..., 1] = yy
pts[..., 2] = zz

vectors = empty(vx.shape + (3,), dtype=float)
vectors[..., 0] = vx
vectors[..., 1] = vy
vectors[..., 2] = vz

# We reorder the points and vectors so this is as per VTK's
# requirement of x first, y next and z last.
pts = pts.transpose(2, 1, 0, 3).copy()
pts.shape = pts.size // 3, 3

vectors = vectors.transpose(2, 1, 0, 3).copy()
vectors.shape = vectors.size // 3, 3

sg = tvtk.StructuredGrid(dimensions=xx.shape, points=pts)

sg.point_data.vectors = vectors
sg.point_data.vectors.name = 'velocity'

write_data(sg, 'vtktest.vtk')

问候

噬菌体


推荐阅读