Python 从numpy数组创建球形遮罩并获取球体内的数组索引

Python 从numpy数组创建球形遮罩并获取球体内的数组索引,python,numpy,Python,Numpy,嗨,我有一个x、y、z位置的样本数据: # x y z -0.120932 -0.300053 -0.296206 -0.0978073 -0.304533 -0.291415 -0.097738 -0.299779 -0.28466 -0.118981 -0.293157 -0.292577 -0.105695 -0.263689 -0.303431 -0.0759291 -0.254051 -0.294597 -0.0637251 -0.293032 -0.306507 -0.083585

嗨,我有一个x、y、z位置的样本数据:

# x y z
-0.120932 -0.300053 -0.296206
-0.0978073 -0.304533 -0.291415
-0.097738 -0.299779 -0.28466
-0.118981 -0.293157 -0.292577
-0.105695 -0.263689 -0.303431
-0.0759291 -0.254051 -0.294597
-0.0637251 -0.293032 -0.306507
-0.083585 -0.290494 -0.311816
-0.0928098 -0.294645 -0.294957
我想创建一个5个单位的球体,然后应用球形遮罩来获得该球体内的位置坐标。我还想得到球体内相应行(坐标)的索引

我的代码如下所示:

pos = 'data.txt'

x, y, z = np.loadtxt(pos, unpack =True)


h = len(x)
w = len(y)
l = len(z)
center = [-0.120932, -0.300053, -0.296206]
radius = 5.


# create circular mask 
def createCircularMask(h, w, l, center, radius):

    X, Y, Z = np.ogrid[:h, :w, :l]
        dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2 + (Z-center[2]**2))

        mask = dist_from_center <= radius
        return mask

inside_x = x[createCircularMask]

print inside_x
print len(inside_x)
pos='data.txt'
x、 y,z=np.loadtxt(pos,unpack=True)
h=len(x)
w=长度(y)
l=len(z)
中心=[-0.120932,-0.300053,-0.296206]
半径=5。
#创建圆形遮罩
def createCircularMask(h、w、l、中心、半径):
十、 Y,Z=np.ogrid[:h,:w,:l]
距离中心的距离=np.sqrt((X-中心[0])**2+(Y-中心[1])**2+(Z-中心[2]**2))

mask=除了Andras Deak回答之外,与中心的距离 计算Z坐标的距离时,函数中有一个输入错误:

距离中心的距离=np.sqrt((X-中心[0])**2+(Y-中心[1])**2+(Z-中心[2]**2))
固定的:

距离中心的距离=np.sqrt((X-中心)**2+(Y-中心)**2+(Z-中心)**2)
对我来说,它工作正常

您忘记调用函数:
x[createCircularMask]
尝试使用函数对象对数组进行索引。相反,您需要返回值:
x[createCircularMask()]
(注意括号)。对于需要的索引
mask=createCircularMask();mask.nonzero()
。这将为
mask
True
的点提供沿每个维度的索引。
   File "density_map_test.py", line 41, in <module>
    inside_x = x[createCircularMask]
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices