• Stars
    star
    607
  • Rank 73,353 (Top 2 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created almost 10 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple library to make working with STL files (and 3D objects in general) fast and easy.

numpy-stl

numpy-stl test status numpy-stl test status numpy-stl Pypi version numpy-stl code coverage

Simple library to make working with STL files (and 3D objects in general) fast and easy.

Due to all operations heavily relying on numpy this is one of the fastest STL editing libraries for Python available.

Security contact information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Issues

If you encounter any issues, make sure you report them here. Be sure to search for existing issues however. Many issues have been covered before. While this project uses numpy as it's main dependency, it is not in any way affiliated to the numpy project or the NumFocus organisation.

Links

Requirements for installing:

Installation:

pip install numpy-stl

Initial usage:

After installing the package, you should be able to run the following commands similar to how you can run pip.

$ stl2bin your_ascii_stl_file.stl new_binary_stl_file.stl
$ stl2ascii your_binary_stl_file.stl new_ascii_stl_file.stl
$ stl your_ascii_stl_file.stl new_binary_stl_file.stl

Contributing:

Contributions are always welcome. Please view the guidelines to get started: https://github.com/WoLpH/numpy-stl/blob/develop/CONTRIBUTING.rst

Quickstart

import numpy
from stl import mesh

# Using an existing stl file:
your_mesh = mesh.Mesh.from_file('some_file.stl')

# Or creating a new mesh (make sure not to overwrite the `mesh` import by
# naming it `mesh`):
VERTICE_COUNT = 100
data = numpy.zeros(VERTICE_COUNT, dtype=mesh.Mesh.dtype)
your_mesh = mesh.Mesh(data, remove_empty_areas=False)

# The mesh normals (calculated automatically)
your_mesh.normals
# The mesh vectors
your_mesh.v0, your_mesh.v1, your_mesh.v2
# Accessing individual points (concatenation of v0, v1 and v2 in triplets)
assert (your_mesh.points[0][0:3] == your_mesh.v0[0]).all()
assert (your_mesh.points[0][3:6] == your_mesh.v1[0]).all()
assert (your_mesh.points[0][6:9] == your_mesh.v2[0]).all()
assert (your_mesh.points[1][0:3] == your_mesh.v0[1]).all()

your_mesh.save('new_stl_file.stl')

Plotting using matplotlib is equally easy:

from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot

# Create a new plot
figure = pyplot.figure()
axes = figure.add_subplot(projection='3d')

# Load the STL files and add the vectors to the plot
your_mesh = mesh.Mesh.from_file('tests/stl_binary/HalfDonut.stl')
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))

# Auto scale to the mesh size
scale = your_mesh.points.flatten()
axes.auto_scale_xyz(scale, scale, scale)

# Show the plot to the screen
pyplot.show()

Experimental support for reading 3MF files

import pathlib
import stl

path = pathlib.Path('tests/3mf/Moon.3mf')

# Load the 3MF file
for m in stl.Mesh.from_3mf_file(path):
    # Do something with the mesh
    print('mesh', m)

Note that this is still experimental and may not work for all 3MF files. Additionally it only allows reading 3mf files, not writing them.

Modifying Mesh objects

from stl import mesh
import math
import numpy

# Create 3 faces of a cube
data = numpy.zeros(6, dtype=mesh.Mesh.dtype)

# Top of the cube
data['vectors'][0] = numpy.array([[0, 1, 1],
                                  [1, 0, 1],
                                  [0, 0, 1]])
data['vectors'][1] = numpy.array([[1, 0, 1],
                                  [0, 1, 1],
                                  [1, 1, 1]])
# Front face
data['vectors'][2] = numpy.array([[1, 0, 0],
                                  [1, 0, 1],
                                  [1, 1, 0]])
data['vectors'][3] = numpy.array([[1, 1, 1],
                                  [1, 0, 1],
                                  [1, 1, 0]])
# Left face
data['vectors'][4] = numpy.array([[0, 0, 0],
                                  [1, 0, 0],
                                  [1, 0, 1]])
data['vectors'][5] = numpy.array([[0, 0, 0],
                                  [0, 0, 1],
                                  [1, 0, 1]])

# Since the cube faces are from 0 to 1 we can move it to the middle by
# substracting .5
data['vectors'] -= .5

