Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
rzaratx Avatar asked Dec 10 '22 03:12

rzaratx


2 Answers

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'])) 
like image 152
balderman Avatar answered Dec 12 '22 16:12

balderman


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()
like image 26
Aaron Pereira Avatar answered Dec 12 '22 15:12

Aaron Pereira