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

Map an array of indexes to an array of coordinates

我正在玩 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()

这是生成的曲面:

顶点坐标似乎是根据数组索引而不是网格坐标给出的。我怎样才能转换顶点的坐标,以便它们映射到网格,如下图所示?

我可以手工完成:

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

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

谢谢。

恕我直言,这里没有魔法。 mplot3d.

中没有 'plug and play' 转换

对于自动化,您只需使用一个函数来完成您的 'by hand' 工作:

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)