# Generate 4 different meshes so we can rotate them later
meshes = [mesh.Mesh(data.copy()) for _ in range(4)]

# Rotate 90 degrees over the Y axis
meshes[0].rotate([0.0, 0.5, 0.0], math.radians(90))

# Translate 2 points over the X axis
meshes[1].x += 2

# Rotate 90 degrees over the X axis
meshes[2].rotate([0.5, 0.0, 0.0], math.radians(90))
# Translate 2 points over the X and Y points
meshes[2].x += 2
meshes[2].y += 2

# Rotate 90 degrees over the X and Y axis
meshes[3].rotate([0.5, 0.0, 0.0], math.radians(90))
meshes[3].rotate([0.0, 0.5, 0.0], math.radians(90))
# Translate 2 points over the Y axis
meshes[3].y += 2


# Optionally render the rotated cube faces
from matplotlib import pyplot
from mpl_toolkits import mplot3d

# Create a new plot
figure = pyplot.figure()
axes = figure.add_subplot(projection='3d')

# Render the cube faces
for m in meshes:
    axes.add_collection3d(mplot3d.art3d.Poly3DCollection(m.vectors))

# Auto scale to the mesh size
scale = numpy.concatenate([m.points for m in meshes]).flatten()
axes.auto_scale_xyz(scale, scale, scale)

# Show the plot to the screen
pyplot.show()

Extending Mesh objects

from stl import mesh
import math
import numpy

# Create 3 faces of a cube
data = numpy.zeros(6, dtype=mesh.Mesh.dtype)

# Top of the cube
data['vectors'][0] = numpy.array([[0, 1, 1],
                                  [1, 0, 1],
                                  [0, 0, 1]])
data['vectors'][1] = numpy.array([[1, 0, 1],
                                  [0, 1, 1],
                                  [1, 1, 1]])
# Front face
data['vectors'][2] = numpy.array([[1, 0, 0],
                                  [1, 0, 1],
                                  [1, 1, 0]])
data['vectors'][3] = numpy.array([[1, 1, 1],
                                  [1, 0, 1],
                                  [1, 1, 0]])
# Left face
data['vectors'][4] = numpy.array([[0, 0, 0],
                                  [1, 0, 0],
                                  [1, 0, 1]])
data['vectors'][5] = numpy.array([[0, 0, 0],
                                  [0, 0, 1],
                                  [1, 0, 1]])

# Since the cube faces are from 0 to 1 we can move it to the middle by
# substracting .5
data['vectors'] -= .5

cube_back = mesh.Mesh(data.copy())
cube_front = mesh.Mesh(data.copy())

# Rotate 90 degrees over the X axis followed by the Y axis followed by the
# X axis
cube_back.rotate([0.5, 0.0, 0.0], math.radians(90))
cube_back.rotate([0.0, 0.5, 0.0], math.radians(90))
cube_back.rotate([0.5, 0.0, 0.0], math.radians(90))

cube = mesh.Mesh(numpy.concatenate([
    cube_back.data.copy(),
    cube_front.data.copy(),
]))

# Optionally render the rotated cube faces
from matplotlib import pyplot
from mpl_toolkits import mplot3d

# Create a new plot
figure = pyplot.figure()
axes = figure.add_subplot(projection='3d')

# Render the cube
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(cube.vectors))

# Auto scale to the mesh size
scale = cube_back.points.flatten()
axes.auto_scale_xyz(scale, scale, scale)

# Show the plot to the screen
pyplot.show()

Creating Mesh objects from a list of vertices and faces

import numpy as np
from stl import mesh

# Define the 8 vertices of the cube
vertices = np.array([\
    [-1, -1, -1],
    [+1, -1, -1],
    [+1, +1, -1],
    [-1, +1, -1],
    [-1, -1, +1],
    [+1, -1, +1],
    [+1, +1, +1],
    [-1, +1, +1]])
# Define the 12 triangles composing the cube
faces = np.array([\
    [0,3,1],
    [1,3,2],
    [0,4,7],
    [0,7,3],
    [4,5,6],
    [4,6,7],
    [5,1,2],
    [5,2,6],
    [2,3,6],
    [3,7,6],
    [0,1,5],
    [0,5,4]])

