从numpy数组创建球形蒙版,并在球体内获取数组索引

时间:2018-10-16 19:10:44

标签: 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 -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)

我收到以下错误:

   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

能否请您说明我为什么得到这个?以及如何获取索引预先感谢

1 个答案:

答案 0 :(得分:1)

除了 Andras Deak 答案 计算Z坐标的距离时,您的函数中有错字:

dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2 + (Z-center[2]**2))

已修复:

dist_from_center = np.sqrt((X - center)**2 + (Y-center)**2 + (Z-center)**2)

对我来说很好