Skip to content

Instantly share code, notes, and snippets.

@viniciusarruda
Created June 6, 2018 21:04
Show Gist options
  • Save viniciusarruda/8351348eaebabc92b00140ea54692564 to your computer and use it in GitHub Desktop.
Save viniciusarruda/8351348eaebabc92b00140ea54692564 to your computer and use it in GitHub Desktop.
Gets a centered square crop of all images that is inside a directory and resize all of them to a size with a specific side and outputs them to another directory.
from PIL import Image
import os
import numpy as np
def _square(img):
w, h = img.size
s = min(h, w)
sh = (h - s)/2.0
sw = (w - s)/2.0
cropped_img = img.crop((sw, sh, sw+s, sh+s))
return cropped_img
def _shrink(cropped_img, side):
return cropped_img.resize((side, side), resample=Image.LANCZOS)
def square_and_shrink(side, input_dir, output_dir):
for f in os.listdir(input_dir):
img = Image.open(input_dir + f)
cropped_img = _square(img)
resized_img = _shrink(cropped_img, side)
resized_img.save(output_dir + f)
square_and_shrink(256, 'images/', 'squared_and_shrinked/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment