Skip to content

Instantly share code, notes, and snippets.

@rreece
Created February 17, 2019 23:35
Show Gist options
  • Save rreece/d51efaa8ee44b7af97810f1ba22fad5d to your computer and use it in GitHub Desktop.
Save rreece/d51efaa8ee44b7af97810f1ba22fad5d to your computer and use it in GitHub Desktop.
Crop the surrounding whitespace from an image with python
"""
Taken from here:
https://github.com/thumbor/thumbor/issues/116
"""
def crop_surrounding_whitespace(image):
"""Remove surrounding empty space around an image.
This implemenation assumes that the surrounding space has the same colour
as the top leftmost pixel.
:param image: PIL image
:rtype: PIL image
"""
bg = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, bg)
bbox = diff.getbbox()
if not bbox:
return image
return image.crop(bbox)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment