Resize multiple images in a folder (Python) - python

I already saw the examples suggested but some of them don't work.
So, I have this code which seems to work fine for one image:
im = Image.open('C:\\Users\\User\\Desktop\\Images\\2.jpg') # image extension *.png,*.jpg
new_width = 1200
new_height = 750
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\resized.tif') # .jpg is deprecated and raise error....
How can I iterate it and resize more than one image ? Aspect ration need to be maintained.
Thank you

# Resize all images in a directory to half the size.
#
# Save on a new file with the same name but with "small_" prefix
# on high quality jpeg format.
#
# If the script is in /images/ and the files are in /images/2012-1-1-pics
# call with: python resize.py 2012-1-1-pics
import Image
import os
import sys
directory = sys.argv[1]
for file_name in os.listdir(directory):
print("Processing %s" % file_name)
image = Image.open(os.path.join(directory, file_name))
x,y = image.size
new_dimensions = (x/2, y/2) #dimension set here
output = image.resize(new_dimensions, Image.ANTIALIAS)
output_file_name = os.path.join(directory, "small_" + file_name)
output.save(output_file_name, "JPEG", quality = 95)
print("All done")
Where it says
new_dimensions = (x/2, y/2)
You can set any dimension value you want
for example, if you want 300x300, then change the code like the code line below
new_dimensions = (300, 300)

I assume that you want to iterate over images in a specific folder.
You can do this:
import os
from datetime import datetime
for image_file_name in os.listdir('C:\\Users\\User\\Desktop\\Images\\'):
if image_file_name.endswith(".tif"):
now = datetime.now().strftime('%Y%m%d-%H%M%S-%f')
im = Image.open('C:\\Users\\User\\Desktop\\Images\\'+image_file_name)
new_width = 1282
new_height = 797
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\test_resize\\resized' + now + '.tif')
datetime.now() is just added to make the image names unique. It is just a hack that came to my mind first. You can do something else. This is needed in order not to override each other.

I assume that you have a list of images in some folder and you to resize all of them
from PIL import Image
import os
source_folder = 'path/to/where/your/images/are/located/'
destination_folder = 'path/to/where/you/want/to/save/your/images/after/resizing/'
directory = os.listdir(source_folder)
for item in directory:
img = Image.open(source_folder + item)
imgResize = img.resize((new_image_width, new_image_height), Image.ANTIALIAS)
imgResize.save(destination_folder + item[:-4] +'.tif', quality = 90)

Related

How do I write file names to a new folder with an added prefix?

I'm trying to take a dir like ["cats.jpg", "dogs.jpg", "stars.jpg"] and resize them to 100x100 pixels and output the edited files into a new directory with the prefix "resized_" i.e ["resized_cats.jpg", "resized_dogs.jpg", "resized_stars.jpg"].
At the moment I'm getting the new directory but no files are being written to it.
batch = glob.glob("files/batch/*.jpg")
for file in batch:
img = cv2.imread(file,1)
resize = cv2.resize(img, (100,100))
if not os.path.exists("files/batchOut"):
os.makedirs("files/batchOut")
cv2.imwrite(f"files/batchOut/resized_{file}", resize)
You can use os.path.basename to isolate the file name from your path string like this:
batch = glob.glob("files/batch/*.jpg")
for file in batch:
img = cv2.imread(file,1)
resize = cv2.resize(img, (100,100))
if not os.path.exists("files/batchOut"):
os.makedirs("files/batchOut")
file_name = os.path.basename(file)
cv2.imwrite(f"files/batchOut/resized_{file_name}", resize)
You may find this to be a more robust approach. You certainly only want to call makedirs once:
import os
from glob import glob
import cv2
import sys
source_directory = '<your source directory>'
target_directory = '<your target directory>'
pattern = '*.jpg'
prefix = 'resized_'
dims = (100, 100)
os.makedirs(target_directory, exist_ok=True)
for filename in glob(os.path.join(source_directory, pattern)):
try:
img = cv2.imread(filename, cv2.IMREAD_COLOR)
newfile = f'{prefix}{os.path.basename(filename)}'
newfilepath = os.path.join(target_directory, newfile)
cv2.imwrite(newfilepath, cv2.resize(img, dims))
except Exception as e:
print(f'Failed to process {filename} due to {e}', file=sys.stderr)
Was able to alter the name using the replace() function.
Important for "batch\" double backward slashes are required i.e. "batch\\"
batch = glob.glob("files/batch/*.jpg")
for file in batch:
img = cv2.imread(file,1)
resize = cv2.resize(img, (100,100))
if not os.path.exists("files/batchOut"):
os.makedirs("files/batchOut")
cv2.imwrite("files/batchOut/resized_" + file.replace("files/batch\\", "" ) + ".jpg", resize)

How to save images with the same name to the different direction using PIL and os.path?

While trying to split the path to get a name, I get the traceback:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?
I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.
import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
image = Image.open(image)
image.thumbnail((640, 428), Image.ANTIALIAS)
image_path_and_name = os.path.split(image)
image_name_and_ext = os.path.splitext(image[0])
name = image_name_and_ext[0] + '.png'
name = os.path.splitext(image)[0] + '.png'
file_path = os.path.join(path, name)
image.save(file_path, quality=quality_val)
import glob
from PIL import Image
import os
images = glob.glob("Source_path")
path = r"Destination_path"
quality_val=95
for image in images:
img = Image.open(image)
img.thumbnail((640, 428), Image.ANTIALIAS)
name = os.path.split(image)
file_path = os.path.join(path, name[1])
img.save(file_path, quality=quality_val)
The primary problem with your code was that you were using a variable and an object under the same name image. Which was causing problems.
LOGICAL ERRORS:-
image_path_and_name is a needless variable in the code, as it is
used for nothing.
name has been initialized with totally different values twice,
instead use name = os.path.split(image) which serves the purpose
of both.
you should not try to explicitly define the extension of each image
as .png as it might create issues when dealing with other image
formats.
for image in images:
image = Image.open(image)
image.thumbnail((640, 428), Image.ANTIALIAS)
image_path_and_name = os.path.split(image)
When you say image = Image.open(image), you're overwriting the loop variable also named image, and it's no longer a splittable string.
Change one of the image variables to a different name.
firstly,
image_name_and_ext = os.path.splitext(image[0])
should be
image_name_and_ext = os.path.splitext(image_path_and_name[1])
because image is string so image[0] just get first character of image not useless in this case
secondly,
name = os.path.splitext(image)[0] + '.png' equal image
name = os.path.splitext(image)[0] should return path of image not include extention
to solve this problem, you can try:
for image in images:
img = Image.open(image)
img.thumbnail((640, 428), Image.ANTIALIAS)
name = os.path.split(image)
file_path = os.path.join(path, name[1])
image.save(file_path, quality=quality_val)
By the code above you will get image in thumbnails I recommend to use resize function because from resize you can maintain you aspect ratio that helps you in getting better results.
image.thumbnail((640, 428), Image.ANTIALIAS)
this line of code is converting your thumbnail.which is not good approach of resizing. Try the code below.
import os
from PIL import Image
PATH = "F:\\FYP DATASET\\images\\outliers Dataset\\Not Outliers\\"
Copy_to_path="F:\\FYP DATASET\\images\\outliers Dataset\\"
for filename in os.listdir(PATH):
img = Image.open(os.path.join(PATH, filename)) # images are color images
img = img.resize((224,224), Image.ANTIALIAS)
img.save(Copy_to_path+filename+'.jpeg')
In this code you are taking images directly from folder resize them and saving them to other location with same name. All the images are processing one by one So you need not worry to load all the images at once into the memory.

Take an image directory and resize all images in the directory

I am trying to convert high resolution images to something more manageable for machine learning. Currently I have the code to resize the images to what ever height and width I want however I have to do one image at a time which isn't bad when I'm only doing a 12-24 images but soon I want to scale up to do a few hundred images.
I am trying to read in a directory rather than individual images and save the new images in a new directory. Initial images will vary from .jpg, .png, .tif, etc. but I would like to make all the output images as .png like I have in my code.
import os
from PIL import Image
filename = "filename.jpg"
size = 250, 250
file_parts = os.path.splitext(filename)
outfile = file_parts[0] + '_250x250' + file_parts[1]
try:
img = Image.open(filename)
img = img.resize(size, Image.ANTIALIAS)
img.save(outfile, 'PNG')
except IOError as e:
print("An exception occured '%s'" %e)
Any help with this problem is appreciated.
Assuming the solution you are looking for is to handle multiple images at the same time - here is a solution. See here for more info.
from multiprocessing import Pool
def handle_image(image_file):
print(image_file)
#TODO implement the image manipulation here
if __name__ == '__main__':
p = Pool(5) # 5 as an example
# assuming you know how to prepare image file list
print(p.map(handle_image, ['a.jpg', 'b.jpg', 'c.png']))
You can use this:
#!/usr/bin/python
from PIL import Image
import os, sys
path = "\\path\\to\\files\\"
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,100), Image.ANTIALIAS)
imResize.save(f+'.png', 'png', quality=80)
resize()
You can loop over the contents of a directory with
import os
for root, subdirs, files in os.walk(MY_DIRECTORY):
for f in files:
if f.endswith('png'):
#do something
You can run through all the images inside the directory using glob. And then resize the images with opencv as follows or as you have done with PIL.
import glob
import cv2
import numpy as np
IMG_DIR='home/xx/imgs'
def read_images(directory):
for img in glob.glob(directory+"/*.png"):
image = cv2.imread(img)
resized_img = cv2.resize(image/255.0 , (250 , 250))
yield resized_img
resized_imgs = np.array(list(read_images(IMG_DIR)))
I used:
from PIL import Image
import os, sys
path = os.path.dirname(os.path.abspath(__file__))
dirs = os.listdir( path )
final_size = 244
print(dirs)
def resize_aspect_fit():
for item in dirs:
if ".PNG" in item:
print(item)
im = Image.open(path+"\\"+item)
f, e = os.path.splitext(path+"\\"+item)
size = im.size
print(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))
print(f)
new_im.save(f + 'resized.jpg', 'JPEG', quality=400)# png
resize_aspect_fit()
You can use this code to resize multiple images and save them after conversion in the same folder for let's say dimensions of (200,200):
import os
from PIL import Image
f = r' ' #Enter the location of your Image Folder
new_d = 200
for file in os.listdir(f):
f_img = f+'/'+file
try:
img = Image.open(f_img)
img = img.resize((new_d, new_d))
img.save(f_img)
except IOError:
pass
you can try to use the PIL library to resize images in python
import PIL
import os
import os.path
from PIL import Image
path = r'your images path here'
for file in os.listdir(path):
f_img = path+"/"+file
img = Image.open(f_img)
img = img.resize((100, 100)) #(width, height)
img.save(f_img)
from PIL import Image
import os
images_dir_path=' '
def image_rescaling(path):
for img in os.listdir(path):
img_dir=os.path.join(path,img)
img = Image.open(img_dir)
img = img.resize((224, 224))
img.save(img_dir)
image_rescaling(images_dir_path)

Loading resized image with cv2.imread failed with TypeError [duplicate]

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

Python/PIL Resize all images in a 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

Categories

Resources