Skip to content

Instantly share code, notes, and snippets.

@seiteta
Created February 3, 2017 17:41
Show Gist options
  • Save seiteta/0c6a4aa6119f1cfbc35fb2e9724ad948 to your computer and use it in GitHub Desktop.
Save seiteta/0c6a4aa6119f1cfbc35fb2e9724ad948 to your computer and use it in GitHub Desktop.
Image cropper
import os
from PIL import Image
# Parameters to be specified:
origin_folder = "path"
destination_folder = "path"
top_ratio = 0.15
# Create the destination folder if it doesn't exist
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
# Create the croping function
def croper(image_path, top_ratio):
"""
Crop images and make them square. One rectangle is remove at the top of
the image, another rectangle is remove at the bottom.
Parameters:
image_path => Absolute path of the original image (string)
top_ratio => Ratio between the top and the bottom rectangles to be removed (float)
"""
image = Image.open(image_path)
width, heigth = image.size
crop = heigth - width
# TODO: Check if top_ratio is between 0 and 1
top_crop = top_ratio * crop
down_crop = crop - top_crop
croped_image = image.crop((0, top_crop, width, heigth-down_crop))
return(croped_image)
# List all the files in the folder
# TODO: Check if files are images
image_names = next(os.walk(origin_folder))[2]
# Crop every images in the origin folder and save them in the destination folder
for image_name in image_names:
croped_image = croper(origin_folder + image_name, top_ratio)
croped_image.save(destination_folder + image_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment