Skip to content

Instantly share code, notes, and snippets.

@durgaswaroop
Created October 28, 2018 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durgaswaroop/6aea3b5aae21090fc17bfde8f4532477 to your computer and use it in GitHub Desktop.
Save durgaswaroop/6aea3b5aae21090fc17bfde8f4532477 to your computer and use it in GitHub Desktop.
Image Resizer.
#!/usr/bin/env python
# coding: utf-8
# Run this from the directory where you see data/.
# %%sh
# ls -F
# data/
# Also create directory data_resized with test and train subdirectories
# %%sh
# ls -F
# data/
# data_resized/
# Install the python-resize-image package
# `pip install python-resize-image`
from PIL import Image
from resizeimage import resizeimage
import os
def resize_image(directory, image_name, new_directory, new_dims=[256, 256]):
with open(directory + image_name, 'r+b') as f:
with Image.open(f) as image:
cover = resizeimage.resize_cover(image, new_dims)
cover.save(new_directory + image_name, image.format)
def resize_images_into_new_directory(old_directory, new_directory):
for image_name in os.listdir(old_directory):
resize_image(old_directory, image_name, new_directory)
old_train_directory = 'data/train/'
old_test_directory = 'data/test/'
new_train_directory = 'data_resized/train/'
new_test_directory = 'data_resized/test/'
# Resize train data
resize_images_into_new_directory(old_train_directory, new_train_directory)
# Resize test data
resize_images_into_new_directory(old_test_directory, new_test_directory)
# Depending on your system configuration this can take quite a lot of time.
# On my machine (16 GB RAM, I5 8th gen processor), I was able to resize about 1800 images per minute.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment