Library to make reading, writing and modifying both binary and ascii STL files easy.
npx @tessl/cli install tessl/pypi-numpy-stl@3.2.0A high-performance Python library for reading, writing, and manipulating STL (STereoLithography) files. NumPy STL leverages NumPy for fast operations on 3D mesh data, enabling efficient processing of both binary and ASCII STL file formats with comprehensive mesh manipulation capabilities.
pip install numpy-stlnumpy, python-utils>=3.4.5from stl import meshAccess to enums and constants:
from stl import Mesh, Mode, Dimension, RemoveDuplicatesimport numpy as np
from stl import mesh
# Load an existing STL file
your_mesh = mesh.Mesh.from_file('model.stl')
# Create a new mesh from scratch
TRIANGLE_COUNT = 100
data = np.zeros(TRIANGLE_COUNT, dtype=mesh.Mesh.dtype)
your_mesh = mesh.Mesh(data, remove_empty_areas=False)
# Access mesh properties
print(f"Triangle count: {len(your_mesh)}")
print(f"Volume: {your_mesh.get_mass_properties()[0]}")
# Access mesh data
normals = your_mesh.normals # Triangle normal vectors (Nx3)
vertices = your_mesh.vectors # Triangle vertices (Nx3x3)
v0, v1, v2 = your_mesh.v0, your_mesh.v1, your_mesh.v2 # Individual vertex arrays
# Transform the mesh
your_mesh.translate([1.0, 2.0, 3.0]) # Move by offset
your_mesh.rotate([0, 0, 1], np.pi/4) # Rotate 45° around Z-axis
# Save the mesh
your_mesh.save('output.stl')NumPy STL is built around NumPy structured arrays for efficient mesh data storage and manipulation:
The library supports both Cython extensions for performance-critical operations and pure Python fallbacks, with automatic format detection for STL files and comprehensive geometric calculations including volume, center of gravity, and inertia tensors.
Load, save, and convert STL files with support for both ASCII and binary formats, automatic format detection, and multi-file operations.
def Mesh.from_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs): ...
def save(self, filename, fh=None, mode=Mode.AUTOMATIC, update_normals=True): ...
def Mesh.from_multi_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs): ...
def Mesh.from_files(filenames, calculate_normals=True, mode=Mode.AUTOMATIC, speedups=True, **kwargs): ...
def Mesh.from_3mf_file(filename, calculate_normals=True, **kwargs): ...Calculate geometric properties including volume, surface area, center of gravity, inertia tensors, and mesh validation.
def get_mass_properties(self): ...
def get_mass_properties_with_density(self, density): ...
def update_areas(self, normals=None): ...
def update_centroids(self): ...
def is_closed(self, exact=False): ...
def check(self, exact=False): ...Transform meshes through rotation, translation, and general 4x4 transformation matrices with support for rotation around arbitrary axes and points.
def rotate(self, axis, theta=0, point=None): ...
def rotate_using_matrix(self, rotation_matrix, point=None): ...
def translate(self, translation): ...
def transform(self, matrix): ...
def rotation_matrix(cls, axis, theta): ...Access and modify mesh data through convenient properties and array interfaces with support for both vertex-based and coordinate-based operations.
@property
def vectors(self): ...
@property
def normals(self): ...
@property
def v0(self): ...
@property
def v1(self): ...
@property
def v2(self): ...
@property
def x(self): ...
@property
def y(self): ...
@property
def z(self): ...Clean and process mesh data including duplicate removal, empty area elimination, and normal vector calculations.
def update_normals(self, update_areas=True, update_centroids=True): ...
def get_unit_normals(self): ...
def remove_duplicate_polygons(cls, data, value=RemoveDuplicates.SINGLE): ...
def remove_empty_areas(cls, data): ...class Mesh(BaseStl):
"""
Primary mesh class for STL file manipulation.
Attributes:
data: numpy.array - Structured array containing mesh data
name: str - Mesh name
speedups: bool - Whether to use Cython optimizations
"""
class Mode(enum.IntEnum):
"""STL file read/write modes."""
AUTOMATIC = 0 # Auto-detect based on TTY
ASCII = 1 # Force ASCII format
BINARY = 2 # Force binary format
class Dimension(enum.IntEnum):
"""Axis indices for vector access."""
X = 0 # X-axis index
Y = 1 # Y-axis index
Z = 2 # Z-axis index
class RemoveDuplicates(enum.Enum):
"""Duplicate triangle handling options."""
NONE = 0 # Keep all duplicates
SINGLE = 1 # Keep only one copy
ALL = 2 # Remove all including originals
# NumPy data type for mesh storage
dtype = np.dtype([
('normals', np.float32, (3,)), # Triangle normal vectors
('vectors', np.float32, (3, 3)), # Triangle vertices
('attr', np.uint16, (1,)), # Triangle attributes
])BUFFER_SIZE: int = 4096 # Buffer size for file reading
HEADER_SIZE: int = 80 # STL header field size in bytes
COUNT_SIZE: int = 4 # Triangle count field size in bytes
MAX_COUNT: float = 1e8 # Maximum number of triangles
HEADER_FORMAT: str = '{package_name} ({version}) {now} {name}' # STL header format template
# Backward compatibility constants
AUTOMATIC: int = 0 # Alias for Mode.AUTOMATIC
ASCII: int = 1 # Alias for Mode.ASCII
BINARY: int = 2 # Alias for Mode.BINARY
X: int = 0 # Alias for Dimension.X
Y: int = 1 # Alias for Dimension.Y
Z: int = 2 # Alias for Dimension.ZNumPy STL provides console commands for STL file format conversion:
# Convert STL files (auto-detects format)
stl input.stl output.stl
# Force ASCII output
stl2ascii binary_model.stl ascii_model.stl
# Force binary output
stl2bin ascii_model.stl binary_model.stl
# Common options for all commands
stl --help # Show help
stl input.stl output.stl --name "MyMesh" # Set mesh name
stl input.stl output.stl -r # Remove empty areas
stl input.stl output.stl -s # Disable speedups