Convert Figma logo to code with AI

mikedh logotrimesh

Python library for loading and using triangular meshes.

3,663
665
3,663
479

Top Related Projects

11,072

Point Cloud Library (PCL)

3,783

3D visualization and mesh analysis for science and engineering

2,044

Geometry Processing Library for Python

6,009

The public CGAL repository, see the README below

Quick Overview

Trimesh is a Python library for loading, manipulating, and analyzing 3D triangular meshes. It provides a wide range of functionality for working with 3D geometry, including mesh processing, collision detection, and path planning. Trimesh is designed to be efficient and easy to use, making it suitable for both research and practical applications.

Pros

  • Comprehensive set of tools for 3D mesh manipulation and analysis
  • Efficient implementation, suitable for large-scale mesh processing
  • Good integration with other scientific Python libraries (NumPy, SciPy)
  • Extensive documentation and examples

Cons

  • Steep learning curve for beginners in 3D geometry
  • Some advanced features may require additional dependencies
  • Limited support for non-triangular meshes
  • Performance can be slower compared to specialized C++ libraries for certain operations

Code Examples

Loading and visualizing a mesh:

import trimesh
import numpy as np

# Load a mesh from an STL file
mesh = trimesh.load('example.stl')

# Visualize the mesh
mesh.show()

Performing boolean operations:

# Create two simple meshes
sphere = trimesh.primitives.Sphere(radius=1.0)
box = trimesh.primitives.Box(extents=[2, 2, 2])

# Perform boolean intersection
intersection = trimesh.boolean.intersection([sphere, box])

# Visualize the result
intersection.show()

Computing mesh properties:

# Load a mesh
mesh = trimesh.load('example.obj')

# Compute various properties
print(f"Volume: {mesh.volume}")
print(f"Surface area: {mesh.area}")
print(f"Center of mass: {mesh.center_mass}")
print(f"Moment of inertia: {mesh.moment_inertia}")

Getting Started

To get started with Trimesh, follow these steps:

  1. Install Trimesh using pip:

    pip install trimesh[easy]
    
  2. Import the library in your Python script:

    import trimesh
    
  3. Load a mesh from a file or create a primitive shape:

    # Load from file
    mesh = trimesh.load('path/to/your/mesh.stl')
    
    # Or create a primitive
    sphere = trimesh.primitives.Sphere(radius=1.0)
    
  4. Start manipulating and analyzing your mesh:

    # Compute some properties
    print(f"Mesh volume: {mesh.volume}")
    print(f"Mesh surface area: {mesh.area}")
    
    # Visualize the mesh
    mesh.show()
    

Competitor Comparisons

11,072

Point Cloud Library (PCL)

Pros of PCL

  • Extensive functionality for point cloud processing, including advanced algorithms for segmentation, registration, and surface reconstruction
  • Large and active community, with extensive documentation and support
  • Optimized for performance, with GPU acceleration for certain operations

Cons of PCL

  • Steeper learning curve due to its complexity and extensive API
  • Heavier resource requirements, which may impact performance on less powerful systems
  • C++ based, which may be less accessible for users more comfortable with Python

Code Comparison

PCL (C++):

#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>

pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
pcl::VoxelGrid<pcl::PointXYZ> vg;
vg.setInputCloud (cloud);
vg.setLeafSize (0.01f, 0.01f, 0.01f);
vg.filter (*cloud_filtered);

Trimesh (Python):

import trimesh

mesh = trimesh.load('model.stl')
mesh = mesh.simplify_quadric_decimation(face_count=1000)
mesh.export('simplified_model.stl')
3,783

3D visualization and mesh analysis for science and engineering

Pros of PyVista

  • More comprehensive visualization capabilities, including 3D plotting and interactive rendering
  • Extensive documentation and examples for various use cases
  • Seamless integration with VTK for advanced visualization features

Cons of PyVista

  • Steeper learning curve due to its broader feature set
  • Larger dependency footprint, which may impact installation and deployment

Code Comparison

PyVista:

import pyvista as pv
mesh = pv.Sphere()
plotter = pv.Plotter()
plotter.add_mesh(mesh)
plotter.show()

Trimesh:

import trimesh
mesh = trimesh.creation.icosphere()
mesh.show()

Key Differences

  • PyVista focuses on scientific visualization and data analysis, while Trimesh specializes in 3D mesh processing and manipulation
  • PyVista offers more advanced plotting capabilities, whereas Trimesh excels in mesh operations and geometric computations
  • Trimesh has a lighter footprint and simpler API, making it easier to get started for basic mesh operations

Both libraries have their strengths, and the choice between them depends on the specific requirements of your project. PyVista is better suited for complex visualizations and data analysis, while Trimesh is ideal for efficient mesh processing and manipulation tasks.

2,044

Geometry Processing Library for Python

Pros of PyMesh

  • More comprehensive geometry processing capabilities, including advanced mesh operations and boolean operations
  • Supports a wider range of file formats for import and export
  • Provides bindings to external libraries for additional functionality

Cons of PyMesh

  • Steeper learning curve due to more complex API
  • Less active development and community support
  • Requires compilation and external dependencies, making installation more challenging

Code Comparison

PyMesh:

import pymesh
mesh = pymesh.load_mesh("input.obj")
mesh = pymesh.subdivide(mesh, order=1)
pymesh.save_mesh("output.obj", mesh)

Trimesh:

import trimesh
mesh = trimesh.load("input.obj")
mesh = mesh.subdivide()
mesh.export("output.obj")

Key Differences

  • PyMesh offers more advanced geometry processing features but has a steeper learning curve
  • Trimesh is easier to install and use, with a more Pythonic API
  • PyMesh supports more file formats, while Trimesh focuses on common formats
  • Trimesh has more active development and community support
  • PyMesh provides bindings to external libraries, while Trimesh is more self-contained

Both libraries have their strengths, and the choice depends on specific project requirements and user preferences.

6,009

The public CGAL repository, see the README below

Pros of CGAL

  • More comprehensive and feature-rich library for computational geometry
  • Supports a wider range of geometric algorithms and data structures
  • Better suited for complex geometric computations and research applications

Cons of CGAL

  • Steeper learning curve due to its complexity and extensive API
  • Heavier and slower to compile compared to Trimesh
  • Less focused on 3D mesh processing specifically

Code Comparison

CGAL example (C++):

#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_3.h>

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Delaunay_triangulation_3<K> Delaunay;

Trimesh example (Python):

import trimesh

mesh = trimesh.load('model.stl')
convex_hull = mesh.convex_hull

CGAL offers a more low-level, C++ based approach with fine-grained control over geometric operations, while Trimesh provides a higher-level, Python-based interface focused on 3D mesh manipulation.

Trimesh is more accessible for quick 3D mesh operations and analysis, whereas CGAL is better suited for advanced geometric computations and algorithm development. The choice between the two depends on the specific requirements of the project and the user's familiarity with the respective programming languages and APIs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

trimesh


Github Actions coverage Docker Image Version (latest by date) PyPI version

Trimesh is a pure Python 3.10+ library for loading and using triangular meshes with an emphasis on watertight surfaces. The goal of the library is to provide a full featured and well tested Trimesh object which allows for easy manipulation and analysis, in the style of the Polygon object in the Shapely library.

The API is mostly stable, but this should not be relied on and is not guaranteed: install a specific version if you plan on deploying something using trimesh.

Pull requests are appreciated and responded to promptly! If you'd like to contribute, here a quick development and contributing guide.

Basic Installation

Keeping trimesh easy to install is a core goal, thus the only hard dependency is numpy. Installing other packages adds functionality but is not required. For the easiest install with just numpy:

pip install trimesh

The minimal install can load many supported formats (STL, PLY, OBJ, GLTF/GLB) into numpy.ndarray values. More functionality is available when soft dependencies are installed, including convex hulls (scipy), graph operations (networkx), fast ray queries (embreex), vector path handling (shapely and rtree), XML formats like 3DXML/XAML/3MF (lxml), preview windows (pyglet), faster cache checks (xxhash), etc.

To install trimesh with the soft dependencies that generally install cleanly from binaries on Linux x86_64, MacOS ARM, and Windows x86_64 using pip:

pip install trimesh[easy]

If you are supporting a different platform or are freezing dependencies for an application we recommend you do not use extras, i.e. depend on trimesh scipy versus trimesh[easy]. Further information is available in the advanced installation documentation.

Quick Start

Here is an example of loading a mesh from file and colorizing its faces (nicely formatted notebook version of this example.

import numpy as np
import trimesh

# attach to logger so trimesh messages will be printed to console
trimesh.util.attach_to_log()

# mesh objects can be created from existing faces and vertex data
mesh = trimesh.Trimesh(vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]],
                       faces=[[0, 1, 2]])

# by default, Trimesh will do a light processing, which will
# remove any NaN values and merge vertices that share position
# if you want to not do this on load, you can pass `process=False`
mesh = trimesh.Trimesh(vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]],
                       faces=[[0, 1, 2]],
                       process=False)

# some formats like `glb` represent multiple meshes with multiple instances
# and `load_mesh` will concatenate irreversibly, load it as a Scene
# if you need instance information:
#   `scene = trimesh.load_scene('models/CesiumMilkTruck.glb')`
mesh = trimesh.load_mesh('models/CesiumMilkTruck.glb')

# is the current mesh watertight?
mesh.is_watertight

# what's the euler number for the mesh?
mesh.euler_number

