or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-access.mdfile-operations.mdindex.mdmesh-analysis.mdmesh-processing.mdtransformations.md
tile.json

tessl/pypi-numpy-stl

Library to make reading, writing and modifying both binary and ascii STL files easy.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/numpy-stl@3.2.x

To install, run

npx @tessl/cli install tessl/pypi-numpy-stl@3.2.0

index.mddocs/

NumPy STL

A 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.

Package Information

  • Package Name: numpy-stl
  • Language: Python
  • Installation: pip install numpy-stl
  • Dependencies: numpy, python-utils>=3.4.5

Core Imports

from stl import mesh

Access to enums and constants:

from stl import Mesh, Mode, Dimension, RemoveDuplicates

Basic Usage

import 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')

Architecture

NumPy STL is built around NumPy structured arrays for efficient mesh data storage and manipulation:

  • Mesh: Primary interface inheriting from BaseStl for file I/O operations
  • BaseMesh: Core mesh data structure and geometric operations
  • BaseStl: STL file format reading/writing with automatic format detection
  • Structured Data Type: NumPy dtype with normals, vectors, and attributes for efficient memory layout

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.

Capabilities

File Operations

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): ...

File Operations

Mesh Properties and Analysis

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): ...

Mesh Analysis

Geometric Transformations

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): ...

Transformations

Mesh Data Access

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): ...

Data Access

Mesh Processing

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): ...

Mesh Processing

Types

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
])

Constants

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.Z

Command Line Tools

NumPy STL provides console commands for STL file format conversion:

  • stl: Convert between ASCII and binary STL formats with automatic detection
  • stl2ascii: Convert STL files to ASCII (text) format
  • stl2bin: Convert STL files to binary format
# 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