如何将Pillow的Image.convert()与自定义调色板一起使用?

JJC:

我想将图像的位深度(颜色深度)降低到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.converthttps://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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

用自定义调色板调用gimp_image_convert_indexed,找不到调色板

使用自定义调色板将numpy数组转换为RGB img

R Leaflet-将日期或字符图例标签与colorNumeric()调色板一起使用

如何在Angular中使用自定义主题调色板?

如何创建由scale_fill_manual()使用的自定义调色板

如何为 InkToolbarBallpointPenButton 自定义自定义调色板的悬停行为?

如何同时使用ColorBrewer调色板将我的自定义图例顺序保留在R中?

如何在AnyLogic中创建自定义调色板

创建vscode主题时如何自定义命令调色板颜色

创建 vscode 主题时如何自定义命令调色板颜色和键绑定

如何自定义从Android Studio的调色板添加的工具栏

如何在R中为ggplot自定义调色板?

如何为Material Design App创建具有自定义颜色的自定义调色板?

使用相同的自定义调色板将 8bpp 索引位图转换为 24bpp 并再次返回

如何将Spring REST Projections与自定义控制器一起使用

如何将 ConcurrentWebSocketSessionDecorator 与自定义 WebSocketHandler 一起使用

如何将 Firebase 存储与自定义服务器一起使用?

如何将boost :: assign与扩展STL容器的自定义容器一起使用?

如何将Picasso与用于RecyclerView的自定义适配器一起使用

如何将sklearn Pipeline与自定义功能一起使用?

如何将AWS Cognito与自定义NodeJS服务器一起使用?

如何将dask.dataframe与自定义dsk图一起使用

如何将 lodash sortBy 与自定义订单比较器一起使用

PS7.1-如何将管道链接与自定义功能一起使用?

如何将标准验证数据注释与自定义类型一起使用?

如何将Alamofire与自定义标头一起使用

如何将AngularJS自定义元素与玉一起使用?

如何将azure流量管理与自定义服务url端点一起使用?

如何将MultiDex与自定义Application类一起使用?