Skip to content

Instantly share code, notes, and snippets.

@FlorianLatapie
Last active August 4, 2023 15:28
Show Gist options
  • Save FlorianLatapie/6bdee189fd376a5b832cc25050ef0462 to your computer and use it in GitHub Desktop.
Save FlorianLatapie/6bdee189fd376a5b832cc25050ef0462 to your computer and use it in GitHub Desktop.
Python script to crop transparent pixels in .png images
from PIL import Image
import numpy as np
def crop_blank_pixels(path: str):
img = Image.open(path)
are_transparent_pixels = np.array(img)[:, :, 3] != 0
rows, cols = are_transparent_pixels.nonzero() # keep only non-transparent pixels
img.crop((cols.min(), rows.min(), cols.max() + 1, rows.max() + 1)).save(path)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Crop blank pixels from images.')
parser.add_argument('input_path', metavar='input_path', type=str, nargs='+', help='the path of the image to crop')
args = parser.parse_args()
for file_path in args.input_path:
crop_blank_pixels(file_path)
numpy==1.23.3
Pillow==10.0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment