Skip to content

Instantly share code, notes, and snippets.

@tiff
Created March 28, 2018 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiff/5c2a01a66119d8e5d48c7b8dbf35a15c to your computer and use it in GitHub Desktop.
Save tiff/5c2a01a66119d8e5d48c7b8dbf35a15c to your computer and use it in GitHub Desktop.
Trim image whitespace
import numpy as np
from PIL import Image, ImageChops
import sys
import numpy as np
def trim(im):
bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
size = im.size
top_left_pixel = im.getpixel((0,0))
bottom_right_pixel = im.getpixel((size[0] - 1, size[1] - 1))
is_top_left_white = top_left_pixel[0] >= 240 and top_left_pixel[1] >= 240 and top_left_pixel[2]
is_bottom_right_white = bottom_right_pixel[0] >= 240 and bottom_right_pixel[1] >= 240 and bottom_right_pixel[2] >= 240
is_top_left_transparent = top_left_pixel[3] < 20 if len(top_left_pixel) > 3 else False
is_bottom_right_transparent = bottom_right_pixel[3] < 20 if len(bottom_right_pixel) > 3 else False
if (is_top_left_white and is_bottom_right_white) or (is_top_left_transparent and is_bottom_right_transparent):
diff = ImageChops.difference(im, bg)
offset = round(size[1] / 100 * 4);
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
return im.crop((max(bbox[0] - offset, 0), max(bbox[1] - offset, 0), min(bbox[2] + offset, size[0]), min(bbox[3] + offset, size[1])))
else:
return im
else:
print('No change because no transparency or no white background')
return im
im = Image.open(sys.argv[1])
im = trim(im)
im.save(sys.argv[2])
@tiff
Copy link
Author

tiff commented Mar 28, 2018

Usage:

python trim.py input.jpg output.jpg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment