如何将任何 STL 文件中的 3D 对象转换为 JPG 或 PNG 图像。
我尝试在网上进行一些搜索,但无法找到任何可能的解决方案。
任何人都可以帮我编写可以使用 Python 完成这项直接任务的代码吗?有没有任何图书馆可以提供帮助?
编辑:
代码示例:
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")```
看看https://pypi.org/project/numpy-stl/
此代码片段来自上面的链接:
from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot
# 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('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()
将 pyplot 对象保存为图像:
pyplot.savefig("file_name.jpg")
正如 numpy-stl 中的示例所述,您必须使用 pyplot 的 savefig:
pyplot.savefig('model.jpg', format='jpg', bbox_inches='tight')
默认为 PNG。我必须添加 bbox_inches 以避免出现空图像。查看 docs 了解更多选项。这是完整的工作示例:
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('model.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)
# Save as image
pyplot.savefig('model.jpg', format='jpg', bbox_inches='tight')
# Show the plot to the screen
pyplot.show()