https://github.com/wolph/numpy-stl

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

https://github.com/wolph/numpy-stl

Science Score: 36.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
    2 of 27 committers (7.4%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (16.1%) to scientific vocabulary

Keywords

3d fast high-performance numpy python python2 python3 stl

Keywords from Contributors

mesh pypi optimizing-compiler mathematics simulator circuit finite-elements notebook pip vtk
Last synced: 6 months ago · JSON representation

Repository

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

Basic Info
Statistics
  • Stars: 662
  • Watchers: 33
  • Forks: 110
  • Open Issues: 0
  • Releases: 29
Topics
3d fast high-performance numpy python python2 python3 stl
Created over 11 years ago · Last pushed 10 months ago
Metadata Files
Readme Contributing Funding License Security

README.rst

numpy-stl
==============================================================================

.. image:: https://github.com/WoLpH/numpy-stl/actions/workflows/main.yml/badge.svg?branch=master
    :alt: numpy-stl test status 
    :target: https://github.com/WoLpH/numpy-stl/actions/workflows/main.yml

.. image:: https://ci.appveyor.com/api/projects/status/cbv7ak2i59wf3lpj?svg=true
    :alt: numpy-stl test status 
    :target: https://ci.appveyor.com/project/WoLpH/numpy-stl

.. image:: https://badge.fury.io/py/numpy-stl.svg
    :alt: numpy-stl Pypi version 
    :target: https://pypi.python.org/pypi/numpy-stl

.. image:: https://coveralls.io/repos/WoLpH/numpy-stl/badge.svg?branch=master
    :alt: numpy-stl code coverage 
    :target: https://coveralls.io/r/WoLpH/numpy-stl?branch=master

.. image:: https://img.shields.io/pypi/pyversions/numpy-stl.svg

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

 - The source: https://github.com/WoLpH/numpy-stl
 - Project page: https://pypi.python.org/pypi/numpy-stl
 - Reporting bugs: https://github.com/WoLpH/numpy-stl/issues
 - Documentation: http://numpy-stl.readthedocs.org/en/latest/
 - My blog: https://wol.ph/

Requirements for installing:
------------------------------------------------------------------------------

 - `numpy`_ any recent version
 - `python-utils`_ version 1.6 or greater

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

.. code-block:: shell
 
   $ 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
------------------------------------------------------------------------------

.. code-block:: python

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

.. code-block:: python

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

.. _numpy: http://numpy.org/
.. _matplotlib: http://matplotlib.org/
.. _python-utils: https://github.com/WoLpH/python-utils

Experimental support for reading 3MF files
------------------------------------------------------------------------------

.. code-block:: python

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

.. code-block:: python

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

.. code-block:: python

    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 a single triangle
----------------------------------

.. code-block:: python

    import numpy
    from stl import mesh

    # A unit triangle
    tri_vectors = [[0,0,0],[0,1,0],[0,0,1]]

    # Create the vector data. It’s a numpy structured array with N entries, where N is the number of triangles (here N=1), and each entry is in the format ('normals','vectors','attr')
    data = numpy.array([(
        0, # Set 'normals' to zero, and the mesh class will automatically calculate them at initialization
        tri_vectors, # 'vectors'
        0 # 'attr'
    )], dtype = mesh.Mesh.dtype) # The structure defined by the mesh class (N x ('normals','vectors','attr'))

    # Create the mesh object from the structured array
    tri_mesh = mesh.Mesh(data)

    # Optionally make a plot for fun
    # Load the plot tools
    from matplotlib import pyplot
    from mpl_toolkits import mplot3d

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

    # Add mesh to plot
    axes.add_collection3d(mplot3d.art3d.Poly3DCollection(tri_mesh.vectors)) # Just need the 'vectors' attribute for display

Creating Mesh objects from a list of vertices and faces
------------------------------------------------------------------------------

.. code-block:: python

    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, Convexity)
------------------------------------------------------------------------------

.. code-block:: python

    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,:]))
    print("Your mesh is convex: {0}".format(your_mesh.is_convex()))
Combining multiple STL files
------------------------------------------------------------------------------

.. code-block:: python

    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.

Owner

  • Name: Rick van Hattem
  • Login: wolph
  • Kind: user
  • Location: Amsterdam

Author of @mastering-python and entrepreneur interested in scaling large and complicated systems.

GitHub Events

Total
  • Create event: 1
  • Release event: 1
  • Issues event: 8
  • Watch event: 36
  • Issue comment event: 28
  • Push event: 12
  • Pull request event: 11
  • Fork event: 5
Last Year
  • Create event: 1
  • Release event: 1
  • Issues event: 8
  • Watch event: 36
  • Issue comment event: 28
  • Push event: 12
  • Pull request event: 11
  • Fork event: 5

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 460
  • Total Committers: 27
  • Avg Commits per committer: 17.037
  • Development Distribution Score (DDS): 0.248
Past Year
  • Commits: 22
  • Committers: 7
  • Avg Commits per committer: 3.143
  • Development Distribution Score (DDS): 0.455
