Numpy 在三维坐标系中查找球体中的每个点

Numpy 在三维坐标系中查找球体中的每个点,numpy,numpy-ndarray,Numpy,Numpy Ndarray,我正在尝试解决这个算法。 给定一个半径和一个点。 在三维坐标系中找到以给定点为中心的半径球体中的每个点,并将它们存储在列表中。您可以使用下面的numpy来完成此操作 注意,这里的代码将为您提供相对于球体的坐标,该球体以您选择的点为中心,半径为您选择的半径。您需要确保设置下面的输入尺寸“dim”,以便球体首先完全包含在该体积内。它也只适用于阳性指标。如果您的点有任何负坐标,请使用该点的正坐标,然后在输出中自己翻转该轴坐标的符号 import numpy as np dim = 15 # get

我正在尝试解决这个算法。 给定一个半径和一个点。
在三维坐标系中找到以给定点为中心的半径球体中的每个点,并将它们存储在列表中。

您可以使用下面的numpy来完成此操作

注意,这里的代码将为您提供相对于球体的坐标,该球体以您选择的点为中心,半径为您选择的半径。您需要确保设置下面的输入尺寸“dim”,以便球体首先完全包含在该体积内。它也只适用于阳性指标。如果您的点有任何负坐标,请使用该点的正坐标,然后在输出中自己翻转该轴坐标的符号

import numpy as np

dim = 15

# get 3 arrays representing indicies along each axis
xx, yy, zz = np.ogrid[:dim, :dim, :dim]

# set you center point and radius you want
center = [7, 7, 7]
radius = 3

# create 3d array with values that are the distance from the
# center squared
d2 = (xx-center[0])**2 + (yy-center[1])**2 + (zz-center[2])**2

# create a logical true/false array based on whether the values in d2
# above are less than radius squared
#
# so this is what you want - all the values within "radius" of the center
# are now set to True
mask = d2 <= radius**2

# calculate distance squared and compare to radius squared to avoid having to use
# slow sqrt()

# now you want to get the indicies from the mask array where the value of the
# array is True.  numpy.nonzero does that, and gives you 3 numpy 1d arrays of
# indicies along each axis
s, t, u = np.nonzero(mask)

# finally, to get what you want, which is all those indicies in a list, zip them together:
coords = list(zip(s, t, u))

print(coords)
>>>
[(2, 5, 6),
 (3, 4, 5),
 (3, 4, 6),
 (3, 4, 7),
 (3, 5, 5),
 (3, 5, 6),
 (3, 5, 7),
 (3, 6, 5),
 (3, 6, 6),
 (3, 6, 7),
 (4, 3, 6),
 (4, 4, 5),
 (4, 4, 6),
 (4, 4, 7),
 (4, 5, 4),
 (4, 5, 5),
 (4, 5, 6),
 (4, 5, 7),
 (4, 5, 8),
 (4, 6, 5),
 (4, 6, 6),
 (4, 6, 7),
 (4, 7, 6),
 (5, 4, 5),
 (5, 4, 6),
 (5, 4, 7),
 (5, 5, 5),
 (5, 5, 6),
 (5, 5, 7),
 (5, 6, 5),
 (5, 6, 6),
 (5, 6, 7),
 (6, 5, 6)]

将numpy导入为np
尺寸=15
#获取3个表示沿每个轴的标记的数组
xx,yy,zz=np.ogrid[:dim,:dim,:dim]
#设置所需的中心点和半径
中间=[7,7,7]
半径=3
#创建三维阵列,其值为与阵列的距离
#中心平方
d2=(xx中心[0])**2+(yy中心[1])**2+(zz中心[2])**2
#根据d2中的值是否为
#上面的半径小于半径的平方
#
#这就是你想要的——中心“半径”内的所有值
#现在设置为True
掩码=d2>>
[(2, 5, 6),
(3, 4, 5),
(3, 4, 6),
(3, 4, 7),
(3, 5, 5),
(3, 5, 6),
(3, 5, 7),
(3, 6, 5),
(3, 6, 6),
(3, 6, 7),
(4, 3, 6),
(4, 4, 5),
(4, 4, 6),
(4, 4, 7),
(4, 5, 4),
(4, 5, 5),
(4, 5, 6),
(4, 5, 7),
(4, 5, 8),
(4, 6, 5),
(4, 6, 6),
(4, 6, 7),
(4, 7, 6),
(5, 4, 5),
(5, 4, 6),
(5, 4, 7),
(5, 5, 5),
(5, 5, 6),
(5, 5, 7),
(5, 6, 5),
(5, 6, 6),
(5, 6, 7),
(6, 5, 6)]

一个球体有无限多的点。@WillemVanOnsem很抱歉混淆了,但我指的是整数坐标的所有点。提示:看看正/反是分数。是在球体内部还是在球体表面?@JoseMaria它在球体内部,谢谢你的注意。另一种方法是这样做的(也许更简单、更快——绝对更少的内存lol!)就是在x、y、z维度上做3个嵌套的循环,这将完全包围球体。然后比较这3个值到中心点的距离,如果小于半径,则将它们添加到“在球体内”列表中坐标。谢谢你的回答。我为循环一做了3个嵌套。绝对有帮助!我认为当半径较大时,你的答案更快。不客气……你用numpy标记了它,所以我给了你numpy方式(我可以想到)。但在这种情况下,我认为3个嵌套循环会更快更容易