Dispersion with Python's standard library and Pillow Find the RGB standard deviation of the image and determine if it is monochromatic

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

Dispersion with Python's standard library and Pillow Find the RGB standard deviation of the image and determine if it is monochromatic
Find the average / standard deviation of the brightness values in the image
Determine if the library is installed.
Use Pillow to make the image transparent and overlay only part of it
POST the image with json and receive it with flask
Return the image data with Flask of Python and draw it to the canvas element of HTML
I tried to find the entropy of the image with python
Hash with the standard library hashlib and compare login passwords
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
What to do when a part of the background image becomes transparent when the transparent image is combined with Pillow
What I did when I couldn't find the feature point with the optical flow of opencv and when I lost it