如何使用RGB图像上的调色板提取主色调?

2024-09-30 10:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个模块,可以从图像中提取主色调。例如,我试图从这幅旗帜图像中提取四种颜色:

enter image description here

如果我尝试在RGB模式下使用getpalettegetcolors方法,则返回None。(我试过设置maxcolors,但仍然得到None。)

paletted = img.convert('RGB', palette=Image.ADAPTIVE, colors=4)
print(paletted.getpalette())
print(paletted.getcolors(maxcolors=256))
# None
# None

如果我转换为P模式,我可以使用这些模块,但我会丢失黄色

paletted = img.convert('P', palette=Image.ADAPTIVE, colors=4)
paletted.show()

enter image description here

我做错了什么


Tags: 模块图像imagenoneconvertimg模式rgb
1条回答
网友
1楼 · 发布于 2024-09-30 10:34:50

首先,以下内容不起作用,或者准确地说,被忽略了:

paletted = img.convert('RGB', palette=Image.ADAPTIVE, colors=4)

从关于^{}的文件中:

palette – Palette to use when converting from mode "RGB" to "P". Available palettes are WEB or ADAPTIVE.

您正在从RGB转换为RGB,因此palettecolors参数被忽略

下一个问题,也会阻止正确转换到模式P:您有一个带有JPG工件的JPG图像。您的图像包含的颜色比您预期的多得多。从关于^{}的文件中:

maxcolors – Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors.

增加maxcolors(对于一些完整的24位RGB图像,可能的最大不同颜色数为224),并检查四种最突出的颜色:

from PIL import Image

img = Image.open('47ckF.jpg')
n_dom_colors = 4
dom_colors = sorted(img.getcolors(2 ** 24), reverse=True)[:n_dom_colors]
print(dom_colors)
# [(135779, (0, 0, 0)), (132476, (0, 0, 254)), (109155, (254, 0, 0)), (2892, (251, 2, 0))]

你会得到纯黑色、近纯蓝色、近纯红色和红色的变体。黄色在哪里?JPG工件!你有很多带黑色、带蓝色和带红色的颜色,它们都比第一种带黄色的颜色更突出。例如,即使设置n_dom_colors = 20也不会显示第一种黄色

如何实现,你的想法是什么?请看一下^{},它将为您提供一个使用颜色量化的模式P图像:

from PIL import Image

img = Image.open('47ckF.jpg')
img = img.quantize(colors=4, kmeans=4).convert('RGB')
n_dom_colors = 4
dom_colors = sorted(img.getcolors(2 ** 24), reverse=True)[:n_dom_colors]
print(dom_colors)
# [(139872, (1, 0, 1)), (138350, (0, 0, 253)), (134957, (252, 1, 1)), (3321, (253, 240, 12))]

你会得到近乎纯黑色、近乎纯蓝色、近乎纯红色和黄色的变体

作为参考,量化和重新转换的图像:

Quantized

                    
System information
                    
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
PyCharm:       2021.1.1
Pillow:        8.2.0
                    

相关问题 更多 >

    热门问题