3D visualization of DXF STL file using mayavi python script

extensive googling doesn’t find a good solution. Writing a python script from scratch actually takes much less time.

"""
To read a STL file and plot in mayavi
First created by Junwei Huang @ Toronto, Feb 26, 2013
"""

from numpy import *
from mayavi import mlab

STLfile="test.stl"
f=open(STLfile,'r')

x=[]
y=[]
z=[]

for line in f:
	strarray=line.split()
	if strarray[0]=='vertex':
		x=append(x,double(strarray[1]))
		y=append(y,double(strarray[2]))
		z=append(z,double(strarray[3]))

triangles=[(i, i+1, i+2) for i in range(0, len(x),3)]

mlab.triangular_mesh(x, y, z, triangles)
mlab.show()
tunnel geometry from STL file

tunnel geometry from STL file

Q: What about DXF file?
A: Convert DXF to STL file first before using this script:)

6 thoughts on “3D visualization of DXF STL file using mayavi python script

  1. Nice code! I am trying to to resize only one axis (i.e. x-axis) coordinates so I type x=append(x,double(strarray[1]))/xScale

    where xScale is a float (e.g. 0.5) but then the shape displayed is completely messed up.

    What am I doing wrong? How can I fix this so that I can change the scale of certain axes on my shape?

    Thanks,
    Mahyar

  2. from enthought.tvtk.api import tvtk
    filename = “test.stl”
    stlr = tvtk.STLReader()
    stlr.file_name = file_name=filename
    stlr.update()
    stld = stlr.output

    from mayavi import mlab
    fig = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    surf = mlab.pipeline.surface(stld, opacity=1, color=(0, 1, 1))
    edge = mlab.pipeline.extract_edges(surf)
    edge_surf = mlab.pipeline.surface(edge, opacity=.1, color=(1,0,0))

    • Thanks very much Nick. Very elegant code. Good to know tvtk has a STL reader. Does it have a direct reader for DXF file? Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *