Last active
August 4, 2023 15:28
-
-
Save FlorianLatapie/6bdee189fd376a5b832cc25050ef0462 to your computer and use it in GitHub Desktop.
Python script to crop transparent pixels in .png images
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 | |
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) |
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
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