将三维坐标映射到一维索引

时间:2011-04-25 09:36:16

标签: python numpy coordinates

我有一个三维坐标。我想将它映射到一维索引。据我所知,可以使用配对功能在二维情况下处理这个问题。但是,我已经为3D案例提出了以下天真的实现:

from numpy import *

# the size of the coordinate space
xn = 100
yn = 100
zn = 100

# make a 3 dimensional matrix of zeros
m = zeros((xn,yn,zn))

def xyz_to_index(m,x,y,z):
    # set a particular coordinate to 1
    m[x,y,z] = 1
    # find its index
    i = argmax(m)
    # rezero matrix
    m[x,y,z] = 0
    # return 1D index
    return i

此代码允许我从3D点映射到1D索引,如下面的ipython日志所示:

In [40]: xyz_to_index(m,34,56,2)
Out[40]: 345602

所以现在我的问题是,有更好的方法吗?我认为遍历矩阵并不是进行此坐标转换的最有效方法。你会做什么呢?

3 个答案:

答案 0 :(得分:2)

您可以为任意维度的NumPy数组实现函数ravel_index()

def ravel_index(x, dims):
    i = 0
    for dim, j in zip(dims, x):
        i *= dim
        i += j
    return i

此函数与函数numpy.unravel_index()的反函数。

对于您的应用程序,您可以将此功能称为ravel_index((x, y, z), m.shape)

答案 1 :(得分:2)

此处提供了一般解决方案:

Numpy interconversion between multidimensional and linear indexing

但基本上如果您知道多维空间的形状:

def ravel_index(x, dims):
    c = np.cumprod([1] + dims[::-1])[:-1][::-1]
    return np.dot(c,x)


s = [100,100,100] # shape of dims
ii = [34,56,2] # 3d index
jj = ravel_index(ii,s) # 1d index

答案 2 :(得分:1)

如果您事先知道所有坐标都在0..99范围内,您可以通过以下函数轻松计算索引:

def xyz_to_index(x,y,z):
    return ((x * 100) + y) * 100 + z
相关问题