Created
March 28, 2015 01:53
-
-
Save zhy0216/de468b7440d215ec5b2f to your computer and use it in GitHub Desktop.
Remove any unnecessary whitespace from the edges of the source image
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
# copy from easy_thumbnails | |
from PIL import Image, ImageChops | |
def is_transparent(image): | |
""" | |
Check to see if an image is transparent. | |
""" | |
if not isinstance(image, Image.Image): | |
# Can only deal with PIL images, fall back to the assumption that that | |
# it's not transparent. | |
return False | |
return (image.mode in ('RGBA', 'LA') or | |
(image.mode == 'P' and 'transparency' in image.info)) | |
def autocrop(im, **kwargs): | |
""" | |
Remove any unnecessary whitespace from the edges of the source image. | |
This processor should be listed before :func:`scale_and_crop` so the | |
whitespace is removed from the source image before it is resized. | |
autocrop | |
Activates the autocrop method for this image. | |
""" | |
# If transparent, flatten. | |
if is_transparent(im) and False: | |
no_alpha = Image.new('L', im.size, (255)) | |
no_alpha.paste(im, mask=im.split()[-1]) | |
else: | |
no_alpha = im.convert('L') | |
# Convert to black and white image. | |
bw = no_alpha.convert('L') | |
# bw = bw.filter(ImageFilter.MedianFilter) | |
# White background. | |
bg = Image.new('L', im.size, 255) | |
bbox = ImageChops.difference(bw, bg).getbbox() | |
if bbox: | |
im = im.crop(bbox) | |
return im | |
if __name__ == "__main__": | |
import sys | |
image_name_list = sys.argv[1:] | |
name_dict = dict(map(lambda _: _.split('.'), image_name_list)) | |
for pre_name in name_dict: | |
full_name = pre_name + '.' + name_dict[pre_name] | |
im = Image.open(full_name) | |
croped_im = autocrop(im) | |
croped_im.save(pre_name + "_croped." + name_dict[pre_name]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment