5

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.

rzaratx
  • 756
  • 3
  • 9
  • 29

8 Answers8

4

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'])) 
balderman
  • 22,927
  • 7
  • 34
  • 52
3

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()
Aaron Pereira
  • 314
  • 1
  • 2
  • 10
2

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 
Mitch
  • 3,342
  • 2
  • 21
  • 31
2

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)))
Achintha Ihalage
  • 2,310
  • 4
  • 20
  • 33
1

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()
sqp_125
  • 538
  • 6
  • 21
1

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
optimusPrime
  • 49
  • 1
  • 5
0

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)
Moez Ben Rebah
  • 170
  • 1
  • 12
  • I need a code for multipage so that output should also come as multipage tiff image.... – Ani Feb 10 '21 at 07:34
0
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)
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – NameVergessen Dec 17 '22 at 16:21