PIL- Applying a threshold to an image's alpha

If you are using PIL (python imaging library) for batch processing textures you might find this useful.

I used this little bit of code in one of my batch texture reduction scripts to apply a threshold to the alpha channel. This is to make sure it is still one bit after the size reduction, but also leaves the other channels intact.

Here is the snippet:

from PIL import Image

fileName = r'C:\temp\test_image.tga'

#Load the image
    img = Image.open(fileName)
    tempImg = img.load()

except IOError:
    print "*** IOError: %s\n" % sys.exc_info()[1].message

#Test if the image actually *has* an alpha channel
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):

    #create a threshold value
    threshold = 128

    #Create a reference to the alpha channel using the split function
    alpha = img.split()[3]

    #Apply the threshold using the point function
    alpha = alpha.point(lambda p: p > threshold and 255)

    #Paste a copy of the alpha object that has had the threshold applied. 

print 'Saving', fileName