# Create the mesh
cube = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
for i, f in enumerate(faces):
    for j in range(3):
        cube.vectors[i][j] = vertices[f[j],:]

# Write the mesh to file "cube.stl"
cube.save('cube.stl')

Evaluating Mesh properties (Volume, Center of gravity, Inertia)

import numpy as np
from stl import mesh

# Using an existing closed stl file:
your_mesh = mesh.Mesh.from_file('some_file.stl')

volume, cog, inertia = your_mesh.get_mass_properties()
print("Volume                                  = {0}".format(volume))
print("Position of the center of gravity (COG) = {0}".format(cog))
print("Inertia matrix at expressed at the COG  = {0}".format(inertia[0,:]))
print("                                          {0}".format(inertia[1,:]))
print("                                          {0}".format(inertia[2,:]))

Combining multiple STL files

import math
import stl
from stl import mesh
import numpy


# find the max dimensions, so we can know the bounding box, getting the height,
# width, length (because these are the step size)...
def find_mins_maxs(obj):
    minx = obj.x.min()
    maxx = obj.x.max()
    miny = obj.y.min()
    maxy = obj.y.max()
    minz = obj.z.min()
    maxz = obj.z.max()
    return minx, maxx, miny, maxy, minz, maxz


def translate(_solid, step, padding, multiplier, axis):
    if 'x' == axis:
        items = 0, 3, 6
    elif 'y' == axis:
        items = 1, 4, 7
    elif 'z' == axis:
        items = 2, 5, 8
    else:
        raise RuntimeError('Unknown axis %r, expected x, y or z' % axis)

    # _solid.points.shape == [:, ((x, y, z), (x, y, z), (x, y, z))]
    _solid.points[:, items] += (step * multiplier) + (padding * multiplier)


def copy_obj(obj, dims, num_rows, num_cols, num_layers):
    w, l, h = dims
    copies = []
    for layer in range(num_layers):
        for row in range(num_rows):
            for col in range(num_cols):
                # skip the position where original being copied is
                if row == 0 and col == 0 and layer == 0:
                    continue
                _copy = mesh.Mesh(obj.data.copy())
                # pad the space between objects by 10% of the dimension being
                # translated
                if col != 0:
                    translate(_copy, w, w / 10., col, 'x')
                if row != 0:
                    translate(_copy, l, l / 10., row, 'y')
                if layer != 0:
                    translate(_copy, h, h / 10., layer, 'z')
                copies.append(_copy)
    return copies

# Using an existing stl file:
main_body = mesh.Mesh.from_file('ball_and_socket_simplified_-_main_body.stl')

# rotate along Y
main_body.rotate([0.0, 0.5, 0.0], math.radians(90))

minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(main_body)
w1 = maxx - minx
l1 = maxy - miny
h1 = maxz - minz
copies = copy_obj(main_body, (w1, l1, h1), 2, 2, 1)

# I wanted to add another related STL to the final STL
twist_lock = mesh.Mesh.from_file('ball_and_socket_simplified_-_twist_lock.stl')
minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(twist_lock)
w2 = maxx - minx
l2 = maxy - miny
h2 = maxz - minz
translate(twist_lock, w1, w1 / 10., 3, 'x')
copies2 = copy_obj(twist_lock, (w2, l2, h2), 2, 2, 1)
combined = mesh.Mesh(numpy.concatenate([main_body.data, twist_lock.data] +
                                    [copy.data for copy in copies] +
                                    [copy.data for copy in copies2]))

combined.save('combined.stl', mode=stl.Mode.ASCII)  # save as ASCII

Known limitations

  • When speedups are enabled the STL name is automatically converted to lowercase.

More Repositories

1

python-progressbar

Progressbar 2 - A progress bar for Python 2 and Python 3 - "pip install progressbar2"
Python
826
star
2

portalocker

An easy library for Python file locking. It works on Windows, Linux, BSD and Unix systems and can even perform distributed locking. Naturally it also supports the with statement.
Python
226
star
3

python-statsd

Python Client for the Etsy NodeJS Statsd Server
Python
106
star
4

alfred-converter

Alfred unit converter is a smart calculator for Alfred with support for unit conversions to make it a bit comparable to the Google Calculator and Wolfram Alpha.
Python
87
star
5

django-admin-generator

