Skip to content

Instantly share code, notes, and snippets.

@justudin
Last active November 16, 2021 16:06
Show Gist options
  • Save justudin/2c1075cc4fd4424cb8ba703a2527958b to your computer and use it in GitHub Desktop.
Save justudin/2c1075cc4fd4424cb8ba703a2527958b to your computer and use it in GitHub Desktop.
bulk resize image with python with its its corresponding subdirectory/folder
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 13:59:03 2020
@author: xyz
This code is used to resize the images from dir/subdir to new directory (newdir/subdir) with its corresponding subdirectory
Original folder with it subdir:
..\DATA\ORI-DIR
├─Apolo
├─Bailey
├─Bandit
├─Bella
New folder with its subdir:
..\DATA\NEW-RESIZED-DIR
├─Apolo
├─Bailey
├─Bandit
├─Bella
"""
from PIL import Image
import glob
import os
# new folder path (may need to alter for Windows OS)
# change path to your path
ORI_PATH = '..\DATA\ORI-DIR'
NEW_SIZE = 224
PATH = '..\DATA\NEW-RESIZED-DIR' #the path where to save resized images
# create new folder
if not os.path.exists(PATH):
os.makedirs(PATH)
# loop over existing images and resize
# change path to your path
for filename in glob.glob(ORI_PATH+'**/*.jpg'): #path of raw images with is subdirectory
img = Image.open(filename).resize((NEW_SIZE,NEW_SIZE))
# get the original location and find its subdir
loc = os.path.split(filename)[0]
subdir = loc.split('\\')[1]
# assembly with its full new directory
fullnew_subdir = PATH+"/"+subdir
name = os.path.split(filename)[1]
# check if the subdir is already created or not
if not os.path.exists(fullnew_subdir):
os.makedirs(fullnew_subdir)
# save resized images to new folder with existing filename
img.save('{}{}{}'.format(fullnew_subdir,'/',name))
@haimon1442
Copy link

haimon1442 commented Jun 11, 2021

File "", line 45
subdir = loc.split('')[1]
^
SyntaxError: EOL while scanning string literal
i have occured this problem when i am trying to run your code consider that i am using windows os

@dhrubapuc23
Copy link

@haimon1442
Use subdir = loc.split('/')[-1]
it works for me.

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