Jimmy Kane Jimmy Kane - 4 months ago 33
Python Question

Python PIL Detect if an image is completely black or white

Using the Python Imaging Library PIL how can someone detect if an image has all it's pixels black or white?

~Update~

Condition: Not iterate through each pixel!

Answer
if not img.getbbox():

... will test to see whether an image is completely black. (Image.getbbox() returns the falsy None if there are no non-black pixels in the image, otherwise it returns a tuple of points, which is truthy.) To test whether an image is completely white, invert it first:

if not ImageChops.invert(img).getbbox():

You can also use img.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).

extrema = img.convert("L").getextrema()
if extrema == (0, 0):
    # all black
elif extrema == (1, 1):
    # all white

The latter method will likely be faster, but not so you'd notice in most applications (both will be quite fast).

A one-line version of the above technique that tests for either black or white:

if sum(img.convert("L").getextrema()) in (0, 2):
    # either all black or all white