Related
I want to loop over a batch of files in order to get 32 images of each sub-directory at a time (I cant load all images due to memory) e.g load img 1-32 of every dir use them and then load img 33-64 then 65-96 etc
My directory:
Rootdir
- dir1
- img 1
- img 2
- img...
- dir2
- img 5000001
- img 5000002
- img...
- dir3
- img 10000001
- img 10000002
- img...
So I would need to load img1,2,..,32, 5000001,...5000032, 1000001,...10000032 at first loop then img33,34,..,64, 5000033,...5000064, 1000033,...10000064 at second loop
Is there a way to do this properly?
I am trying using os.walk and it allows me to loop over my directory but I don't see how I can adapt this loop to my required 32 batches?
for dirName, subdirList, fileList in os.walk(rootdir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
img_path = os.path.join(dirName, fname)
try:
img = load_img(img_path, target_size=None)
imgs.append(img)
except Exception as e:
print(str(e), fname, i)
#do something on imgs
EDIT
all of your comment get me stuff like that:
dir1/img1.jpg to dir1/img32.jpg then dir1/img33.jpg to dir1/img64.jpg then
...
then dir2/img1.jpg to dir1/img32.jpg then dir2/img33.jpg to dir2/img64.jpg then ...
then dir3/img1.jpg to dir3/img32.jpg then dir3/img33.jpg to dir3/img64.jpg :(
What I'm trying to achieve is:
Files of dir1 numero 1 to 32 + files of dir2 numero 1 to 32 + files of dir3 numero 1 to 32 then
Files of dir1 numero 33 to 64 + files of dir2 numero 33 to 64 + files of dir3 numero 33 to 64 in the same loop
os.walk already returns a generator which will yield a 3-tuple (dirpath, dirnames, filenames) values on fly, so you just need to yield the slice of the filenames array in batches of 32.
This is an example:
import os
# Your root directory path
rootdir = r"Root"
#Your batch size
batch_size = 32
def walk_dirs(directory, batch_size):
walk_dirs_generator = os.walk(directory)
for dirname, subdirectories, filenames in walk_dirs_generator:
for i in range(0, len(filenames), batch_size):
# slice the filenames list 0-31, 32-64 and so on
yield [os.path.join(dirname, filename) for filename in filenames[i:i+batch_size]]
# Finally iterate over the walk_dirs function which itself returns a generator
for file_name_batch in walk_dirs(rootdir, batch_size):
for file_name in file_name_batch:
# Do some processing on the batch now
print (file_name)
pass
You could take a look at os.walk()
EDIT: simple counter example
counter = 0
for x in mylist:
# do something with x
todo_list.append(x)
counter += 1
if counter % 32 == 0:
# do something with todo list
todo_list = [] # empty todo list for next batch
What about always using the same img list and process it as soon as you have 32 images?
for dirName, subdirList, fileList in os.walk('c:\\Java\\'):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
img_path = os.path.join(dirName, fname)
try:
img = load_img(img_path, target_size=None)
imgs.append(img)
if len(imgs) == 32:
print("Doing what I have to with current imgs list (add your function here)")
img = [] # cleaning img list
except Exception as e:
print(str(e))
#do something on imgs
if you need to keep track of all the previous lists you can simply copy the list content over.
Let me know if you want that implementation too.
Okay I found a way, not the most beautiful but here it is:
I use a set to know which file I already seen and I continue if I'm on it so it doesn't count.
number_of_directory = 17
batch_size = 32
seen = set()
for overall_count in pbar(range(data_number // (batch_size * number_of_directory))):
imgs = []
for dirName, subdirList, fileList in os.walk(rootdir):
count = 0
for fname in sorted(fileList):
if fname in seen:
continue
if count == batch_size:
break
img_path = os.path.join(dirName, fname)
try:
img = cv2.imread(img_path, cv2.IMREAD_COLOR)
img = cv2.resize(img, (img_width, img_height))
imgs.append(np.array(img))
except Exception as e:
print(str(e), fname)
seen.add(fname)
count +=1
#Do something with images
I have a bunch of jpgs in one folder (images) that I want to copy across to another folder (destination_folder). When they are copied across, I want the jpg files to be renamed as follows: filename1_red.jpg, filename2_red.jpg (i.e. adding on the suffix _red at the end)
I have the following so far:
import os
images = os.listdir('C:/Users/Admin-dsc/Documents/.../buses and motorcycles')
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
for img in images:
filename = os.path.basename(img)
copyfile(img, os.path.join(destination_folder, filename))
Question 1: I get this error that I don't understand - how do I resolve it:
FileNotFoundError: [Errno 2] No such file or directory: 'RWG074059_2_o.jpg'
Question 2: I am unsure how to get the suffix.
Can anyone help?
os.listdir returns just the file names of the files in the specified folder, it doesn't return the complete path to the file. So, you need to join the source folder path with img:
import os
from shutil import copyfile
source_folder = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
images = os.listdir(source_folder)
for img in images:
filename, ext = os.path.splitext(img)
filename = filename + '_red' + ext
copyfile(os.path.join(source_folder, img), os.path.join(destination_folder, filename))
How to debug this error:
import os
directory = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
images = os.listdir(directory)
for img in images:
print(img)
filename = os.path.basename(img)
print(filename)
Output:
main.py
main.py
What you can see:
You see that listdir() only returns filenames. You need to prepend the source folder again.
How to fix:
import os
directory = './'
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
images = os.listdir(directory)
for img in images:
print(img)
filename = os.path.basename(img)
print(filename)
# prepend path again
source = os.path.join(directory,img)
target = os.path.join(destination_folder,img)
print(source, "=>", target)
# copyfile(source, target)
Output:
./main.py => C:/Users/Admin-dsc/Documents/.../Buses/main.py
img only contains the name of the image, not the complete path information.
Build an aboslute path instead when you specify the source image:
import os
source_folder = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
images = os.listdir(source_folder)
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
for img in images:
filename = os.path.basename(img)
copyfile(os.path.join(source_folder, img), os.path.join(destination_folder, filename))
I want to read multiple .jpg images, that are in 3 separate folders. The 3 folders are on the same path. I tried to do it like this:
path1 = os.path.abspath('Type_1')
path2 = os.path.abspath('Type_2')
path3 = os.path.abspath('Type_3')
folder = os.path.join(path1, path2, path3)
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
if filename.endswith(".jpg"):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
print(load_images_from_folder(folder))
But it only returns the last path and not all of them. I also tried to use relative paths, such as:
path1 = os.path.relpath('Type_1')
path2 = os.path.relpath('Type_2')
path3 = os.path.relpath('Type_3')
folder = os.path.join(os.path.sep, path1, path2, path3)
but still the same problem. Can someone help with this?
Your return images line is inside your loop, so it will return as soon as it finds any matching result. You only want it to return after the whole loop as finished.
Reduce the indentation of the return statement so that it lies after the loop instead of inside it.
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
if filename.endswith(".jpg"):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
[Edit]
If you want to look in multiple adjacent folders, you want something like this:
root_folder = '[whatever]/data/train'
folders = [os.path.join(root_folder, x) for x in ('Type_1', 'Type_2', 'Type_3')]
all_images = [img for folder in folders for img in load_images_from_folder(folder)]
That will call load_images on each folder, and put all the results into one list.
If I understand the problem correctly, your file structure looks as follows:
- Type1
- Image1.jpg
- Image2.jpg
- Type2
- Image1.jpg
- Image2.jpg
- Type3
- Image1.jpg
- Image2.jpg
If this is true, then the os.path.join call is errant (it'll result in a string that reads "Type1/Type2/Type3" which achieves nothing for you).
I think the code you're looking for is as follows:
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
if any([filename.endswith(x) for x in ['.jpeg', '.jpg']]):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
folders = [
'Type1',
'Type2',
'Type3',
]
for folder in folders:
images = load_images_from_folder(folder)
# your code that does something with the return images goes here
I know this is really old, but this worked for me recently.
def create_dataset(img_folder):
img_data_array=[]
class_name=[]
for dirl in os.listdir(img_folder):
for file in os.listdir(os.path.join(img_folder,dirl)):
if any([file.endswith(x) for x in ['.jpeg', '.jpg']]):
image_path=os.path.join(img_folder,dirl,file)
image=cv2.imread(image_path,cv2.COLOR_BGR2RGB)
img_data_array.append(image)
class_name.append(dirl)
return img_data_array,class_name
img_data, class_name =create_dataset(train_folder)
I have the following code that I thought would resize the images in the specified path
But when I run it, nothing works and yet python doesn't throw any error so I don't know what to do. Please advise. Thanks.
from PIL import Image
import os, sys
path = ('C:\Users\Maxxie\color\complete')
def resize():
for item in os.listdir(path):
if os.path.isfile(item):
im = Image.open(item)
f, e = os.path.splitext(item)
imResize = im.resize((200,200), Image.ANTIALIAS)
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
resize()
#!/usr/bin/python
from PIL import Image
import os, sys
path = "/root/Desktop/python/images/"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((200,200), Image.ANTIALIAS)
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
resize()
Your mistake is belong to full path of the files. Instead of item must be path+item
John Ottenlips's solution created pictures with black borders on top/bottom i think because he used
Image.new("RGB", (final_size, final_size))
which creates a square new image with the final_size as dimension, even if the original picture was not a square.
This fixes the problem and, in my opinion, makes the solution a bit clearer:
from PIL import Image
import os
path = "C:/path/needs/to/end/with/a/"
resize_ratio = 0.5 # where 0.5 is half size, 2 is double size
def resize_aspect_fit():
dirs = os.listdir(path)
for item in dirs:
if item == '.jpg':
continue
if os.path.isfile(path+item):
image = Image.open(path+item)
file_path, extension = os.path.splitext(path+item)
new_image_height = int(image.size[0] / (1/resize_ratio))
new_image_length = int(image.size[1] / (1/resize_ratio))
image = image.resize((new_image_height, new_image_length), Image.ANTIALIAS)
image.save(file_path + "_small" + extension, 'JPEG', quality=90)
resize_aspect_fit()
In case you want to keep the same aspect ratio of the image you can use this script.
from PIL import Image
import os, sys
path = "/path/images/"
dirs = os.listdir( path )
final_size = 244;
def resize_aspect_fit():
for item in dirs:
if item == '.DS_Store':
continue
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
size = im.size
ratio = float(final_size) / max(size)
new_image_size = tuple([int(x*ratio) for x in size])
im = im.resize(new_image_size, Image.ANTIALIAS)
new_im = Image.new("RGB", (final_size, final_size))
new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
resize_aspect_fit()
Expanding on the great solution of #Sanjar Stone
for including subfolders and also avoid DS warnings you can use the glob library:
from PIL import Image
import os, sys
import glob
root_dir = "/.../.../.../"
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((28,28), Image.ANTIALIAS)
imResize.save(filename , 'JPEG', quality=90)
This code just worked for me to resize images..
from PIL import Image
import glob
import os
# new folder path (may need to alter for Windows OS)
# change path to your path
path = 'yourpath/Resized_Shapes' #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('your_path/*.jpg'): #path of raw images
img = Image.open(filename).resize((306,306))
# save resized images to new folder with existing filename
img.save('{}{}{}'.format(path,'/',os.path.split(filename)[1]))
For those that are on Windows:
from PIL import Image
import glob
image_list = []
resized_images = []
for filename in glob.glob('YOURPATH\\*.jpg'):
print(filename)
img = Image.open(filename)
image_list.append(img)
for image in image_list:
image = image.resize((224, 224))
resized_images.append(image)
for (i, new) in enumerate(resized_images):
new.save('{}{}{}'.format('YOURPATH\\', i+1, '.jpg'))
Heavily borrowed the code from #Sanjar Stone. This code work well in Windows OS.
Can be used to bulky resize the images and assembly back to 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
Gist link: https://gist.github.com/justudin/2c1075cc4fd4424cb8ba703a2527958b
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))
Expanded the answer of Andrei M. In order to only change the height of the picture and automatically size the width.
from PIL import Image
import os
path = "D:/.../.../.../resized/"
dirs = os.listdir(path)
def resize():
for item in dirs:
if item == '.jpg':
continue
if os.path.isfile(path+item):
image = Image.open(path+item)
file_path, extension = os.path.splitext(path+item)
size = image.size
new_image_height = 190
new_image_width = int(size[1] / size[0] * new_image_height)
image = image.resize((new_image_height, new_image_width), Image.ANTIALIAS)
image.save(file_path + "_small" + extension, 'JPEG', quality=90)
resize()
If you want to resize any image from a folder where without images files, other files also exist, then you can try this:
from genericpath import isdir
from PIL import Image
import os, sys
path = "C://...//...//....//...//"
save_path = "C://...//..//...//...//"
images = os.listdir(path)
if not os.path.isdir(save_path):
os.makedirs(save_path)
for image in images:
image_path = os.path.join(path, image)
iamge_save_path = os.path.join(save_path, image)
if image.split(".")[1] not in ["jpg", "png"]:
continue
if os.path.exists(image_path):
im = Image.open(image_path)
image_resized = im.resize((224,224))
image_resized.save(iamge_save_path, quality=90)
# print("saved")
Safer to use pathlib
As jwal commented on a similar question, use the object-oriented counterparts for os of pathlib:
p = Path('images') to define the path instance (here as directory relative to current)
Path.iterdir() to find files in the path instance
Path.absolute() to get the absolute-path for file-IO functions
Path.joinpath(*other) to add subfolders or filenames
Path.mkdir(parents=True, exist_ok=True)
Path.name to return the basename of the file (like picture.png)
from pathlib import Path
# folder = 'images'
# new_dimension = (width, height)
def resize(folder, new_dimension, new_subdir):
images_folder = Path(folder)
for child in images_folder.iterdir():
print("Found image:", child)
image_path = child.absolute()
image = Image.open(image_path)
resized_image = image.resize() # could also add Image.ANTIALIAS
# create if the subdir not exists
subdir = images_folder.join(new_subdir)
if not subdir.exists():
subdir.mkdir(parents=True, exist_ok=True)
to_path = subdir.joinpath(child.name) # join adds the path-separators
print("Saving resized to:", to_path)
resized_image.save(to_path) # could also add save-options like 'JPEG', quality=90
I have the following code that I thought would resize the images in the specified path
But when I run it, nothing works and yet python doesn't throw any error so I don't know what to do. Please advise. Thanks.
from PIL import Image
import os, sys
path = ('C:\Users\Maxxie\color\complete')
def resize():
for item in os.listdir(path):
if os.path.isfile(item):
im = Image.open(item)
f, e = os.path.splitext(item)
imResize = im.resize((200,200), Image.ANTIALIAS)
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
resize()
#!/usr/bin/python
from PIL import Image
import os, sys
path = "/root/Desktop/python/images/"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((200,200), Image.ANTIALIAS)
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
resize()
Your mistake is belong to full path of the files. Instead of item must be path+item
John Ottenlips's solution created pictures with black borders on top/bottom i think because he used
Image.new("RGB", (final_size, final_size))
which creates a square new image with the final_size as dimension, even if the original picture was not a square.
This fixes the problem and, in my opinion, makes the solution a bit clearer:
from PIL import Image
import os
path = "C:/path/needs/to/end/with/a/"
resize_ratio = 0.5 # where 0.5 is half size, 2 is double size
def resize_aspect_fit():
dirs = os.listdir(path)
for item in dirs:
if item == '.jpg':
continue
if os.path.isfile(path+item):
image = Image.open(path+item)
file_path, extension = os.path.splitext(path+item)
new_image_height = int(image.size[0] / (1/resize_ratio))
new_image_length = int(image.size[1] / (1/resize_ratio))
image = image.resize((new_image_height, new_image_length), Image.ANTIALIAS)
image.save(file_path + "_small" + extension, 'JPEG', quality=90)
resize_aspect_fit()
In case you want to keep the same aspect ratio of the image you can use this script.
from PIL import Image
import os, sys
path = "/path/images/"
dirs = os.listdir( path )
final_size = 244;
def resize_aspect_fit():
for item in dirs:
if item == '.DS_Store':
continue
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
size = im.size
ratio = float(final_size) / max(size)
new_image_size = tuple([int(x*ratio) for x in size])
im = im.resize(new_image_size, Image.ANTIALIAS)
new_im = Image.new("RGB", (final_size, final_size))
new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
resize_aspect_fit()
Expanding on the great solution of #Sanjar Stone
for including subfolders and also avoid DS warnings you can use the glob library:
from PIL import Image
import os, sys
import glob
root_dir = "/.../.../.../"
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((28,28), Image.ANTIALIAS)
imResize.save(filename , 'JPEG', quality=90)
This code just worked for me to resize images..
from PIL import Image
import glob
import os
# new folder path (may need to alter for Windows OS)
# change path to your path
path = 'yourpath/Resized_Shapes' #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('your_path/*.jpg'): #path of raw images
img = Image.open(filename).resize((306,306))
# save resized images to new folder with existing filename
img.save('{}{}{}'.format(path,'/',os.path.split(filename)[1]))
For those that are on Windows:
from PIL import Image
import glob
image_list = []
resized_images = []
for filename in glob.glob('YOURPATH\\*.jpg'):
print(filename)
img = Image.open(filename)
image_list.append(img)
for image in image_list:
image = image.resize((224, 224))
resized_images.append(image)
for (i, new) in enumerate(resized_images):
new.save('{}{}{}'.format('YOURPATH\\', i+1, '.jpg'))
Heavily borrowed the code from #Sanjar Stone. This code work well in Windows OS.
Can be used to bulky resize the images and assembly back to 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
Gist link: https://gist.github.com/justudin/2c1075cc4fd4424cb8ba703a2527958b
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))
Expanded the answer of Andrei M. In order to only change the height of the picture and automatically size the width.
from PIL import Image
import os
path = "D:/.../.../.../resized/"
dirs = os.listdir(path)
def resize():
for item in dirs:
if item == '.jpg':
continue
if os.path.isfile(path+item):
image = Image.open(path+item)
file_path, extension = os.path.splitext(path+item)
size = image.size
new_image_height = 190
new_image_width = int(size[1] / size[0] * new_image_height)
image = image.resize((new_image_height, new_image_width), Image.ANTIALIAS)
image.save(file_path + "_small" + extension, 'JPEG', quality=90)
resize()
If you want to resize any image from a folder where without images files, other files also exist, then you can try this:
from genericpath import isdir
from PIL import Image
import os, sys
path = "C://...//...//....//...//"
save_path = "C://...//..//...//...//"
images = os.listdir(path)
if not os.path.isdir(save_path):
os.makedirs(save_path)
for image in images:
image_path = os.path.join(path, image)
iamge_save_path = os.path.join(save_path, image)
if image.split(".")[1] not in ["jpg", "png"]:
continue
if os.path.exists(image_path):
im = Image.open(image_path)
image_resized = im.resize((224,224))
image_resized.save(iamge_save_path, quality=90)
# print("saved")
Safer to use pathlib
As jwal commented on a similar question, use the object-oriented counterparts for os of pathlib:
p = Path('images') to define the path instance (here as directory relative to current)
Path.iterdir() to find files in the path instance
Path.absolute() to get the absolute-path for file-IO functions
Path.joinpath(*other) to add subfolders or filenames
Path.mkdir(parents=True, exist_ok=True)
Path.name to return the basename of the file (like picture.png)
from pathlib import Path
# folder = 'images'
# new_dimension = (width, height)
def resize(folder, new_dimension, new_subdir):
images_folder = Path(folder)
for child in images_folder.iterdir():
print("Found image:", child)
image_path = child.absolute()
image = Image.open(image_path)
resized_image = image.resize() # could also add Image.ANTIALIAS
# create if the subdir not exists
subdir = images_folder.join(new_subdir)
if not subdir.exists():
subdir.mkdir(parents=True, exist_ok=True)
to_path = subdir.joinpath(child.name) # join adds the path-separators
print("Saving resized to:", to_path)
resized_image.save(to_path) # could also add save-options like 'JPEG', quality=90