I wanted to judge whether the image was monochromatic, so I searched variously, but there seems to be no easy way to check it.
As a result of thinking, if the RGB variance is found to be 0, it should be judged as a single color.
If you use numpy or something, you can do distributed calculations quickly, but I didn't want to put in numpy just for this, so I implemented it only with the standard library and Pillow.
from PIL import Image
rgb = list(Image.open(que.image).getdata())
avg_rgb = [sum(x)/len(rgb) for x in zip(*rgb)]
var_rgb = [sum(map(lambda p: (p - a) ** 2, x)) / len(x) for x, a in zip([t for t in zip(*rgb)], avg_rgb)]
std = sqrt(sum(var_rgb))
Now it should be monochromatic with sum (var_rgb) == 0
Postscript: If the variance is 0, it is a little too monochromatic and unusable. It is good to calculate up to the standard deviation and use it. The threshold depends on what you want to judge, but about 25 seems to be good for practical use.
Speaking of which, when I get RGB from Pillow's Image, I get an error saying decoder jpeg not available
.
brew install libjpeg
pip uninstall pillow
pip install pillow
Healed with. It seems that the pillow version, which did not include libjpeg, was old.
Recommended Posts