我想将图像的位深度(颜色深度)降低到Python中的一组自定义颜色。从本质上讲,是为程序提供一组x色,并将其与全彩色图像中的每个像素与给定列表中最接近的颜色相关联。我在Pillow库上遇到了麻烦,如下所示。
根据从图像本身创建的调色板,此代码将正确地将图像“ Z.png”中的颜色减少到仅4种颜色:
from PIL import Image
colorImage = Image.open("Z.png")
imageWithColorPalette = colorImage.convert("P", palette=Image.ADAPTIVE, colors=4)
imageWithColorPalette.save("Output.png")
from IPython.display import Image
Image('Output.png')
这段代码类似,除了我尝试使用自己的调色板。问题在于此代码返回的代码与上述代码完全相同,并且似乎只是带有自适应调色板,而忽略了我尝试指定的自定义调色板:
from PIL import Image
pall = [
0, 0, 0,
255, 0, 0,
255, 255, 0,
255, 153, 0,
]
colorImage = Image.open("Z.png")
imageWithColorPalette = colorImage.convert("P", palette=pall, colors=4)
imageWithColorPalette.save("Output.png")
from IPython.display import Image
Image('Output.png')
基于此处的文档:https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert和https://pillow.readthedocs.io/en/3.0。 x / reference / ImagePalette.html。我假设我的pall格式/大小不正确,或者我需要在convert方法中包含一个矩阵参数。根据文档,矩阵参数为“可选转换矩阵。如果给出的话,它应该是包含浮点值的4或12元组。我不确定如何执行。
不管是什么问题,我都非常困惑,会寻求一些帮助。
Alternativley,我愿意接受建议,因此有更好的Python库可用于此任务。
我相信这符合您的要求
from PIL import Image
if __name__ == '__main__':
palette = [
159, 4, 22,
98, 190, 48,
122, 130, 188,
67, 153, 0,
]
img = Image.open('img.jpg')
p_img = Image.new('P', (16, 16))
p_img.putpalette(palette * 64)
conv = img.quantize(palette=p_img, dither=0)
conv.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句