Reading and writing binary STL files with Numpy

I’ve since written a library to replace this script and add more functionality such as reading/writing both binary and ascii STL files. See the blog post here

After seeing Sukhbinder’s implementation of reading STL files with Numpy I thought it would be a nice thing to have a simple STL class to both read and write the binary files.

[python]
import struct
import numpy

class Stl(object):
dtype = numpy.dtype([
(‘normals’, numpy.float32, (3, )),
(‘v0’, numpy.float32, (3, )),
(‘v1’, numpy.float32, (3, )),
(‘v2’, numpy.float32, (3, )),
(‘attr’, ‘u2′, (1, )),
])

def __init__(self, header, data):
self.header = header
self.data = data

@classmethod
def from_file(cls, filename, mode=’rb’):
with open(filename, mode) as fh:
header = fh.read(80)
size, = struct.unpack(‘@i’, fh.read(4))
data = numpy.fromfile(fh, dtype=cls.dtype, count=size)
return Stl(header, data)

def to_file(self, filename, mode=’wb’):
with open(filename, mode) as fh:
fh.write(self.header)
fh.write(struct.pack(‘@i’, self.data.size))
self.data.tofile(fh)

if __name__ == ‘__main__’:
# Read from STL file
stl = Stl.from_file(‘test.stl’)

# Increment the X axis by one
stl.data[‘v0’][:, 0] += 1
stl.data[‘v1’][:, 0] += 1
stl.data[‘v2’][:, 0] += 1

# Write back to file
stl.to_file(‘test.stl’)
[/python]

Bookmark and Share

Tags:

About Rick van Hattem

Rick van Hattem is a Dutch Internet entrepreneur and co-founder of Fashiolista.com

2 Responses to “Reading and writing binary STL files with Numpy”

  1. Sukhbinder | 2014-10-20 at 16:51:44 #

    Nice Rick!!! Makes the code more useful and thanks for putting it on pypi https://pypi.python.org/pypi/numpy-stl/1.1.2 Wow why didn’t i think of it… Cheers!!

Trackbacks/Pingbacks

  1. Reading/writing 3D STL files with numpy-stl | Wolph - 2015-06-09

    […] a followup of my earlier article about reading and writing STL files with Numpy, I’ve created a library that can be used […]

Leave a Reply