python - 将索引数组映射到坐标数组

标签 python numpy matplotlib scikit-image

我正在玩一下 scikit-image marching cubes algorithm 。这是文档中给出的示例的简化版本。

from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure


x = np.linspace(-1, 1, 11)

X, Y, Z = np.meshgrid(x, x, x, indexing = 'ij')

def f(x, y, z):
    return x

verts, faces = measure.marching_cubes(f(X, Y, Z), 0.6)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

mesh = Poly3DCollection(verts[faces])
ax.add_collection3d(mesh)

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)

plt.show()

这是生成的表面:

enter image description here

看来顶点坐标是根据数组索引给出的,而不是网格网格的坐标。如何转换顶点的坐标,以便它们映射到网格,如下图所示?

enter image description here

我可以手动完成:

mesh = Poly3DCollection((verts[faces] / 5) - 1)

但是这里一定有一些numpy魔法。

谢谢。

最佳答案

恕我直言,这里没有魔法。 mplot3d 中没有“即插即用”转换。

对于自动化,您可以使用函数来完成“手动”工作:

from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure

x=y=z= np.linspace(-1, 1, 11)

grid=np.meshgrid(x,y,z)

def f(x, y, z):
    return x*x+y*y+z*z   # more fun ;)

def scale_marching(x,verts):
    return x[0]+ (x[-1]-x[0])/len(x)*verts

verts, faces = measure.marching_cubes(f(*grid), 1.5)    
verts=scale_marching(x,verts)

ax = plt.figure().add_subplot(111, projection='3d') 
ax.add_collection3d(Poly3DCollection(verts[faces]))
ax.auto_scale_xyz(*grid)

holes

关于python - 将索引数组映射到坐标数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34060955/

相关文章:

python - 在嵌入 C++ 程序的 python 脚本中使用 matplotlib 时出错

python - 具有基于列名称的图例的 T-SNE 散点图

python - 创建后如何修改matplotlib图例?

python - 用 LIME 解释 CNN (Keras) 输出

python - Windows 上的 Tensorflow 量化

python - 加速 Python Numpy 代码

python - Theano 中的余弦相似度

python - 解析字符串以查找并删除 float

python - 使用 numpy 在 python 中执行 varimax 旋转

python - 如何将仿射变换应用于 3d numpy 数组?