用python写一段导入点云文件后用matplotlib导出的三维曲面保存成stl文件的代码
时间: 2023-03-09 16:50:30 浏览: 73
答案:import numpy as np
from matplotlib import cm
from stl import mesh
import pptk# 导入点云文件
points = np.loadtxt('cloud.txt')# 用matplotlib绘制三维曲面
X, Y, Z = points[:, 0], points[:, 1], points[:, 2]
xi = np.linspace(X.min(),X.max(),1000)
yi = np.linspace(Y.min(),Y.max(),1000)
XI, YI = np.meshgrid(xi, yi)
rbf = scipy.interpolate.Rbf(X, Y, Z, function='linear')
ZI = rbf(XI, YI)# 将三维曲面保存为stl文件
vertices = np.array([XI.flatten(), YI.flatten(), ZI.flatten()]).T
faces = Delaunay(vertices).convex_hull
stl_mesh = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
for i, f in enumerate(faces):
for j in range(3):
stl_mesh.vectors[i][j] = vertices[f[j],:]stl_mesh.save('surface.stl')
相关问题
用python写一段用matplotlib画出的三维曲面导出保存成stl文件的代码
代码如下:import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from stl import mesh# 定义曲面
X = np.arange(-2,2,0.25)
Y = np.arange(-2,2,0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)# 画出曲面
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')# 导出stl文件
stl_mesh = mesh.Mesh(np.zeros(Z.shape[0]*Z.shape[1], dtype=mesh.Mesh.dtype))
for i in range(Z.shape[0] - 1):
for j in range(Z.shape[1] - 1):
stl_mesh.vectors[i*Z.shape[1] + j] = np.array([[X[i, j], Y[i, j], Z[i, j]],
[X[i, j + 1], Y[i, j + 1], Z[i, j + 1]],
[X[i + 1, j + 1], Y[i + 1, j + 1], Z[i + 1, j + 1]],
[X[i + 1, j], Y[i + 1, j], Z[i + 1, j]]])stl_mesh.save('my_stl_file.stl')
用python写一段用matplotlib画出的长方体导出保存成stl文件的代码
以下是一段可以用来画出长方体并保存为stl文件的python代码:from stl import mesh
import numpy
import matplotlib.pyplot as plt# Create 6 faces of a cube
data = numpy.zeros(6, dtype=mesh.Mesh.dtype)# Top of the cube
data['vectors'][0] = numpy.array([[0, 1, 1],
[1, 0, 1],
[0, 0, 1]])
data['vectors'][1] = numpy.array([[1, 0, 1],
[0, 1, 1],
[1, 1, 1]])
# Front face
data['vectors'][2] = numpy.array([[1, 0, 0],
[1, 0, 1],
[1, 1, 0]])
data['vectors'][3] = numpy.array([[1, 1, 1],
[1, 0, 1],
[1, 1, 0]])
# Left face
data['vectors'][4] = numpy.array([[0, 0, 0],
[1, 0, 0],
[1, 0, 1]])
data['vectors'][5] = numpy.array([[0, 0, 1],
[1, 0, 1],
[0, 0, 0]])# Create the mesh
cube = mesh.Mesh(data.copy())# Visualization of the cube
# Create a figure
fig = plt.figure()
# Add an axes
ax = fig.add_subplot(1, 1, 1)
# Set the title
ax.set_title('3D Test')
# Show the cube
ax.add_collection3d(mesh.Mesh3dCollection(cube.vectors))
# Auto scale to the mesh size
scale = cube.points.flatten(-1)
ax.auto_scale_xyz(scale, scale, scale)
# Show the figure
plt.show()# Save the stl file
cube.save('cube.stl')