4

I've been looking to export a surface that I am rendering with mayavi as a .stl file, and I haven't found any solutions.

I came up with a bit of code which appears to work, though it may not be the best solution. Below you can see a sample to show what I am doing.

Is there a better way to write a stl file of a surface with mayavi?

from mayavi import mlab
import vtk

# numpy array of points which define the vertices of the surface
points = np.array([[0,0,0],[1,0,0],[1,1,0]]) 
# numpy array defining the triangle which connects those points
element = np.array([[0,1,2]]) 

# mlab surface defined with the points and element
surface = mlab.pipeline.triangular_mesh_source(points[:,0], points[:,1], points[:,2], element) 

# For readability, define a variable as the _vtk_obj from the surface.
# This will be the surface data in the .stl file.
surface_vtk = surface.outputs[0]._vtk_obj

stlWriter = vtk.vtkSTLWriter()
# Set the file name
stlWriter.SetFileName('test_surface.stl')
# Set the input for the stl writer. surface.output[0]._vtk_obj is a polydata object
stlWriter.SetInput(surface_vtk)
# Write the stl file
stlWriter.Write()

# View the .stl surface that was just written-----------------------------------------------
from mayavi.core.api import Engine

engine = Engine()
# Create a new figure and add that figure to the engine
fig = mlab.figure(engine = engine)
# Open the stl file
surface_data = engine.open('test_surface.stl')
# Add the opened surface to the pipeline
opened_surface = mlab.pipeline.surface(surface_data)
# Add a module to show the opened surface
mlab.pipeline.surface(opened_surface, figure = fig)
# Show the scene
mlab.show()
Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
wzaylor
  • 195
  • 2
  • 9
  • I doubt you'll find a cleaner way. Though it might be useful to work this code into a patch to provide an interface for more easily exporting surfaces. – aestrivex Sep 22 '14 at 14:46
  • My main concern is using the outputs list in the surface object (surface.outputs[0]). Currently it is hard coded to export the first entry. Do you know if it is possible to have more than one entry into the surface.outputs list? – wzaylor Sep 22 '14 at 15:16
  • It may be possible, but you would have to be doing something quite unusual. But for your purposes, I wouldn't worry about it. – aestrivex Sep 22 '14 at 16:08

0 Answers0