我正在尝试通过PIL /枕头识别图像所用调色板的颜色。我尝试了以下方法:
image[x,y]
:这只会给我相应像素的索引号(即1
)image.getpixel((x,y))
:同样,这只会给我相应像素的索引号(即1
)image.getcolors()
:这将为我提供像素数及其相应的索引号(即[(2, 1), (2, 0)]
)image.palette
:返回一个“ PIL.ImagePalette.ImagePalette对象”image.getpalette()
:返回一大堆(在我看来)不相关的整数(即[0, 0, 255, 255, 0, 0, 2, 2, 2, 3, 3 ,3 ...]
)作为绝对的后备,我可以转换图像模式,然后获取颜色值,但如果可能,我宁愿不这样做。
[使用此example image(2x2像素图像,使用GIMP创建的具有2种颜色的索引模式,顶部两个像素为红色(255,0,0),底部两个像素为蓝色(0,0,255)),我期望有一些东西像:
image.getpalette()
1: (255,0,0)
0: (0,0,255)
编辑:我最近的是:
image.palette.getdata()
:这给了我('RGB;L', b'\x00\x00\xff\xff\x00\x00')
。有什么办法可以将此映射到索引号。我认为这里每三个字节将映射到一个索引号。
编辑2:
import numpy as np
palette = np.array(im.getpalette(),dtype=np.uint8).reshape((256,3))
print(palette)
据我所知,这给了我一系列颜色值,但与索引没有明显的关系。
输出:
[[ 0 0 255]
[255 0 0]
[ 2 2 2]
[ 3 3 3]
[ 4 4 4]
[...]
[255 255 255]]
[从上下文中我知道(0,0,255)是索引为0的颜色,(255,0,0)是索引为1的颜色。我不明白以下值代表什么。有没有一种方法可以使索引与颜色值直接相关?
您可以像这样获得和安排调色板:
import numpy as np
from PIL import Image
# Open image
im = Image.open('a.png')
# Get palette and reshape into 3 columns
palette = np.array(im.getpalette(),dtype=np.uint8).reshape((256,3))
然后仅打印palette
。
[[ 0 0 255] <--- first entry is blue
[255 0 0] <--- second is red
[ 2 2 2] <--- grey padding to end
[ 3 3 3]
[ 4 4 4]
[ 5 5 5]
[ 6 6 6]
...
...
[253 253 253]
[254 254 254]
[255 255 255]]
如果您要计算颜色以及每种颜色的数量,请执行以下操作:
# Convert Image to RGB and make into Numpy array
na = np.array(im.convert('RGB'))
# Get used colours and counts of each
colours, counts = np.unique(na.reshape(-1,3), axis=0, return_counts=1)
将colours
设为:
array([[ 0, 0, 255],
[255, 0, 0]], dtype=uint8)
和counts
为:
array([2, 2])