numpy-stl

3.2.0 · active · verified Thu Apr 16

Numpy-stl is a Python library designed to simplify reading, writing, and modifying both binary and ASCII STL (stereolithography) files. Leveraging NumPy, it offers fast and efficient operations for 3D object manipulation. The library is currently at version 3.2.0, with regular updates that include bug fixes, new features, and compatibility enhancements for its core dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple cube mesh from vertices and faces and save it to an STL file. It also shows how to load an existing STL file and access some of its properties like the number of triangles and volume. The example includes creating a dummy file if one doesn't exist to ensure the loading part is runnable.

import numpy as np
from stl import mesh
import os

# --- Create a new mesh from scratch ---

# Define the 8 vertices of the cube
vertices = np.array([
    [-1, -1, -1], [+1, -1, -1], [+1, +1, -1], [-1, +1, -1], # Bottom square
    [-1, -1, +1], [+1, -1, +1], [+1, +1, +1], [-1, +1, +1]  # Top square
])

# Define the 12 triangles (faces) composing the cube
faces = np.array([
    [0,3,1], [1,3,2], # Bottom
    [0,4,7], [0,7,3], # Front-left
    [4,5,6], [4,6,7], # Top
    [5,1,2], [5,2,6], # Back-right
    [2,3,6], [3,7,6], # Top-right
    [0,1,5], [0,5,4]  # Bottom-left
])

# Create the mesh object
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],:]

# Save the mesh to a file
output_filename = 'new_cube.stl'
cube.save(output_filename)
print(f"Saved new mesh to {output_filename}")

# --- Load an existing STL file ---
# Create a dummy file for demonstration if it doesn't exist
if not os.path.exists('example.stl'):
    # In a real scenario, 'example.stl' would be an existing file.
    # For this quickstart, we'll save the cube we just created as 'example.stl'
    # just to demonstrate loading.
    cube.save('example.stl')

try:
    your_mesh = mesh.Mesh.from_file('example.stl')
    print(f"Successfully loaded mesh from example.stl with {len(your_mesh.vectors)} triangles.")
    # Access mesh properties
    print(f"Volume: {your_mesh.get_mass_properties()[0]:.2f}")
except Exception as e:
    print(f"Could not load example.stl: {e}")

view raw JSON →