将3D .stl文件转换为JPG图像
如何将任何 STL 文件中的 3D 对象转换为 JPG 或 PNG 图像。
我尝试在网上进行一些搜索,但无法找到任何可能的解决方案。
谁能帮助我编写可以使用 Python 完成这项直接任务的代码?有什么图书馆可以帮助解决这个问题吗?
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")
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看https://pypi.org/project/numpy-stl/
这个代码片段来自上面的链接。
在python 3.12.0、matplotlib 3.8.0、stl 3.0.1中测试
要在
pyplot.show()
之前将 pyplot 对象保存为图像:pyplot.savefig("file_name.jpg")
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
To save a pyplot object as an image before
pyplot.show()
:pyplot.savefig("file_name.jpg")
正如 numpy-stl 中的示例所述,您必须使用 pyplot 的 savefig:
默认为巴布亚新几内亚。我必须添加
bbox_inches
以避免出现空图像。查看 文档 了解更多选项。这是完整的工作示例,改编自链接资源:As mentioned in the example from numpy-stl you have to use pyplot's savefig:
The default is PNG. I had to add
bbox_inches
to avoid an empty image. Check out the docs for more options. Here is the full working example, adapted from the linked resource: