Last active
July 28, 2016 18:31
-
-
Save Nasawa/1c1abba9711d9d8b97457fbcda36c45d to your computer and use it in GitHub Desktop.
Trim image borders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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