Skip to content

Instantly share code, notes, and snippets.

@nmichlo
Last active January 20, 2021 08:41
Show Gist options
  • Save nmichlo/02c9e4ddffaa978199511c0917cdd2b7 to your computer and use it in GitHub Desktop.
Save nmichlo/02c9e4ddffaa978199511c0917cdd2b7 to your computer and use it in GitHub Desktop.
Pad portrait images that do not fit for instagram.
import imageio
import numpy as np
import sys
import os
import imagesize
if __name__ == '__main__':
assert len(sys.argv) >= 2, 'must supply at least 1 file argument'
WIDTH = 1080
HEIGHT = 1350
ASPECT_RATIO = HEIGHT / WIDTH
for i, path in enumerate(sys.argv[1:]):
try:
# get image size
w, h = imagesize.get(path)
aspect_ratio = h / w
if aspect_ratio <= ASPECT_RATIO:
print(f'\033[90m{i}: SKIPPING... {h}x{w} (~{HEIGHT}x{int(HEIGHT/h*w)}) {path=}\033[0m')
continue
# load image
img = imageio.imread(path)
h, w = img.shape[:2]
# compute new image size
new_w = int(np.ceil(h / ASPECT_RATIO))
new_size = (h, new_w, *img.shape[2:])
offset = (new_w - w) // 2
# create new image
new_img = np.full(new_size, 255, dtype=np.uint8)
new_img[:, offset:offset+w, :] = img
# write image to disk
name, ext = os.path.splitext(path)
new_path = f'{name}_padded{ext}'
imageio.imsave(new_path, new_img, quality=90)
print(f'{i}: Saved: {h}x{w} (~{HEIGHT}x{int(HEIGHT/h*w)}) -> {h}x{new_w} (~{HEIGHT}x{int(HEIGHT/h*new_w)}) {new_path=}')
except Exception as e:
print(f'{i}: Failed to process image {path=} with error {e=}')
@nmichlo
Copy link
Author

nmichlo commented Jan 20, 2021

Only processes images that need padding, does not overwrite original images & skips previously padded images.

Example usage with wildcard:

python portrait_ig_pad.py image_folder/IMG*.jpg

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