Binary STL File Reader in Python Powered by Numpy

Binary STL file Reader in Python
At the STL and Fortran post Don Durschmidt asked if the stl binary reader fortran code can be made faster for reading big files.

As Abraham Maslow said “To a man with a hammer, everything looks like a nail” Likewise to an Engineer smitten by python, everything is pythonable.

So while exploring and thinking about the problem, I wrote this python version of STL binary file reader powered by numpy. Haven’t check the speed, I am sure its going to fail the speed test compared to fortran code but having a python version opens up whole new possibilities to play with the data. I think Don will agree.

Now back to the fortran binary stl file reader.

# -*- coding: utf-8 -*-
Created on Thu Nov 19 06:37:35 2013

@author: Sukhbinder Singh

Reads a Binary file and 
Returns Header,Points,Normals,Vertex1,Vertex2,Vertex3

import numpy as np
from struct import unpack

def BinarySTL(fname):
    fp = open(fname, 'rb')
    Header =
    nn =
    Numtri = unpack('i', nn)[0]
    #print nn
    record_dtype = np.dtype([
                   ('normals', np.float32,(3,)),  
                   ('Vertex1', np.float32,(3,)),
                   ('Vertex2', np.float32,(3,)),
                   ('Vertex3', np.float32,(3,)) ,              
                   ('atttr', '<i2',(1,) )
    data = np.fromfile(fp , dtype = record_dtype , count =Numtri)

    Normals = data['normals']
    Vertex1= data['Vertex1']
    Vertex2= data['Vertex2']
    Vertex3= data['Vertex3']

    p = np.append(Vertex1,Vertex2,axis=0)
    p = np.append(p,Vertex3,axis=0) #list(v1)
    Points =np.array(list(set(tuple(p1) for p1 in p)))
    return Header,Points,Normals,Vertex1,Vertex2,Vertex3
if __name__ == '__main__':
    fname = "ship.stl" # "porsche.stl"
    head,p,n,v1,v2,v3 = BinarySTL(fname)
    print head
    print p.shape

Get from github

3 thoughts on “Binary STL File Reader in Python Powered by Numpy

  1. Pingback: SLT Viewer – a VTK and wxpython powered App |

  2. Pingback: Reading and writing binary STL files with Numpy | Wolph

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s