Advertisement
elyetis

extract.py

Jan 22nd, 2019
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. from PIL import Image
  2. import os
  3.  
  4. white = (255, 255, 255, 255)
  5.  
  6. # folder with the original image
  7. img_folder = "img/"
  8. # folder where the alpha is saved
  9. imgAlpha_folder = "img/alpha/"
  10.  
  11.  
  12. # Create target Directory if don't exist for the alpha folder
  13. if not os.path.exists(imgAlpha_folder):
  14.     os.mkdir(imgAlpha_folder)
  15.     print("Directory " , imgAlpha_folder ,  " Created ")
  16. else:    
  17.     print("Directory " , imgAlpha_folder ,  " already exists")
  18.    
  19.  
  20. for element in os.listdir(img_folder):
  21.     if element.endswith('.png'):
  22.         # print("'%s' is a png" % element)
  23.        
  24.         # Open the image and convert it to RGBA, just in case it was indexed
  25.         image = Image.open(img_folder + element).convert('RGBA')
  26.        
  27.         # print(image.getbands)
  28.        
  29.         # Extract just the alpha channel
  30.         alpha = image.split()[-1]
  31.  
  32.         # Unfortunately the alpha channel is still treated as such and can't be dumped
  33.         # as-is
  34.  
  35.         # Create a new image with an opaque black background
  36.         bg = Image.new("RGBA", image.size, (0,0,0,255))
  37.  
  38.         # Copy the alpha channel to the new image using itself as the mask
  39.         bg.paste(alpha, mask=alpha)
  40.        
  41.         # Get the number of colors in the alpha channel
  42.         colors = bg.getcolors()
  43.        
  44.         # If there is only one color, and it's white ( opaque) then do nothing
  45.         if ( colors[0][1] == white and len(colors) == 1 ):
  46.             print('no alpha channel')
  47.         else: # else save the alpha channel as a new image with the same name + "_alpha"
  48.        
  49.             # Since the bg image started as RGBA, we can save some space by converting it
  50.             # to grayscale ('L') Optionally, we can convert the image to be indexed which
  51.             # saves some more space ('P') In my experience, converting directly to 'P'
  52.             # produces both the Gray channel and an Alpha channel when viewed in GIMP,
  53.             # althogh the file sizes is about the same
  54.            
  55.             mask_path = imgAlpha_folder + element.replace('.png', '_alpha.png')
  56.            
  57.             bg.convert('L').convert('P', palette=Image.ADAPTIVE, colors=8).save(mask_path, optimize=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement