如何使用 Pillow 获取浮点 RGBA 像素值列表?

How to get a list of float RGBA pixels values using Pillow?

我想使用 Pillow python 模块获取浮点 RGBA 像素值列表。

到目前为止我只能得到RGBA整数数据:

from PIL import Image

im = Image.open("Lenna.png")
im_alpha = im.convert('RGBA')
Pixels = list(im.getdata())

例如这会得到我 ((226, 137, 125, 255), ...) 但是我不知道如何以浮点形式获取此信息,例如 ((0.88627451, 0.537254902, 0.490196078, 1), ...).

我该怎么做?

这是我用于 RGB .png 的内容:

from PIL import Image
import numpy

# http://www.schaik.com/pngsuite/basn2c16.png
im = Image.open('basn2c16.png')
#~ data = numpy.asarray(im)
data = numpy.array(im) # same as .asarray
print("Array dimensions: %s"%(repr(data.shape)))
data = data.astype(float)
print("[20, 30]=%s"%(repr(data[20, 30])))
print(data)
data = numpy.divide(data, 255.0)
print(data)

但是,请注意,这取决于 .png 的类型;例如,查看 http://www.schaik.com/pngsuite/pngsuite_bas_png.html for test files, and for basn2c16.png 是“3x16 位 rgb 颜色”,打印输出为:

Array dimensions: (32, 32, 3)
[20, 30]=array([   8.,   90.,  156.])
[[[ 255.  255.    0.]
  [ 247.  255.    0.]
  [ 239.  255.    0.]
...
[[[ 1.          1.          0.        ]
  [ 0.96862745  1.          0.        ]
  [ 0.9372549   1.          0.        ]
  ..., 

因此,即使这是 16 位,值似乎也跨越 0-255,就好像 8 位一样。在这种情况下,我们需要用 numpy.divide 和 255 缩放数据以获得浮点范围 0.0-1.0 ...

但是,如果您使用 indexed/palleted png basn3p08.png,您会得到:

Array dimensions: (32, 32)
[20, 30]=120.0
[[ 165.  165.  165. ...,  254.  254.  254.]
 [   8.    8.    8. ...,  248.  248.  248.]
....

所以现在矩阵内容不代表 RGB(A) 值,而是调色板中的索引,所以除以 255 没有意义。

最后,如果它是像 basn6a16.png 这样的 RGBA png,您也会得到 alpha:

Array dimensions: (32, 32, 4)
[20, 30]=array([   0.,   88.,  167.,   16.])
[[[ 255.  255.    0.    0.]
  [ 247.  255.    0.    0.]
...

同样,即使这是 16 位 png,这些值似乎也会缩放到 255,因此除以 255 以获得浮点数是有意义的。

换句话说,使用 numpy 和 PIL 缩放矩阵值相对容易,但是,您应该确保矩阵的格式正确...