-1

在我的程序中,我当前创建了一个充满零的 numpy 数组,然后 for 循环遍历每个元素,并将其替换为所需的值。有没有更有效的方法来做到这一点?

下面是我正在做的一个例子,而不是一个 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)
4

2 回答 2

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 切片功能非常强大且美观。我建议通读本文档以了解可能的情况。

于 2013-10-24T11:49:51.600 回答
0

您可以简单地生成一个长度为 5*2160*2560 的向量并将其应用于图像。

image=np.arange(5*2160*2560)
image.shape=5,2160,-1
于 2013-10-24T11:08:58.093 回答