How to get alpha value of a PNG image with PIL?

后端 未结 5 1189
眼角桃花
眼角桃花 2020-11-30 02:46

How to detect if a PNG image has transparent alpha channel or not using PIL?

img = Image.open(\'example.png\', \'r\')
has_alpha = img.mode == \'RGBA\'
         


        
5条回答
  •  无人及你
    2020-11-30 03:00

    I tried this:

    from PIL import Image
    import operator, itertools
    
    def get_alpha_channel(image): 
       try: 
          alpha_index = image.getbands().index('A')
       except ValueError:
          # no alpha channel, so convert to RGBA
          image = image.convert('RGBA')
          alpha_index = image.getbands().index('A')
       alpha_getter = operator.itemgetter(alpha_index)
       return itertools.imap(alpha_getter, image.getdata())
    

    This returned the result that I was expecting. However, I did some calculation to determine the mean and standard deviation, and the results came out slightly different from imagemagick's fx:mean function.

    Perhaps the conversion changed some of the values? I'm unsure, but it seems relatively trivial.

提交回复
热议问题