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

23 responses to “Binary STL File Reader in Python Powered by Numpy”

  1. […] with VTK and wxpython, got this basic app for loading and viewing SLT files. The GUI is wxpython, vtk provides the STL file […]

    Like

  2. […] seeing Sukhbinder’s implementation of reading STL files with Numpy I thought it would be a nice thing to have a simple […]

    Like

  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

    1. Hi Aman,

      Can you please share the stl? The code seems to work for the file that I have.

      Thanks

      Like

  4. Please tell me your mail ID so that I can share the file with you.
    Thanks

    Like

    1. 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

      1. 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

  5. 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

    1. Aman, all the nodes and vertex are present.

      You can save the data in text form by using numpy’s savetxt

      Or visualize P using matplotlib

      Like

      1. 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

      2. 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

      3. 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

  6. 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

  7. Hi Aman

    What is the size of the stl? I haven’t tested the code on a large model but should not be a problem if your system has enough RAM

    Thanks

    Like

  8. 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

    1. 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

  9. 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

    1. The code is not calculating normals, they are just what are coming from the stl file.

      Although I have not used them in any of my projects. I just simply discard them. So I cannot comment on normals.

      Hope this helps

      Like

      1. Yeah.. Thanks

        Like

  10. […] recent comment on the post titled binary stl file reader in numpy prompted me to revisit the code and while I was looking at it , I updated the same for code to view […]

    Like

Leave a comment

Trending