Identify the color values of an image with a color palette using PIL/Pillow

醉酒当歌 提交于 2020-03-23 12:02:24

问题


I'm trying to identify the colors of the used color palette of an image with PIL/pillow. I've tried the following:

  • image[x,y]: this will only give me the index number of the corresponding pixel (i.e. 1)
  • image.getpixel((x,y)): again, this will only give me the index number of the corresponding pixel (i.e. 1)
  • image.getcolors(): This will give me the number of pixels and their corresponding index number (i.e. [(2, 1), (2, 0)])
  • image.palette: Returns a "PIL.ImagePalette.ImagePalette object"
  • image.getpalette(): Returns a large array of (to me seemingly) unrelated integers (i.e. [0, 0, 255, 255, 0, 0, 2, 2, 2, 3, 3 ,3 ...])

As an absolute fallback, I could convert the image mode and then get the color values, but I'd rather not if possible.

With this example image (2x2 pixel image, indexed mode with 2 colors created with GIMP, the top two pixels are red (255,0,0) the bottom two are blue (0,0,255)), I was expecting something like:

image.getpalette()
1: (255,0,0)
0: (0,0,255)

Edit: The closest I have is:

image.palette.getdata(): This gives me ('RGB;L', b'\x00\x00\xff\xff\x00\x00'). Is there any way to have this mapped to the index number. Here each three bytes would map to one index number, I'd reckon.


回答1:


You can get and arrange the palette like this:

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))

Then just print 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]]

If you want to count the colours and how many of each there are, do this:

# 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)    

That gives colours as:

array([[  0,   0, 255],
       [255,   0,   0]], dtype=uint8)

and counts as:

array([2, 2])


来源:https://stackoverflow.com/questions/60539888/identify-the-color-values-of-an-image-with-a-color-palette-using-pil-pillow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!