Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image
- import os
- white = (255, 255, 255, 255)
- # folder with the original image
- img_folder = "img/"
- # folder where the alpha is saved
- imgAlpha_folder = "img/alpha/"
- # Create target Directory if don't exist for the alpha folder
- if not os.path.exists(imgAlpha_folder):
- os.mkdir(imgAlpha_folder)
- print("Directory " , imgAlpha_folder , " Created ")
- else:
- print("Directory " , imgAlpha_folder , " already exists")
- for element in os.listdir(img_folder):
- if element.endswith('.png'):
- # print("'%s' is a png" % element)
- # Open the image and convert it to RGBA, just in case it was indexed
- image = Image.open(img_folder + element).convert('RGBA')
- # print(image.getbands)
- # Extract just the alpha channel
- alpha = image.split()[-1]
- # Unfortunately the alpha channel is still treated as such and can't be dumped
- # as-is
- # Create a new image with an opaque black background
- bg = Image.new("RGBA", image.size, (0,0,0,255))
- # Copy the alpha channel to the new image using itself as the mask
- bg.paste(alpha, mask=alpha)
- # Get the number of colors in the alpha channel
- colors = bg.getcolors()
- # If there is only one color, and it's white ( opaque) then do nothing
- if ( colors[0][1] == white and len(colors) == 1 ):
- print('no alpha channel')
- else: # else save the alpha channel as a new image with the same name + "_alpha"
- # Since the bg image started as RGBA, we can save some space by converting it
- # to grayscale ('L') Optionally, we can convert the image to be indexed which
- # saves some more space ('P') In my experience, converting directly to 'P'
- # produces both the Gray channel and an Alpha channel when viewed in GIMP,
- # althogh the file sizes is about the same
- mask_path = imgAlpha_folder + element.replace('.png', '_alpha.png')
- 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