Python - find out how much of an image is black

blaylockbk picture blaylockbk · Jan 9, 2015 · Viewed 13.8k times · Source

I am downloading satellite pictures like this satellite_image
(source: u0553130 at home.chpc.utah.edu)

Since some images are mostly black, like this one, I don't want to save it.

How can I use python to check if the image is more than 50% black?

Answer

xnx picture xnx · Jan 9, 2015

You're dealing with gifs which are mostly grayscale by the look of your example image, so you might expect most of the RGB components to be equal.

Using PIL:

from PIL import Image
im = Image.open('im.gif')
pixels = im.getdata()          # get the pixels as a flattened sequence
black_thresh = 50
nblack = 0
for pixel in pixels:
    if pixel < black_thresh:
        nblack += 1
n = len(pixels)

if (nblack / float(n)) > 0.5:
    print("mostly black")

Adjust your threshold for "black" between 0 (pitch black) and 255 (bright white) as appropriate).