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
Leave a comment