2013-10-24 66 views
-1

在我的程序中,我當前創建一個充滿零的numpy數組,然後循環遍歷每個元素,並用所需的值替換它。有沒有更有效的方法來做到這一點?Python Numpy如何有效地更改值

下面是我在做什麼,而不是一個int的例子我有每行需要放入numpy數組的列表。有沒有一種方法可以替換整行,並且效率更高。

import numpy as np 
from tifffile import imsave 

image = np.zeros((5, 2160, 2560), 'uint16') 

num =0 
for pixel in np.nditer(image, op_flags=['readwrite']): 
    pixel = num 
    num += 1 
imsave('multipage.tif', image) 
+0

你是否僅僅想創建一個數值不斷增加的數組?或者您是否有特定條件需要更改像素值? – irenemeanspeace

+0

@irenemeanspeace我從另一個圖像壓縮數據存儲在列表中,我想放入numpy數組中。 – Marmstrong

回答

0

您可以簡單地生成長度爲5 * 2160 * 2560的矢量並將其應用於圖像。

image=np.arange(5*2160*2560) 
image.shape=5,2160,-1 
1

使用切片

import numpy as np 
from tifffile import imsave 

list_of_rows = ... # all items in list should have same length 
image = np.zeros((len(list_of_rows),'uint16') 

for row_idx, row in enumerate(list_of_rows): 
    image[row_idx, :] = row 

imsave('multipage.tif', image) 

numpy的切片是非常強大和漂亮的只是分配到整排。我建議通過this documentation閱讀,以瞭解什麼是可能的。

相關問題