pythonpython-3.xmatplotlibmplot3dmatplotlib-3d

Convert 3D .stl file to JPG image


How do I convert a 3D object in any STL file into a JPG or PNG image.

I tried searching a little bit online but I wasn't been able to arrive at finding any possible solutions.

Can anyone help me with the code that can do this straight forward task with Python? IS there any libraries that can help with that?

from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot
import pathlib

DIR = str(pathlib.Path(__file__).parent.resolve()).replace('\\', '/')
path = f'{DIR}/any_stl_file.stl'

# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)

# Load the STL files and add the vectors to the plot
your_mesh = mesh.Mesh.from_file(path)
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)

pyplot.savefig(f"{DIR}/the_image.jpg")

Solution

  • Take a look at https://pypi.org/project/numpy-stl/

    This code snippet is from the link above.

    Tested in python 3.12.0, matplotlib 3.8.0, stl 3.0.1

    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 
    # file is at https://github.com/wolph/numpy-stl/tree/develop/tests/stl_binary
    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()
    

    To save a pyplot object as an image before pyplot.show():

    pyplot.savefig("file_name.jpg")

    enter image description here