将vtk UnstrucutredGrid写入python中的文件

问题描述 投票:1回答:1

我想将3D标量数据写入* .vtu文件(使用python)以便稍后在Paraview中获取并以体积方式查看。我可以编写* .vtu文件,但Paraview在加载时会崩溃。我是否错误地使用了vtk API?

我的方法:(Python 2.7.12,VTK_MAJOR_VERSION 6,Paraview 5.0.1)

我遵循了我能找到的唯一使用PolyVertex对象here的例子。

并想出了以下课程:

import vtk
import numpy as np

class VtkPolyVertCloud(object):

    def __init__(self):

        self.points= vtk.vtkPoints()
        self.grid = vtk.vtkUnstructuredGrid()
        self.values = vtk.vtkDoubleArray()
        self.values.SetName('point_values_array')
        self.grid.SetPoints(self.points)
        self.grid.GetPointData().SetScalars(self.values)

    def add_polyVertex_cell(self, points, data):
        """
        adds points according to user-supplied numpy arrays

        @param points: numpy array of 3d point coords -- points.shape = (npoints, 3)
        @param data: scalar-valued data belonging to each point -- data.shape = (npoints,)
        """
        npts = points.shape[0]

        pv = vtk.vtkPolyVertex()
        pv.GetPointIds().SetNumberOfIds(npts)
        for idx, point in enumerate(points):
            pointID = self.points.InsertNextPoint(point)
            pv.GetPointIds().SetId(idx, pointID)
            self.values.InsertNextValue(data[idx])

        self.grid.InsertNextCell(pv.GetCellType(), pv.GetPointIds())

我实例化该类并尝试将简单的随机PolyVertex单元格写入XML文件:

def test_vtkPolyVertexCloud_writeToFile():
    """ adds a set of polyvertices meant to represent a finite element """
    pc = vtku.VtkPolyVertCloud()
    points, data = np.random.rand(10, 3), np.random.rand(10)
    pc.add_polyVertex_cell(points, data)

    # write
    fn = 'test_PolyVertexCloud.vtu'
    writer = vtk.vtkUnstructuredGridWriter()
    writer.SetFileName(fn)
    writer.SetInputData(pc.grid)
    writer.Write()

在Paraview中打开文件后,Paraview Gui没有响应,然后崩溃。

python vtk paraview
1个回答
1
投票

一个可以说更容易的方法是使用meshio(我的一个项目)。您可以轻松地以各种格式编写非结构化网格,例如VTK / VTU。安装时

pip3 install meshio [--user]

(甚至不依赖于vtk)并使用它

import meshio
import numpy

points = numpy.array([
    [0.0, 0.0, 0.0],
    [0.0, 1.0, 0.0],
    [0.0, 0.0, 1.0],
    ])
cells = {
    "triangle": numpy.array([
        [0, 1, 2]
        ])
    }
meshio.write_points_cells(
    "foo.vtu",
    points,
    cells,
    # Optionally provide extra data on points, cells, etc.
    # point_data=point_data,
    # cell_data=cell_data,
    # field_data=field_data
    )
© www.soinside.com 2019 - 2024. All rights reserved.