Monthly Archives: February 2017

Autocropping with Python

import argparse
import Image
import ImageChops

def parseArgs():
    parser = argparse.ArgumentParser()
    parser.add_argument("source", metavar = "SOURCE")
    parser.add_argument("target", metavar = "TARGET")
    return parser.parse_args()

args = parseArgs()
source = Image.open(args.source)
background = Image.new(source.mode, source.size, source.getpixel((0, 0)))
difference = ImageChops.difference(source, background)
source.crop(difference.getbbox()).save(args.target)