Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - find out how much of an image is black

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?

like image 384
blaylockbk Avatar asked Jan 09 '15 19:01

blaylockbk


People also ask

How do you know if an image is black in Python?

getextrema() . This will tell you the highest and lowest values within the image. To work with this most easily you should probably convert the image to grayscale mode first (otherwise the extrema might be an RGB or RGBA tuple, or a single grayscale value, or an index, and you have to deal with all those).

How do you count the number of black pixels?

For black images you get the total number of pixels (rows*cols) and then subtract it from the result you get from cv2. countNonZero(mat) .


1 Answers

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).

like image 154
xnx Avatar answered Sep 21 '22 09:09

xnx