逐像素读取图像 (ndimage/ndarray)

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

这会给ie带来:
...
153
253
153
222
253
111
...

这些是像素中每个颜色的值,一个接着一个。相反,我想要读取这些值并以3个一组的方式生成类似于以下内容的内容:

...
(153, 253, 153)
(222, 253, 111)
...
3个回答

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)

更新: 好的,我在2015年对numpy掌握不好。以下是我的最新答案:

现在scipy.ndimage.imread已经被弃用,建议使用imageio.imread。但是,对于这个问题,我测试了两种方法,它们的行为是相同的。

由于我们将图像读入为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]
...

3

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图像,无论深度如何。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接