用倾斜的圆盘遮盖 3D numpy 阵列

Masking a 3D numpy array with a tilted disc

我在 Python2.7 中使用 3D numpy 数组,并尝试仅检索落在 2D 倾斜圆盘上的像素。

这是我绘制我感兴趣的圆盘边界(=一个圆圈)的代码

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


#creating a 3d numpy array (empty in this example, but will represent a binary 3D image in my application)
space=np.zeros((40,40,20))

r = 8 #radius of the circle
theta = np.pi / 4 # "tilt" of the circle
phirange = np.linspace(0, 2 * np.pi) #to make a full circle

#center of the circle
center=[20,20,10]

#computing the values of the circle in spherical coordinates and converting them
#back to cartesian
for phi in phirange:
    x = r * np.cos(theta) * np.cos(phi) + center[0]
    y=  r*np.sin(phi)  + center[1]
    z=  r*np.sin(theta)* np.cos(phi) + center[2]
    space[int(round(x)),int(round(y)),int(round(z))]=1


x,y,z = space.nonzero()

#plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, zdir='z', c= 'red')
plt.show()

剧情给出下图:

这是一个好的开始,但现在我想要一种方法来仅检索 space 的像素值,这些像素位于圆圈定义的圆盘中:下图(在我的应用程序中,space 将是一个 3D 二进制图像,这里是 numpy.zeros() 只是为了能够绘制并向您展示我想要的光盘):

我该如何进行? 我想这涉及到一些 numpy 掩码,我理解你将如何在 2D 中执行此操作(例如 this question),但我无法将其应用于 3D。

那是一道 数学 题,你应该在 Mathematics Stack Exchange 网站上提问。

从我的角度来看,你应该首先找到你的光盘所在的表面,然后在该表面内进行面积计算,例如,通过你在链接问题中提到的方法。

numpymatplotlib这里绝对不负责投影,你做。

没有明确指出它们在哪个(或哪种)表面,方程也不能保证它是一个平面,面积没有任何意义。

一种简单的方法是计算圆盘平面的法向量。您可以为此使用您的球坐标。确保不是添加中心,将 phi 设置为零并交换 cos 和 sin theta,并在 sin 上加上负号。

我们称该向量为 v。平面由 v0*x0 + v1*x1 + v2*x2 == c 给出,您可以通过从圆中插入一个点作为 x 来计算 c。

接下来您可以为 x0 和 x1 制作一个二维网格并求解 x2。这为您提供了高度 x2 作为 x0、x1 网格的函数。对于这些点,您可以计算与光盘中心的距离并丢弃太远的点。这你确实会使用面具来做。

最后,根据您想要绘制的精确程度,您可以将 x2 值四舍五入为网格单位,但例如对于曲面图,我不会这样做。

要获得您所描述的 3d 蒙版,您需要舍入 x2,然后从全零开始 space 使用 space[x0, x1, x2] = True 设置圆盘像素。这假设您已经按照前面所述屏蔽了 x0、x1、x2。