4

我有一个存储为ndarray. 我想遍历这个数组中的每个像素。

我可以像这样遍历数组的每个元素:

from scipy import ndimage
import numpy as np

l = ndimage.imread('sample.gif', mode="RGB")

for x in np.nditer(l):
    print x

这给出了即:

...
153
253
153
222
253
111
...

这些是像素中每种颜色的值,一个接一个。我想要的是 3 到 3 读取这些值以产生如下内容:

...
(153, 253, 153)
(222, 253, 111)
...
4

3 回答 3

3

可能最简单的方法是先重塑 numpy 数组,然后再进行打印。

http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

另外,这应该对您有所帮助。 在python中重塑一个numpy数组

于 2015-01-27T16:22:28.060 回答
3

您可以尝试使用自身压缩列表:

from itertools import izip
for x in izip(l[0::3],l[1::3],l[2::3]):
    print x

输出:

(153, 253, 153)
(222, 253, 111)

更新: Welp,我在 2015 年不擅长 numpy。这是我的更新答案:

scipy.ndimage.imread现在已弃用,建议使用imageio.imread. 但是,出于这个问题的目的,我测试了两者并且它们的行为相同。

由于我们正在读取 as 中的图像RGB,我们将得到一个 数组heightxwidthx3,这已经是您想要的了。当您使用 迭代数组时,您正在丢失形状np.nditer

>>> img = imageio.imread('sample.jpg')
>>> img.shape
(456, 400, 3)
>>> for r in img:
...     for s in r:
...         print(s)
... 
[63 46 52]
[63 44 50]
[64 43 50]
[63 42 47]
...
于 2015-01-27T16:32:48.397 回答
1

虽然@Imran 的答案有效,但它不是一个直观的解决方案......这可能会使调试变得困难。就个人而言,我会避免对图像进行任何操作,然后使用 for 循环进行处理。

备选方案 1:

img = ndimage.imread('sample.gif')
rows, cols, depth = np.shape(img)

r_arr, c_arr = np.mgrid[0:rows, 0:cols]

for r, c in zip(r_arr.flatten(), c_arr.flatten()):
    print(img[r,c])

或者您可以直接使用嵌套的 for 循环执行此操作:

for row in img:
    for pixel in row:
        print(pixel)

请注意,这些是灵活的;无论深度如何,它们都适用于任何 2D 图像。

于 2015-03-09T18:14:25.207 回答