Skip to content

Instantly share code, notes, and snippets.

@durgaswaroop
Last active October 28, 2018 22:03
Show Gist options
  • Save durgaswaroop/824cc06a1fc0aa57a670b3cd4a2e5a10 to your computer and use it in GitHub Desktop.
Save durgaswaroop/824cc06a1fc0aa57a670b3cd4a2e5a10 to your computer and use it in GitHub Desktop.
Resizes images in one directory and saves them in another directory.
#!/usr/bin/env python
# coding: utf-8
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.
@durgaswaroop
Copy link
Author

durgaswaroop commented Oct 28, 2018

I have written this program for the Kaggles Human protein image classification data but you can use this for any data you want.

Run this from the directory where you see data/ folder.

$ ls -F
data/

Also create the directory data_resized with test and train subdirectories

$ ls -F
data/
data_resized/

You would need to install the python-resize-image package

pip install python-resize-image

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 on average.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment