使用Python从STL文件渲染2D图像

时间:2018-07-24 22:39:33

标签: python matplotlib 3d numpy-stl

我想加载一个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()

这仅在我最后得到组件轮廓的情况下有效,但缺少很多细节。下图是一个乐高积木... Lego brick

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

Lego brick with edges

我希望通过增加照明,阴影可以帮助添加丢失的细节,但我找不到解决方法。

有什么想法如何在下面的代码中添加光源以创建阴影?

2 个答案:

答案 0 :(得分:4)

在厌倦了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()

如果您希望砖为蓝色,则可以将

替换为mesh_plot
vpl.mesh_plot(mesh, color="blue")

答案 1 :(得分:0)

如果您觉得Mayavi没有帮助,可以尝试使用Panda3D,该产品专门用于图形/ 3D渲染应用程序。我发现做这样的简单事情非常简单。