原答案
我认为这符合你的要求:
from PIL import Image
# Load image
im = Image.open('logo.png')
# Convert to palette mode and save
im.convert('P').save('result.png')
更新答案
我找不到一种方法让 PIL 制作出合理的调色板图像,但可以通过其他几种方法来做到这一点......
要么与wand
像这样:
#!/usr/bin/env python3
from wand.image import Image
with Image(filename='logo.png') as img:
img.quantize(number_colors=256, colorspace_type='lab', treedepth=0, dither=False, measure_error=False)
img.save(filename='result.png')
或者,通过花钱购买图像魔术师在命令行并执行以下操作:
magick logo.png -colors 255 png8:logo8.png # use "convert" in place of "magick" if using v6
最新答案
好的,我找到了一种让 PIL/Pillow 做得更好的方法,正如预期的那样,它利用了libimagequant
它通常不会内置到 Pillow 中(至少在我所在的 macOS 上)。代码如下所示:
#!/usr/bin/env python3
from PIL import Image
# Load image
im = Image.open('logo.png')
# Convert to palette mode and save. Method 3 is "libimagequant"
im.quantize(colors=256, method=3).save('result.png')
在 macOS 上构建 PIL/Pillow 的步骤libimagequant
如下 - 它们在其他平台上会有所不同,但您应该能够了解总体思路并进行调整:
pip uninstall pillow # remove existing package
brew install libimagequant
brew install zlib
export PKG_CONFIG_PATH="/usr/local/opt/zlib/lib/pkgconfig"
pip install --upgrade Pillow --global-option="build_ext" --global-option="--enable-imagequant" --global-option="--enable-zlib"
Keywords:Python、图像处理、PIL/Pillow、libimagequant、macOS、量化、量化。