【问题标题】:Identify the color values of an image with a color palette using PIL/Pillow使用 PIL/Pillow 使用调色板识别图像的颜色值
【发布时间】:2020-03-05 16:20:31
【问题描述】:

我正在尝试使用 PIL/pillow 识别图像中使用的调色板的颜色。 我尝试了以下方法:

  • 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')。有没有办法把它映射到索引号。我想,这里每三个字节都会映射到一个索引号。

【问题讨论】:

  • 合并getcolorsgetpalette。那些“看似无关的整数”正是您要寻找的;它们很重要。
  • 好的,谢谢您的评论。我应该如何组合它们?
  • imgage.palette.colors 包含从palette colorspalette indices 的映射,例如{(255, 0, 0): 0, (0, 0, 255): 1, (0, 255, 0): 2, (255, 255, 255): 3, (0, 255, 255): 4, (255, 255, 0): 5}

标签: python-3.x image python-imaging-library pixel


【解决方案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])

【讨论】:

  • 太棒了!谢谢 :) 我剩下要做的就是将剩余的颜色映射到索引号和相应的计数!
  • colours?马克,享受你的茶——还有,请向格雷伯爵问好! ;-)
  • 颜色已经映射。 [2,2] 中的前 2 表示索引为 0 的 2 个像素,即蓝色像素。 [2,2] 中的第二个 2 表示索引为 1 的 2 个像素,即红色像素。
  • 我们应该在 Stack Overflow 图像处理中制定一条规则,任何人都不能使用方形图像(因为他们从不告诉你放置行和列索引的方式),并且没有人使用 3 行或3 列,因为那时还不清楚样本是 RGB 三元组还是行或列!示例中小图像的理想形状是 4,5,3,因为可以清楚地知道哪些是行,哪些是列,哪些是 RGB 三元组,并且可以打印出来而不会省略任何部分。塞切尔定律 :-)
  • 哇,你说得对。我选择了一个非常糟糕的例子。感谢您的澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
相关资源
最近更新 更多