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 = fp.read(80)
    nn = fp.read(4)
    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)
    fp.close()

    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

Advertisements

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

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

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

  3. Hi Sukhbinder,
    I am trying to run this .py file but I am not getting the desired output. I am expecting coordinates of vertices of all triangles in the stl file and then to get their normals. But, all I am getting is ‘Color’ ‘Material’, ‘Solid’
    Could you please help me in reading the stl file using python (no involvement of vtk)?
    Thanks a lot

    Like

    • Currently, I am getting this ouput via terminal.
      STLB ASM 218.00.00.0000 COLOR=��K�
      (2304, 3)
      I tried printing more output by editing BinarySTLReader.py file, I had included print p, n, v1, v2, v3 as well but since the number of output rows are 2304, it is not showing complete result.

      Like

      • HI Aman,

        Please check the variables p,n,v1,v2,v3 they all contain the information you need from the stl file.

        The first line is the Header, and there are 2304 nodes in the model.

        v1,v2,v3 contains the vertices of triangles. n contains the normal.

        Thanks
        S

        Like

  4. Hi Sukhbinder,
    When I’m trying to print vertices and normals I’m getting this output:
    [[ -40.15980148 -119.40090179 -1914.73425293]
    [ -46.90470123 -112.36460114 -1912.7019043 ]
    [ -40.24240112 -112.46640015 -1917.0390625 ]
    …,
    [ -60.00090027 -104.0161972 -1918.48144531]
    [ -62.26190186 -106.94989777 -1917.57678223]
    [ -52.31549835 -121.40570068 -1959.72424316]]

    Although there >=2000 nodes, I’m getting first three (first plane) and last last three (last plane).
    1) How to get all vertices-planes?
    2) How to get this output in a different txt file ?

    Like

      • Hi Sukhbinder,
        Could you please help me in using numpy.savetxt? I tried using
        numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=”, footer=”, comments=’# ‘)
        I’m getting this error
        “”””Traceback (most recent call last):
        File “C:\Python27\binarystlreader.py”, line 37, in
        numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=”, footer=”, comments=’# ‘)
        NameError: name ‘numpy’ is not defined “”””
        How can is this possible that when I’m typing import numpy in python IDLE or in the BinarySTLReader file, it is not working without showing any error (that should mean that numpy is installed) and when I’m using numpy.savetxt it is showing this error.
        I am beginner that’s why facing lot of problems. Hoping to get some help again.

        Like

      • Aman, use np.savetxt if you have imported numpy as np

        And before your proceed, please look at some tutorials for numpy, they will really help you more than anything.

        Like

      • Thank you so much Sukhbinder for your efforts and time 🙂
        Could you please give me some source of contact so that I can stay in touch with you?

        Like

  5. Hi Sukhbinder,
    Initially this code was working fine, then It started giving me error. I am facing memory error while using this code in ubuntu.
    And in windows, I am getting this error:
    Traceback (most recent call last):
    File “C:\Python27\binarystlreader.py”, line 33, in
    head,p,n,v1,v2,v3 = BinarySTL(fname)
    File “C:\Python27\binarystlreader.py”, line 17, in BinarySTL
    data = np.fromfile(fp , dtype = record_dtype , count =Numtri)
    ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size.
    Do you have any solution for this issue?

    Like

  6. Well, this stl contains 19000 rows and 3 columns, my windows task manager is showing enough free memory (system’s ram is 4gb). I don’t know what code to use for this file. Are you aware of this one? https://pypi.python.org/pypi/numpy-stl
    Please check the link of the stl file I have mentioned in one of my previous comments and try to work it out, if possible.

    Like

    • Hi Aman. Don’t know why you are getting the error. For me I am able to load the bent plate at file and am getting the correct results.

      I have now tested the code which has 1 lakh nodes and it works fine.

      Thanks

      Like

  7. Hi Sukhbinder,
    Your code is not giving correct values of normals. I tried breaking down my problem into simple by making a very simple cuboid stl with 20-30-40 as the dimension. While using your code, I was able to get the vertices correctly (as verified by https://pypi.python.org/pypi/numpy-stl code as well) but while calculating normals the values I’m getting are wrong (verified by doing cross product of the 3 vectors) (and also verified by https://pypi.python.org/pypi/numpy-stl code). What do you think?

    Like

  8. Pingback: Updated Binary STL File Reader | SukhbinderSingh.com

  9. Pingback: pythonODESTLRegult | 一人のデザイン

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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