11

使用 Python Imaging Library,我可以调用

img.convert("P", palette=Image.ADAPTIVE)

或者

img.convert("P", palette=Image.WEB)

但是有没有办法转换为任意调色板?

p = []
for i in range(0, 256):
    p.append(i, 0, 0)
img.convert("P", palette=p)

它将每个像素映射到图像中最接近的颜色?还是仅支持此功能Image.WEB

4

2 回答 2

9

在查看源代码时,convert()我看到它引用了im.quantize. quantize可以采用调色板参数。如果您提供具有调色板的图像,则此函数将获取该调色板并将其应用于图像。

例子:

    src = Image.open("sourcefilewithpalette.bmp")
    new = Image.open("unconvertednew24bit.bmp")
    converted = new.quantize(palette=src)
    converted.save("converted.bmp")

The other provided answer didn't work for me (it did some really bad double palette conversion or something,) but this solution did.

于 2012-03-23T02:51:56.067 回答
3

ImagePalette 模块文档的第一个示例展示了如何将调色板附加到图像,但该图像必须已经是 mode"P""L". 但是,可以调整示例以将完整的 RGB 图像转换为您选择的调色板:

from __future__ import division
import Image

palette = []
levels = 8
stepsize = 256 // levels
for i in range(256):
    v = i // stepsize * stepsize
    palette.extend((v, v, v))

assert len(palette) == 768

original_path = 'original.jpg'
original = Image.open(original_path)
converted = Image.new('P', original.size)
converted.putpalette(palette)
converted.paste(original, (0, 0))
converted.show()
于 2010-06-25T02:51:18.290 回答