Skip to main content
 首页 » 编程设计

python之在 Python 中从 STL 文件渲染二维图像

2025年05月04日21mengfanrong

我想加载一个 STL 文件并生成一组不同旋转的 2D 图像。

我基于 this 获得了使用 numpy-STL 的基础知识例如,以这段代码结束 -

from stl import mesh 
from mpl_toolkits import mplot3d 
from matplotlib import pyplot 
 
filename = '3001.stl' 
 
# Create a new plot 
figure = pyplot.figure() 
axes = figure.gca(projection='3d') 
 
# Load the STL files and add the vectors to the plot 
mesh = mesh.Mesh.from_file(filename) 
 
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(mesh.vectors, color='lightgrey')) 
#axes.plot_surface(mesh.x,mesh.y,mesh.z) 
# Auto scale to the mesh size 
scale = mesh.points.flatten() 
axes.auto_scale_xyz(scale, scale, scale) 
 
#turn off grid and axis from display       
pyplot.axis('off') 
 
#set viewing angle 
axes.view_init(azim=120) 
 
# Show the plot to the screen 
pyplot.show() 

只有在我最终得到组件的剪影时效果很好,缺少很多细节。下图是一 block 乐高积木...

我试图突出边缘。但这对模型的创建方式很敏感,这对我来说不是很好。

我希望通过添加光照,阴影可以帮助添加缺失的细节,但我找不到办法做到这一点。

知道如何在下面的代码中添加光源来创建阴影吗?

请您参考如下方法:

在厌倦了 Mayavi 的安装灾难后,我最终为此编写了自己的库。 https://github.com/bwoodsend/vtkplotlib

你的代码应该是这样的

import vtkplotlib as vpl 
from stl.mesh import Mesh 
 
path = "your path here.stl" 
 
# Read the STL using numpy-stl 
mesh = Mesh.from_file(path) 
 
# Plot the mesh 
vpl.mesh_plot(mesh) 
 
# Show the figure 
vpl.show() 

如果您希望砖 block 是蓝色的,您可以将 mesh_plot 替换为

vpl.mesh_plot(mesh, color="blue")