Top Committers
Name Email Commits
Rick van Hattem W****h@w****h 346
Guillaume Jacquenot g****t@g****m 33
Ilya V n****s@g****m 28
Miro Hrončok m****o@h****z 15
Nicholas Won d****7@g****m 7
arthurlovekin a****n@g****m 5
Nick Cloward n****k@a****m 2
Hongbo Miao H****o@o****m 2
Håkon Strandenes h****s@k****o 2
Jean-Benoist Leger j****r@h****r 2
bwoodsend b****d@g****m 2
Laszlo Molnar l****o@l****n 1
Andrew Lock 6****k 1
Christian Sachs s****n@g****m 1
Elijah Andrews e****5@s****k 1
JBil8 j****o@e****h 1
James Archer j****r@h****m 1
Jeff Olander 5****I 1
Jorge 4****f 1
Karl Nilsson k****n@g****m 1
Michal Suchanek m****k@s****e 1
Oscar Gustafsson o****n@g****m 1
Thomas BAUDIER t****r@c****r 1
ZhaoKang k****g@s****m 1
loicgasser l****4@g****m 1
mamrehn m****n 1
pyup-bot g****t@p****o 1

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 99
  • Total pull requests: 24
  • Average time to close issues: 4 months
  • Average time to close pull requests: 17 days
  • Total issue authors: 92
  • Total pull request authors: 18
  • Average comments per issue: 3.46
  • Average comments per pull request: 3.21
  • Merged pull requests: 19
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 3
  • Pull requests: 8
  • Average time to close issues: 27 days
  • Average time to close pull requests: 13 days
  • Issue authors: 3
  • Pull request authors: 5
  • Average comments per issue: 5.0
  • Average comments per pull request: 1.5
  • Merged pull requests: 7
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • nilswagner (3)
  • agen49 (2)
  • VeiledTee (2)
  • bwoodsend (2)
  • omerenen (2)
  • rasunag27 (2)
  • nickc92 (1)
  • andreasbuhr (1)
  • diazGT94 (1)
  • snowbugxs (1)
  • DriesAllaerts (1)
  • Occupied-Observer (1)
  • yellowshippo (1)
  • luoyu-123 (1)
  • michpaulatto (1)
Pull Request Authors
  • JeffreyOI (4)
  • hakostra (2)
  • bwoodsend (2)
  • andrewjlock (2)
  • JBil8 (2)
  • arthurlovekin (2)
  • hroncok (2)
  • hramrach (2)
  • Gjacquenot (1)
  • oscargus (1)
  • James-Archer (1)
  • karl-nilsson (1)
  • Skhawule (1)
  • Xorgon (1)
  • jorgectf (1)
Top Labels
Issue Labels
no-activity (17) Stale (17) in progress (2) help wanted (1) bug (1)
Pull Request Labels

Packages

  • Total packages: 4
  • Total downloads:
    • pypi 147,645 last-month
  • Total docker downloads: 1,341
  • Total dependent packages: 62
    (may contain duplicates)
  • Total dependent repositories: 344
    (may contain duplicates)
  • Total versions: 101
  • Total maintainers: 2
pypi.org: numpy-stl

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

  • Versions: 69
  • Dependent Packages: 55
  • Dependent Repositories: 339
  • Downloads: 147,645 Last month
  • Docker Downloads: 1,341
Rankings
Dependent packages count: 0.4%
Dependent repos count: 0.8%
Downloads: 1.4%
Average: 2.0%
Docker downloads count: 2.0%
Stargazers count: 2.7%
Forks count: 4.6%
Maintainers (1)
Last synced: 6 months ago
alpine-edge: py3-numpy-stl-pyc

Precompiled Python bytecode for py3-numpy-stl

  • Versions: 5
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent repos count: 0.0%
Average: 9.3%
Dependent packages count: 12.3%
Forks count: 12.3%
Stargazers count: 12.5%
Maintainers (1)
Last synced: 6 months ago
alpine-edge: py3-numpy-stl

Library for working with STLs

  • Versions: 7
  • Dependent Packages: 2
  • Dependent Repositories: 0
Rankings
Dependent repos count: 0.0%
Average: 9.9%
Forks count: 12.4%
Stargazers count: 12.6%
Dependent packages count: 14.6%
Maintainers (1)
Last synced: 6 months ago
conda-forge.org: numpy-stl

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.

  • Versions: 20
  • Dependent Packages: 5
  • Dependent Repositories: 5
Rankings
Dependent packages count: 10.4%
Dependent repos count: 14.8%
Average: 15.3%
Stargazers count: 17.3%
Forks count: 18.8%
Last synced: 7 months ago

Dependencies

docs/requirements.txt pypi
  • mock *
  • python-utils *
setup.py pypi
  • numpy *
  • python-utils >=1.6.2
tests/requirements.txt pypi
  • Sphinx * test
  • cov-core * test
  • coverage * test
  • cython * test
  • docutils * test
  • execnet * test
  • flake8 * test
  • numpy * test
  • pep8 * test
  • py * test
  • pyflakes * test
  • pytest * test
  • pytest-cache * test
  • pytest-cov * test
  • pytest-flake8 * test
  • python-utils * test
  • wheel * test
.github/workflows/codeql.yml actions
  • actions/checkout v3 composite
  • github/codeql-action/analyze v2 composite
  • github/codeql-action/autobuild v2 composite
  • github/codeql-action/init v2 composite
.github/workflows/main.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite