2012-11-20 164 views
3

我有2个数组[nx1]分别存储xpixel(样本)和ypixel(线)坐标。我有另一个数组[nxn]存储图像。我想要做的是创建一个第三个数组,它将图像数组中的像素值存储在给定的坐标处。我有以下工作,但不知道内置numpy函数是否会更有效。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的长度以及图像的行进方向。因此每次迭代都完全不同。

回答

3

可以使用advanced indexing

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)] 
+0

您不必解开'ylin'和'xsam'。如果你不这样做,'newarr'将保持与'ylin'或'xsam'相同的形状,这是非常有用的(当然,OP的代码会返回一个'newarr'的代码,但是你可以'如果你想的话,最后挤压''newarr')。 – jorgeca

+0

@jorgeca:是的。 '.squeeze'也可以在这里工作。 – jfs