Skip to content

Instantly share code, notes, and snippets.

@Nasawa
Last active July 28, 2016 18:31
Show Gist options
  • Save Nasawa/1c1abba9711d9d8b97457fbcda36c45d to your computer and use it in GitHub Desktop.
Save Nasawa/1c1abba9711d9d8b97457fbcda36c45d to your computer and use it in GitHub Desktop.
Trim image borders
import os
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)
img_types = ['jpg', 'peg', 'bmp', 'png', 'gif']#'peg' in case it says '.jpeg'
for root, dirs, files in os.walk("/imgroot"):#Folder where all images are stored, will walk recursively
for file in files:
if file[-3:] in img_types and "cropped" not in file:
im = Image.open(os.path.join(root, file))
im = trim(im)
im.save(os.path.join(root, "cropped_" + file))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment