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
try:
    img = Image.open(fileName)
    tempImg = img.load()
    del(tempImg)

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. 
    img.putalpha(alpha)

print 'Saving', fileName
img.save(fileName)

Challenger II 3d WIP - High Poly

Edit:
I'm grabbing scraps of time here and there to try and finish this one... here is another update to the high poly model...

Smoke candles, updates to periscopes, headlights and hooks.
Lights, tow equipment, first aid box etc etc...


-----
Random non-python update! This is something I have been tinkering with out of hours. Eventually it will be a low poly tank.

The high poly version is based off of a mix of photographic reference and a model kit I have had sitting in the cupboard for too long.

Still a couple of hours worth of work required on the machine gun (which is like a mini project itself!) rear of tank and various greebleish additions...

Challenger II WIP-

Challenger II

Challenger II

Challenger II