寻找MATLAB isosurface函数的Python/Numpy等价实现,需返回面与顶点生成STL
MATLAB isosurface 函数的Python等价实现
你可以使用scikit-image库的marching_cubes函数实现完全等效的功能,该函数基于移动立方体算法,可直接返回等值面的顶点和面数据,完美适配导出STL的需求。
安装依赖
pip install scikit-image numpy numpy-stl
代码示例
import numpy as np from skimage.measure import marching_cubes from stl import mesh # 生成和示例一致的测试数据 X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j] values = X * X * 0.5 + Y * Y + Z * Z * 2 # 提取等值面,level参数对应MATLAB的isovalue,这里取示例的10 verts, faces, _, _ = marching_cubes( values, level=10, # 直接指定坐标间距和偏移,无需后续手动转换坐标 spacing=( (X.max() - X.min())/(X.shape[0]-1), (Y.max() - Y.min())/(Y.shape[1]-1), (Z.max() - Z.min())/(Z.shape[2]-1) ), offset=(X.min(), Y.min(), Z.min()) ) # 此时verts对应MATLAB的v(顶点数据,形状为[N,3]),faces对应MATLAB的f(面索引数据,形状为[M,3]) # 导出为STL文件示例 output_mesh = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype)) for i, f in enumerate(faces): for j in range(3): output_mesh.vectors[i][j] = verts[f[j],:] output_mesh.save('ellipsoid.stl')
注意事项
- 若需要提取多个等值面,仅需循环调用
marching_cubes并传入不同的level参数即可 - 返回的面数据默认是三角形索引,和MATLAB
isosurface的输出格式完全兼容,无需额外转换 - 如果原始坐标不是均匀网格,可手动对返回的顶点坐标做线性映射适配
内容的提问来源于stack exchange,提问作者Daniel Sempere
相关产品推荐
相关产品推荐

