Python 逐像素读取图像(ndimage/ndarray)
我有一个图像存储为Python 逐像素读取图像(ndimage/ndarray),python,numpy,scipy,multidimensional-array,ndimage,Python,Numpy,Scipy,Multidimensional Array,Ndimage,我有一个图像存储为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) ... 这使ie: ... 153 253 153 222 253 11
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)
...
这使ie:
...
153
253
153
222
253
111
...
这些是像素中每种颜色的值,一个接一个。相反,我想通过3乘3读取这些值来生成如下内容:
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)
...
可能最简单的方法是先重塑numpy阵列,然后再开始打印 而且,这应该对你有帮助。
您可以尝试压缩列表本身:
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
的形式读取图像,因此我们将得到一个高x宽x3
的数组,这已经是您想要的了。当您使用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]
...
虽然@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)
注意这些是灵活的;无论深度如何,它们都适用于任何二维图像