2013-08-21 57 views
10

我想創建一個二維numpy的陣列,其中我想存儲的像素的座標,使得numpy的陣列看起來像這樣最快方法來創建2D numpy的數組,其元素是在範圍

[(0, 0), (0, 1), (0, 2), ...., (0, 510), (0, 511) 
(1, 0), (1, 1), (1, 2), ...., (1, 510), (1, 511) 
.. 
.. 
.. 
(511, 0), (511, 1), (511, 2), ...., (511, 510), (511, 511)] 

這是一個可笑的問題,但我還找不到任何東西。

+0

你的格式化的方式,它看起來像你想要一個3D數組形狀(512,512,2)...但你給出的語法標記是一個二維數組形狀(512 * 512, 2)。你能澄清嗎? – lmjohns3

回答

7

可以使用np.indicesnp.meshgrid更高級的索引:

>>> data=np.indices((512,512)).swapaxes(0,2).swapaxes(0,1) 
>>> data.shape 
(512, 512, 2) 

>>> data[5,0] 
array([5, 0]) 
>>> data[5,25] 
array([ 5, 25]) 

這可能看起來很奇怪,因爲它真的讓做這樣的事情:

>>> a=np.ones((3,3)) 
>>> ind=np.indices((2,1)) 
>>> a[ind[0],ind[1]]=0 
>>> a 
array([[ 0., 1., 1.], 
     [ 0., 1., 1.], 
     [ 1., 1., 1.]]) 

一個mgrid例如:

np.mgrid[0:512,0:512].swapaxes(0,2).swapaxes(0,1) 

一個meshgrid示例:

>>> a=np.arange(0,512) 
>>> x,y=np.meshgrid(a,a) 
>>> ind=np.dstack((y,x)) 
>>> ind.shape 
(512, 512, 2) 

>>> ind[5,0] 
array([5, 0]) 

所有這些都是等效的方法;然而,meshgrid可用於創建不均勻的網格。

如果您不介意切換行/列索引,則可以刪除最後的swapaxes(0,1)

2

您可以在這裏使用np.ogrid。不要存儲tuple,請將其存儲在3D陣列中。

>>> t_row, t_col = np.ogrid[0:512, 0:512] 
>>> a = np.zeros((512, 512, 2), dtype=np.uint8) 
>>> t_row, t_col = np.ogrid[0:512, 0:512] 
>>> a[t_row, t_col, 0] = t_row 
>>> a[t_row, t_col, 1] = t_col 

這應該是訣竅。希望你可以使用這個,而不是元組。

Chintak

3

在問題的例子並不完全清楚 - 無論是額外的逗號丟失或額外brakets。

這一個 - 例如範圍3,4爲清楚起見 - 提供第一變體的溶液,併產生有效的2D陣列(作爲問題標題表明) - 「目錄」的所有座標:

>>> np.indices((3,4)).reshape(2,-1).T 
array([[0, 0], 
     [0, 1], 
     [0, 2], 
     [0, 3], 
     [1, 0], 
     [1, 1], 
     [1, 2], 
     [1, 3], 
     [2, 0], 
     [2, 1], 
     [2, 2], 
     [2, 3]]) 

其他變種已經在另一個答案用2X .swapaxes()顯示 - 但它也可以用一個np.rollaxis()(或新np.moveaxis())來完成:

>>> np.rollaxis(np.indices((3,4)), 0, 2+1) 
array([[[0, 0], 
     [0, 1], 
     [0, 2], 
     [0, 3]], 

     [[1, 0], 
     [1, 1], 
     [1, 2], 
     [1, 3]], 

     [[2, 0], 
     [2, 1], 
     [2, 2], 
     [2, 3]]]) 
>>> _[0,1] 
array([0, 1]) 

這種方法也適用於N維指數相同,例如:

>>> np.rollaxis(np.indices((5,6,7)), 0, 3+1) 

注:np.indices快速的作品的確(C-速度)爲大範圍的功能。

相關問題