使用数组进行Numpy索引

3

我有两个数组[nx1],分别存储x像素(样本)和y像素(行)坐标。我还有另一个数组[nxn]存储一张图片。我想做的是创建第三个数组,它存储图像数组在给定坐标处的像素值。我已经使用以下代码实现了这一点,但想知道是否有内置的numpy函数可以更高效地完成。

#Create an empty array to store the values from the image.
newarr = numpy.zeros(len(xsam))

#Iterate by index and pull the value from the image.  
#xsam and ylin are the line and sample numbers.

for x in range(len(newarr)):
    newarr[x] = image[ylin[x]][xsam[x]]

print newarr

一个随机生成器决定了xsam和ylin的长度以及在图像中行进的方向。因此,每次迭代都是完全不同的。

2个回答

3

您可以使用高级索引

In [1]: import numpy as np
In [2]: image = np.arange(16).reshape(4, 4)
In [3]: ylin = np.array([0, 3, 2, 2])
In [4]: xsam = np.array([2, 3, 0, 1])
In [5]: newarr = image[ylin, xsam]
In [6]: newarr
array([ 2, 15,  8,  9])

3
如果image是一个numpy数组,ylinxsam是一维的:
newarr = image[ylin, xsam]

如果ylinxsam是二维数组,第二维的大小为1(例如ylin.shape == (n, 1)),那么请先将它们转换为一维形式:
newarr = image[ylin.reshape(-1), xsam.reshape(-1)]

你不必解开 ylinxsam。如果你不这样做,newarr 将保持与 ylinxsam 相同的形状,这非常有用(当然,OP 的代码返回一个 1D 的 newarr,但是如果你想要那样的话,你可以在最后使用 .squeeze 压缩 newarr)。 - jorgeca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接