【问题标题】:Read an image pixel by pixel (ndimage/ndarray)逐像素读取图像(ndimage/ndarray)
【发布时间】:2015-03-26 08:07:45
【问题描述】:

我有一个存储为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 到 3 以产生如下内容:

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

【问题讨论】:

    标签: python numpy scipy multidimensional-array ndimage


    【解决方案1】:

    您可以尝试自行压缩列表:

    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。但是,出于这个问题的目的,我测试了两者,它们的行为相同。

    由于我们正在以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]
    ...
    

    【讨论】:

      【解决方案2】:

      虽然@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 图像。

      【讨论】:

        【解决方案3】:

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

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

        另外,这应该对您有所帮助。 Reshaping a numpy array in python

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多