Created
July 3, 2017 14:53
-
-
Save icaromag/a6e244cd920026e79b47e49bc58769c7 to your computer and use it in GitHub Desktop.
Snippet used to crop PNG image transparent borders (alpha 0).
This file contains 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
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