Trim whitespace using PIL

I don’t think there is anything built in to PIL that can do this. But I’ve modified your code so it will do it.

  • It gets the border colour from the top left pixel, using getpixel, so you don’t need to pass the colour.
  • Subtracts a scalar from the differenced image, this is a quick way of saturating all values under 100, 100, 100 (in my example) to zero. So is a neat way to remove any ‘wobble’ resulting from compression.

Code:

from PIL import Image, ImageChops

def trim(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)

im = Image.open("bord3.jpg")
im = trim(im)
im.show()

Heavily compressed jpeg:

enter image description here Cropped: enter image description here

Noisy jpeg:

enter image description here Cropped: enter image description here

Leave a Comment