且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查RGB图像是否只包含一种颜色?

更新时间:2023-11-29 19:20:58

尝试 ImageStat模块。如果 extrema 返回的值相同,则图片中只有一种颜色。


I'm using Python and PIL.

I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001).

I was thinking about using the histogram but it is very hard to figure out something with the 3 color bands, so I'm looking for a more clever algorithm.

Any ideas?

ImageStat module is THE answer! Thanks Aaron. I use ImageStat.var to get the variance and it works perfectly.

Here is my piece of code:

from PIL import Image, ImageStat

MONOCHROMATIC_MAX_VARIANCE = 0.005

def is_monochromatic_image(src):
    v = ImageStat.Stat(Image.open(src)).var
    return reduce(lambda x, y: x and y < MONOCHROMATIC_MAX_VARIANCE, v, True)

Try the ImageStat module. If the values returned by extrema are the same, you have only a single color in the image.