Skip to content

Instantly share code, notes, and snippets.

@icaromag
Created July 3, 2017 14:53
Show Gist options
  • Save icaromag/99e7061802d7fa656f55a23d51bb5100 to your computer and use it in GitHub Desktop.
Save icaromag/99e7061802d7fa656f55a23d51bb5100 to your computer and use it in GitHub Desktop.
Snippet used to crop PNG image transparent borders (alpha 0).
from PIL import Image
import numpy as np
from os import listdir
def crop(png_image_name):
pil_image = Image.open(png_image_name)
np_array = np.array(pil_image)
blank_element = [255, 255, 255, 0]
mask = np_array != blank_element
coords = np.argwhere(mask)
x0, y0, z0 = coords.min(axis=0)
x1, y1, z1 = coords.max(axis=0) + 1
cropped_box = np_array[x0:x1, y0:y1, z0:z1]
pil_image = Image.fromarray(cropped_box, 'RGBA')
pil_image.save(png_image_name)
for f in listdir('.'):
if f.endswith('.png'):
crop(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment