【问题标题】:How to set the origin for the mesh with mplot3d?如何使用 mplot3d 设置网格的原点?
【发布时间】:2018-09-17 22:09:57
【问题描述】:

按照scikit-image doc 中的示例,我使用行进立方体算法生成球面网格。我想将单位球壳居中于 x,y,z 网格定义的原点。但是,我不能这样做,因为我不知道如何将 x、y、z 信息与 mpl_toolkits.mplot3d.art3d.Poly3DCollection 一起放置。代码如下:

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

x, y, z = np.ogrid[-4:4:20j, -4:4:20j, -4:4:20j]
r = np.sqrt(x ** 2 + y ** 2 + z ** 2)
verts, faces, normals, values = measure.marching_cubes_lewiner(r,level=1)
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
mesh = Poly3DCollection(verts[faces])
mesh.set_edgecolor('k')
ax.add_collection3d(mesh)
plt.show()

问题在于marching_cubes_lewiner 函数没有考虑x,y,z。如何将生成的球体以网格所暗示的 0,0,0 为中心?

【问题讨论】:

  • 教程中的函数名为measure.marching_cubes_lewiner,它有两个参数。
  • @ImportanceOfBeingErnest:第二个参数是可选的,用于设置等值面的值。 marching_cubes 使用 lewiner 算法作为默认值,因此两者都有效。但是,我编辑了问题以避免混淆。
  • 我的 skimage 版本没有marching_cubes。但是现在的代码应该可以工作;你遇到了什么问题?
  • 我希望球体以 0,0,0 为中心。我不知道该怎么做。

标签: python matplotlib scikit-image mplot3d marching-cubes


【解决方案1】:

measure.marching_cubes_lewiner 采用网格中点的索引来计算拓扑。它似乎没有办法指定实际的网格,也没有任何偏移量。

因此,您可以以所需的方式操作生成的verts。 IE。可以先乘以网格点之间的差异,有效缩放输出,然后加上网格的偏移量。在这种情况下,转换将是 newverts = 0.42105 * oldverts - 4

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

x, y, z = np.ogrid[-4:4:20j, -4:4:20j, -4:4:20j]
r = np.sqrt(x ** 2 + y ** 2 + z ** 2)

verts, faces, normals, values = measure.marching_cubes_lewiner(r, level=1)

verts *= np.array([np.diff(ar.flat)[0] for ar in [x,y,z]])
verts += np.array([x.min(),y.min(),z.min()])

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
mesh = Poly3DCollection(verts[faces])
mesh.set_edgecolor('k')
ax.add_collection3d(mesh)
ax.set_xlim(-2, 2) 
ax.set_ylim(-2, 2)
ax.set_zlim(-2, 2)
plt.show()

【讨论】:

  • 非常感谢您的回答。您能否详细说明对顶点的操作?顺便说一句,import numpy as np 不见了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 2012-04-18
相关资源
最近更新 更多