Skip to content

Instantly share code, notes, and snippets.

@mikkohei13
Created November 23, 2022 12:42
Show Gist options
  • Save mikkohei13/592b6824ed4549b13eddcc591f9f43b7 to your computer and use it in GitHub Desktop.
Save mikkohei13/592b6824ed4549b13eddcc591f9f43b7 to your computer and use it in GitHub Desktop.
Crop images in a folder
import os
from os import listdir
from PIL import Image
# get the path/directory
source_dir = "images/Carpocoris_fuscispinus"
target_dir = "images/carp_fusc_crop"
limit = 300
i = 1
for image in os.listdir(source_dir):
# check if the image ends with png
if (image.endswith(".jpg")):
print(image)
im = Image.open(source_dir + "/" + image)
w, h = im.size
# Crop to 1/3
'''
target_w = round(w / 3)
target_h = round(h / 3)
print(f"{target_w}, {target_h}")
im_cropped = im.crop((target_w, target_h, target_w * 2, target_h * 2))
im_cropped = im_cropped.save(dirname + "/crop_" + image)
'''
# Crop to 1/2
target_w = round(w / 2)
target_h = round(h / 2)
print(f"{target_w}, {target_h}")
im_cropped = im.crop((target_w/2, target_h/2, target_w/2*3, target_h/2*3))
im_cropped = im_cropped.save(target_dir + "/crop_" + image)
i = i + 1
if i >= limit:
print(f"Limit of {limit} reached")
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment