Created
June 23, 2024 16:59
-
-
Save Imeguras/2186ee0ea60c16acbd16e70a3d533611 to your computer and use it in GitHub Desktop.
Ivo's preprocessing script
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 os | |
def resize_crop_and_flip(image_path, output_path, size=(250, 250)): | |
with Image.open(image_path) as img: | |
img_ratio = img.width / img.height | |
target_ratio = size[0] / size[1] | |
if img_ratio > target_ratio: | |
# Crop the width (crop horizontally) | |
new_height = img.height | |
new_width = int(target_ratio * new_height) | |
left = (img.width - new_width) / 2 | |
top = 0 | |
right = (img.width + new_width) / 2 | |
bottom = img.height | |
else: | |
# Crop the height (crop vertically) | |
new_width = img.width | |
new_height = int(new_width / target_ratio) | |
left = 0 | |
top = (img.height - new_height) / 2 | |
right = img.width | |
bottom = (img.height + new_height) / 2 | |
img_cropped = img.crop((left, top, right, bottom)) | |
img_resized = img_cropped.resize(size, Image.LANCZOS) | |
img_flipped = img_resized.transpose(Image.FLIP_LEFT_RIGHT) | |
img_flipped.save(output_path) | |
def process_images_in_folder(input_folder, output_folder, size=(250, 250)): | |
if not os.path.exists(output_folder): | |
os.makedirs(output_folder) | |
for filename in os.listdir(input_folder): | |
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff')): | |
input_path = os.path.join(input_folder, filename) | |
output_path = os.path.join(output_folder, filename) | |
resize_crop_and_flip(input_path, output_path, size) | |
input_folder = '.\imgs' | |
output_folder = '.\imgs_output' | |
process_images_in_folder(input_folder, output_folder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment