使用 python 的 PIL 模块导入图像后,我想获取图像中的颜色集作为 rgb 元组列表。
如果我事先知道只有 2 种颜色,并且图像会非常小,可能是 20x20 像素,该怎么办?然而,我将在很多图像上运行这个算法。循环遍历所有像素直到看到 2 种独特的颜色会更有效吗?因为我知道Python中的循环非常慢。
首先,让我们制作一个图像。我将使用 ImageMagick 制作带有洋红色文字的蓝色背景:
convert -size 300x120 -background blue -fill magenta -gravity center -font AppleChancery label:"StackOverflow" PNG24:image.png
如您所见,我只指定了两种颜色 - 洋红色和蓝色,但 PNG 图像实际上包含 200 多种颜色,JPEG 图像包含 2,370 种不同的颜色!
所以,如果我想获得两种主要颜色,我可以这样做:
from PIL import Image
# Open the image
im = Image.open('image.png')
# Quantize down to 2 colour palettised image using *"Fast Octree"* method:
q = im.quantize(colors=2,method=2)
# Now look at the first 2 colours, each 3 RGB entries in the palette:
print(q.getpalette()[:6])
结果示例
[0, 0, 255, 247, 0, 255]
如果将其写为 2 个 RGB 三元组,您将得到:
RGB 0/0/255 = blue
RGB 247/0/255 = magenta
对于大量图像执行此操作的最佳方法是使用多线程或多处理(如果您希望快速完成它们)!