Search code examples
pythonvtkmayavi

Convert mayavi mlab.contour3d plot to vtkPolyData


I am trying to get the triangulated vtkPolyData from a mlab.contour3d plot. I am using mayavi because it seems to be the fastest way to get minimal surfaces triangulated properly. I need it as vtkPolyData because I want to save it as an .stl file.

Here is a MWE of my code:

import numpy as np
from mayavi import mlab

def fun(x, y, z):
    return np.cos(x) + np.cos(y) + np.cos(z)

x, y, z = np.mgrid[-1:1:100j, -1:1:100j, -1:1:100j]
contour = mlab.contour3d(x, y, z, fun)
mlab.show()

What I get then from mayavi is a surface that is already triangulated and displayed using VTK (or tvtk), so it should be possible to get the vtkPolyData from there. But the only way I found so far is to use mlab.savefig(test.obj) to export an .obj-file (which is bad, because it takes time to save the file everytime the mayavi UI opens) and import that file again using vtkOBJReader, which gives me the vtkPolyData I want.

Does anyone know a more straight-forward way to do this?

edit: To clarify my problem a bit more: I can access the data from the visualization e.g. with mayavi.tools.pipeline.get_vtk_src(), but it comes in form of vtkImageData. If anyone knows a way to convert that to vtkPolyData, that would also be a solution.


Solution

  • By total coincidence I found a solution.

    import numpy as np
    from mayavi import mlab
    
    def fun(x, y, z):
        return np.cos(x) + np.cos(y) + np.cos(z)
    
    x, y, z = np.mgrid[-1:1:100j, -1:1:100j, -1:1:100j]
    contour = mlab.contour3d(x, y, z, fun)
    actor = contour.actor.actors[0]
    polydata = tvtk.to_vtk(actor.mapper.input)  # solution
    mlab.show()
    

    The trick seems to be to access the mapper from the pipeline, which is a PolyDataMapper. Then I just use the tvtk.to_vtk() function so that I can continue with vtk which I prefer over tvtk, at least for now.