python 如何使用 PIL 减少调色板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1065945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:24:06  来源:igfitidea点击:

How to reduce color palette with PIL

pythonimagecolorspython-imaging-librarypalette

提问by Nadia Alramli

I'm not sure how I would go about reducing the color palette of a PIL Image. I would like to reduce an image's palette to the 5 prominent colors found in that image. My overall goal is to do some basic color sampling.

我不确定如何减少 PIL 图像的调色板。我想将图像的调色板减少到该图像中的 5 种突出颜色。我的总体目标是做一些基本的颜色采样。

回答by Nadia Alramli

That's easy, just use the undocumented colors argument:

这很简单,只需使用未记录的颜色参数:

result = image.convert('P', palette=Image.ADAPTIVE, colors=5)

I'm using Image.ADAPTIVE to avoid dithering

我正在使用 Image.ADAPTIVE 来避免抖动

回答by Paul

I assume you want to do something more sophisticated than posterize. "Sampling" as you say, will take some finesse, as the 5 most common colors in the image are likely to be similar to one another. Maybe take a look at the 5 most separated peaks in a histogram.

我假设您想做一些比posterize更复杂的事情。正如您所说的“采样”需要一些技巧,因为图像中最常见的 5 种颜色可能彼此相似。也许看看直方图中5 个最分离的峰值。

回答by tzot

The short answer is to use the Image.quantizemethod. For more info, see: How do I convert any image to a 4-color paletted image using the Python Imaging Library ?

简短的回答是使用该Image.quantize方法。有关详细信息,请参阅:如何使用 Python 成像库将任何图像转换为 4 色调色板图像?