Created
October 28, 2018 21:53
-
-
Save durgaswaroop/b4157b15433d038de45c0da04c3fb177 to your computer and use it in GitHub Desktop.
Image Resizer.
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
#!/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