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

2024-10-06 11:20:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用PillowPython模块获得一个浮动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),…)。在

我怎么能做到呢?在


Tags: 模块数据fromimageimport列表pilpng
1条回答
网友
1楼 · 发布于 2024-10-06 11:20:21

这是我在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以获取测试文件,对于^{}(即“3x16位rgb颜色”),打印输出为:

^{pr2}$

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

但是,如果使用索引/托盘png ^{},则可以得到:

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

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

最后,如果它是一个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来缩放矩阵值相对容易,但是,您应该确保矩阵的格式是正确的。。。在

相关问题 更多 >