2012-11-20 67 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