我有一个存储为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)
...发布于 2015-01-28 00:22:28
可能最简单的方法是首先重塑numpy数组,然后开始打印。
http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
另外,这应该会对你有所帮助。Reshaping a numpy array in python
发布于 2015-01-28 00:32:48
你可以试着压缩这个列表:
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]
...发布于 2015-03-10 02:14:25
虽然答案@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图像,而不管深度如何。
https://stackoverflow.com/questions/28175070
复制相似问题