# the convex hull is another Trimesh object that is available as a property
# lets compare the volume of our mesh with the volume of its convex hull
print(mesh.volume / mesh.convex_hull.volume)

# since the mesh is watertight it means there is a volume
# with a center of mass calculated from a surface integral approach
# which we can set as the origin for our mesh. It's perfectly fine to
# alter the vertices directly:
#   mesh.vertices -= mesh.center_mass
# although this will completely clear the cache including face normals
# as we don't know that they're still valid. Using the translation
# method will try to save cached values that are still valid:
mesh.apply_translation(-mesh.center_mass)


# what's the (3, 3) moment of inertia for the mesh?
mesh.moment_inertia

# if there are multiple bodies in the mesh we can split the mesh by
# connected components of face adjacency
# since this example mesh is a single watertight body we get a list of one mesh
mesh.split()

# facets are groups of coplanar adjacent faces
# set each facet to a random color
# colors are 8 bit RGBA by default (n, 4) np.uint8
for facet in mesh.facets:
    mesh.visual.face_colors[facet] = trimesh.visual.random_color()

# preview mesh in an opengl window if you installed pyglet and scipy with pip
mesh.show()

# transform method can be passed a (4, 4) matrix and will cleanly apply the transform
mesh.apply_transform(trimesh.transformations.random_rotation_matrix())

# axis aligned bounding box is available
mesh.bounding_box.extents

# a minimum volume oriented bounding box also available
# primitives are subclasses of Trimesh objects which automatically generate
# faces and vertices from data stored in the 'primitive' attribute
mesh.bounding_box_oriented.primitive.extents
mesh.bounding_box_oriented.primitive.transform

# show the mesh appended with its oriented bounding box
# the bounding box is a trimesh.primitives.Box object, which subclasses
# Trimesh and lazily evaluates to fill in vertices and faces when requested
# (press w in viewer to see triangles)
(mesh + mesh.bounding_box_oriented).show()

# bounding spheres and bounding cylinders of meshes are also
# available, and will be the minimum volume version of each
# except in certain degenerate cases, where they will be no worse
# than a least squares fit version of the primitive.
print(mesh.bounding_box_oriented.volume,
      mesh.bounding_cylinder.volume,
      mesh.bounding_sphere.volume)

Features

  • Import meshes from binary/ASCII STL, Wavefront OBJ, ASCII OFF, binary/ASCII PLY, GLTF/GLB 2.0, 3MF, XAML, 3DXML, etc.
  • Export meshes as GLB/GLTF, binary STL, binary PLY, ASCII OFF, OBJ, COLLADA, etc.
  • Import and export 2D or 3D vector paths with DXF or SVG files
  • Preview meshes using an OpenGL pyglet window, or in-line in jupyter or marimo notebooks using three.js
  • Automatic hashing from a subclassed numpy array for change tracking using MD5, zlib CRC, or xxhash, and internal caching of expensive values.
  • Calculate face adjacencies, face angles, vertex defects, convex hulls, etc.
  • Calculate cross sections for a 2D outline, or slice a mesh for a 3D remainder mesh, i.e. slicing for 3D-printing.
  • Split mesh based on face connectivity using networkx, or scipy.sparse
  • Calculate mass properties, including volume, center of mass, moment of inertia, principal components of inertia, etc.
  • Repair simple problems with triangle winding, normals, and quad/triangle holes
  • Compute rotation/translation/tessellation invariant identifier and find duplicate meshes
  • Check if a mesh is watertight, convex, etc.
  • Sample the surface of a mesh
  • Ray-mesh queries including location, triangle index, etc.
  • Boolean operations on meshes (intersection, union, difference) using Manifold3D or Blender.
  • Voxelize watertight meshes
  • Smooth watertight meshes using Laplacian smoothing algorithms (Classic, Taubin, Humphrey)
  • Subdivide faces of a mesh
  • Approximate minimum volume oriented bounding boxes and spheres for meshes.
  • Calculate nearest point on mesh surface and signed distance
  • Primitive objects (Box, Cylinder, Sphere, Extrusion) which are subclassed Trimesh objects and have all the same features (inertia, viewers, etc)
  • Simple scene graph and transform tree which can be rendered (pyglet window, three.js in a jupyter/marimo notebook or exported.
  • Many utility functions, like transforming points, unitizing vectors, aligning vectors, tracking numpy arrays for changes, grouping rows, etc.

Additional Notes

  • Check out some cool stuff people have done in the GitHub network.
  • Generally trimesh API changes should have a one-year period of printing a warnings.DeprecationWarning although that's not always possible (i.e. the pyglet2 viewer rewrite that's been back-burnered for several years.)
  • Docker containers are available on Docker Hub as trimesh/trimesh and there's a container guide in the docs.
  • If you're choosing which format to use, you may want to try GLB as a fast modern option.