The Django Admin Generator automatically generates (scaffolds) a fully functioning Django admin by introspecting and querying your models
Python
86
star
6

mt940

A library to parse MT940 files and returns smart Python collections for statistics and manipulation.
Python
81
star
7

python-utils

Python Utils is a module with some convenient utilities not included with the standard Python install
Python
80
star
8

django-tags-input

django-tags-input
Python
67
star
9

django-statsd

Django Statsd library to track the page load times with Graphite
Python
63
star
10

pg_query_analyser

A PostgreSQL query analyzer written in C++. Mimicks the output of PgFouine but _much_ faster.
C++
54
star
11

django-utils

Django Utils is a collection of small Django helper functions and classes which make common patterns shorter and easier.
Python
31
star
12

mailjet

Mailjet API implementation in Python
Python
19
star
13

tissue

Tissue - automated pep8 checker for nose
Python
16
star
14

pyExcelerator

pyExcelerator fork with docs
Python
15
star
15

Cache-Debug-Toolbar

Django Cache Debug Toolbar for Redis, Memcache and PyLibMC
Python
13
star
16

python-formatter

A Python formatter based on the Python tokenize lib to ensure validity
Python
11
star
17

django-redis-admin

A Django Admin interface for Redis servers with optional Redis Sentinel support
Python
8
star
18

dotfiles

Wolph's dotfiles, in case you need tmux, zsh or vim example configurations
Shell
6
star
19

splitwise

Small implementation of the Splitwise API using Flask for importing transactions
JavaScript
5
star
20

python-project-tools

Python Project Tools is a package that makes developing and deploying proper Python packages easier
Python
5
star
21

zfs-utils-osx

A simple script to create and manage virtual ZFS images on OS X without requiring repartitioning
Python
5
star
22

dropbox-time-machine

An app that adds a time machine feature to Dropbox, instead of restoring per file you can simply jump back in time (before some idiot deleted all files for example).
Python
5
star
23

wollen-socks

Simple OpenVPN client Socks proxy server combination which supports both Surfshark and NordVPN currently
Shell
4
star
24

Mercury

Django SSI / ESI framework using NGINX and Memcached for static caching with user differentiated content
3
star
25

speedups

Python
3
star
26

django-minify

Python
3
star
27

django-tagging

A generic tagging application for Django projects, which allows association of a number of tags with any Model instance and makes retrieval of tags simple.
Python
3
star
28

trellozilla

Python
2
star
29

eventghost-domoticz

Domoticz plugin for EventGhost
Python
2
star
30

django-inlinetrans

Django Inlinetrans fork with Jinja, Transifex and Babel support
Python
2
star
31

github_difftools

A Chrome Extension to add diff checkboxes buttons to Github :)
JavaScript
2
star
32

sphinx-pypi-upload

This package contains a `setuptools`_ command for uploading `Sphinx`_ documentation to the `Python Package Index`_ (PyPI) at the dedicated URL packages.python.org.
Python
2
star
33

genetic_algorithm

A genetic algorithm implementation in Python for the Traveling Salesman Problem
Python
1
star
34

universal-syntax-highlighter

This userscript automatically adds syntax highlighting to a large amount of filetypes and in case of JSON also indents.
1
star
35

atmoorb-photon

AtmoOrb Particle Photon code
C++
1
star
36

launchy-ec2

EC2 Plugin for Launchy
Python
1
star
37

silk

Django Fabric Project to create a simple webinterface to deploy from Github/Bitbucket. NOTE, this project is currently a stub!
Python
1
star
38

silkproject

Python
1
star
39

supervisord-slack-notifier

Supervisord Slack Event Notifier
Python
1
star
40

dropbox

A fork of the official Dropbox API for better documentation
Python
1
star
41

learnvimscriptthehardway

HTML
1
star
42

Jukify

Webbased Spotify Jukebox written in Python
JavaScript
1
star
43

fping-exporter

Prometheus Exporter for fping
Python
1
star
44

xmlwriter

Python XML writer class inspired by the C# XmlWriter and the Django ORM
Python
1
star
45

tribler

Tribler is an open source peer-to-peer client with various features for watching videos online.
Python
1
star
46

userscript-disable-google-autocorrect

Redirects to "Did you mean" version of Google search instead of automatically correcting you.
JavaScript
1
star