简体   繁体   中英

How to determine if a png picture has a transparency layer in Python

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 (eg: PNG)

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!")

I was able to come up with an answer that uses Pillow's built-in features. Feel free to check out https://stackoverflow.com/a/58567453/2608838 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM