-
-
Save cobaohieu/1abd471ec1f264b6df08de237265867c to your computer and use it in GitHub Desktop.
bulk resize image with python with its its corresponding subdirectory/folder
This file contains hidden or 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
# -*- coding: utf-8 -*- | |
""" | |
Clone on Wed Jul 21 16:39:29 2021 | |
@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: | |
./vegetables | |
├─Image1 | |
├─Image2 | |
├─Image3 | |
├─Image4 | |
New folder with its subdir: | |
./output | |
../vegetables | |
├─Image1 | |
├─Image2 | |
├─Image3 | |
├─Image4 | |
""" | |
# -*- coding: utf-8 -*- | |
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 = './vegetables' | |
NEW_SIZE = 416 | |
PATH = './output' #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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment