Numpy矢量化相对距离

时间:2017-03-20 02:37:13

标签: python numpy vectorization

很抱歉提出一个初学者的问题,但我一直在谷歌搜索一段时间,我不知道如何去绘制涉及索引本身的东西。

import numpy as np
#Sample array
start= np.array([[[1,2,3],[62,63,12],[12,35,56]],[[27,53,34],[33,43,64],[3,75,43]],[[23,53,54],[23,65,97],[34,23,53]]])
f= np.array([[[2,1],[-1,0],[1,-1]],[[0,0],[1,1],[-1,-1]],[[0,-1],[-1,-1],[-1,-2]]])
#f.shape(x,y,2) and start is (x,y,3)
end=np.empty(start.shape)
for x in range(f.shape[0]):
    for y in range(f.shape[1]):
        print (x,y)
        end[x][y]= start[f[x,y,0] + x][f[x,y,1] + y]
#Output 
"""
[[[ 23.  65.  97.]
  [ 23.  65.  97.]
  [ 33.  43.  64.]]

 [[ 27.  53.  34.]
  [ 34.  23.  53.]
  [ 62.  63.  12.]]

 [[ 34.  23.  53.]
  [ 27.  53.  34.]
  [ 27.  53.  34.]]]
"""
print(end)

1 个答案:

答案 0 :(得分:1)

您基本上需要向f的每个元素添加该元素的整数位置。我们可以使用f构建一个与numpy.meshgrid形状匹配的索引数组:

import numpy as np

start = np.array([[[1,2,3],[62,63,12],[12,35,56]],[[27,53,34],[33,43,64],[3,75,43]],[[23,53,54],[23,65,97],[34,23,53]]])
f = np.array([[[2,1],[-1,0],[1,-1]],[[0,0],[1,1],[-1,-1]],[[0,-1],[-1,-1],[-1,-2]]])

m,n,_ = f.shape
x = np.arange(n)
y = np.arange(m)
xx,yy = np.meshgrid(x,y)
indices = np.stack((yy.ravel(),xx.ravel()),axis=-1).reshape(m,n,-1)

# [[[0 0]
#   [0 1]
#   [0 2]]
# 
#  [[1 0]
#   [1 1]
#   [1 2]]
# 
#  [[2 0]
#   [2 1]
#   [2 2]]]

indicesf具有相同的形状,因此请添加它们以生成所需的索引数组idx_f。最后,将idx_f应用为start上的索引数组。

idx_f = f + indices

# [[[ 2  1]
#   [-1  1]
#   [ 1  1]]
#
#  [[ 1  0]
#   [ 2  2]
#   [ 0  1]]
#
#  [[ 2 -1]
#   [ 1  0]
#   [ 1  0]]]

end = start[idx_f[:,:,0],idx_f[:,:,1]]

# [[[23 65 97]
#   [23 65 97]
#   [33 43 64]]
# 
#  [[27 53 34]
#   [34 23 53]
#   [62 63 12]]
# 
#  [[34 23 53]
#   [27 53 34]
#   [27 53 34]]]