1

I'm mostly using Pillow library but I can use something else. I can extract the color layer including the alpha one. I'm wondering if there is a way to quickly define if a picture use transparency or not.

pic = Image.open(path)
red, green, blue, alpha = pic.split()

Is there a way to see if the alpha is really used or only available because the format support it (e.g.: PNG)

Aurélien B
  • 4,590
  • 3
  • 34
  • 48

1 Answers1

3

I don't know about Pillow, but you can use numpy and matplotlib.pyplot to load and examine the image. These are very widespread python libraries.

You can load the image into an numpy array and check the length of the last axis. If it's 3, then there's no alpha channel. If it's 4, there is an alpha channel present.

import matplotlib.pyplot as plt
pic = plt.imread(path)

if pic.shape[2] == 3:
    print("No alpha channel!")
if pic.shape[2] == 4:
    print("There's an alpha channel!")

If you want to know whether that channel is actually used (if present), you can check if it's 1 everywhere:

import numpy as np
if np.allclose(pic[:, :, 3], 1):
    print("Alpha not used because 1 everywhere!")
clemisch
  • 967
  • 8
  • 18
  • Staying in Pillow with the link from @mingganz is probably better in this case. But maybe have a look at working with PNGs as `numpy` arrays anyway, it is very flexible and powerful. – clemisch Jul 19 '18 at 08:46