[Image-SIG] Using PIL to automatically trim borders from an image

Fredrik Lundh fredrik at pythonware.com
Sun Jul 20 13:02:41 CEST 2008

Matt Howell wrote:

> Is there a straightforward way to use PIL to trim off the borders of an 
> image?
> I'm thinking of something equivalent to the trim() function in 
> ImageMagick.  It looks at the 4 corner pixels, figures out what color 
> the border is, and then trims out rows and columns from the image's 
> edges that match the border color.  So, as a use case, you could upload 
> an image with some arbitrary amount of whitespace around the main 
> content of the image, and trim out all that extra space.
> I don't see any equivalent built-in functionality in the PIL 
> documentation -- crop() seems to come closest but it lacks the extra 
> logic needed.  I'm not opposed to writing the logic myself, but I'd like 
> to avoid reinventing the wheel, if I can. :)

there's no built-in function to do this, but it's fairly easy to do this 
by combining a few builtins; given an image and a border color, you can 
do something like:

     from PIL import ImageChops

     def trim(im, border):
         bg = Image.new(im.mode, im.size, border)
         diff = ImageChops.difference(im, bg)
         bbox = diff.getbbox()
         if bbox:
             return im.crop(bbox)
             # found no content
             raise ValueError("cannot trim; image was empty")

for details, see:


(adding a color argument to getbbox could be pretty useful, I think)

writing code to determine a suitable border color (e.g. by inspecting 
the corners or the border row/columns) is left as an exercise.


More information about the Image-SIG mailing list