Removing white pixels from figures


Quite often, especially when you are working with presentations, you may realize that you need to remove the white background from your figures. One way is to use any photo editing software like Gimp for example and remove the background. But if you have a lot of files and you don’t need smoothing or any other effect you can also use a simple script like this:

#!/usr/bin/env python 
#source : http://stackoverflow.com/a/765829
from PIL import Image
import sys
white = (255, 255, 255, 255)
transparent = (255, 255, 255, 0)
for infile in sys.argv[1:]:
    img = Image.open(infile)
    img = img.convert("RGBA")

    pixdata = img.load()

    for y in xrange(img.size[1]):
        for x in xrange(img.size[0]):
            if pixdata[x, y] == white:
                pixdata[x, y] = transparent

    img.save(infile + "_modified", "PNG")

source