Created
February 17, 2019 23:35
-
-
Save rreece/d51efaa8ee44b7af97810f1ba22fad5d to your computer and use it in GitHub Desktop.
Crop the surrounding whitespace from an image with python
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
""" | |
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