请注意,截至2018年,此答案已过时。
scipy已弃用
imread,您应该切换到
imageio.imread。有关两者之间的差异,请参阅此过渡文档。如果仅导入新库来代替旧库,则下面的代码应该没有任何变化,但我尚未对其进行测试。
最简单的答案是在PIL周围使用NumPy和SciPy包装器。有一个很棒的教程,但基本思想是:
from scipy import miscarr = misc.imread('lena.png') # 640x480x3 arrayarr[20, 30] # 3-vector for a pixelarr[20, 30, 1] # green value for a pixel对于640x480 RGB图像,这将为您提供640x480x3的数组
uint8。
或者,您可以仅使用PIL(或更确切地说,使用Pillow打开文件;如果您仍在使用PIL,则此方法可能不起作用,或者可能很慢),然后直接将其传递给NumPy:
import numpy as npfrom PIL import Imageimg = Image.open('lena.png')arr = np.array(img) # 640x480x4 arrayarr[20, 30] # 4-vector, just like above这将为您提供640x480x4类型的数组
uint8(第四个是alpha;
PIL始终将PNG文件加载为RGBA,即使它们没有透明性;也请确保
img.getbands()您不确定)。
如果您根本不想使用NumPy,则PIL自己的
PixelArray类型是一个受限制的数组:
arr = img.load()arr[20, 30] # tuple of 4 ints
这为您提供了640x480
PixelAccess的RGBA 4元组数组。
或者,您可以仅调用
getpixel图像:
img.getpixel(20, 30) # tuple of 4 ints



