10

Hi all I need to open images from a folder one by one do some processing on images and save them back to other folder. I am doing this using following sample code.

path1 = path of folder of images    
path2 = path of folder to save images    

listing = os.listdir(path1)    
for file in listing:
    im = Image.open(path1 + file)    
    im.resize((50,50))                % need to do some more processing here             
    im.save(path2 + file, "JPEG")

Is there any best way to do this?

Thanks!

5
  • 1
    It seems ok with processing one after another, avoiding the load to memory. Commented Oct 24, 2013 at 18:33
  • 4
    Just FYI, the Python comment character is #, not % (LaTeX programmer?). That might save you some trouble in the future. :) Commented Oct 24, 2013 at 18:35
  • 1
    What are you actually trying to do? Please put a little more description in your question -- help us help you by making your question as complete as possible. Commented Oct 24, 2013 at 18:36
  • If you want it to not be a blocking call, I would create a thread for every image processing. Commented Oct 24, 2013 at 18:36
  • @ChristianTernus: As I mention above, I need to open images from one folder and by doing some processing need to save them in another folder. At present I am doing this by opening one image at a time, process it and then saving it into another folder. My question is whether it can be done for all images at a time rather than opening them one by one? Commented Oct 24, 2013 at 20:00

2 Answers 2

13

Sounds like you want multithreading. Here's a quick rev that'll do that.

from multiprocessing import Pool
import os

path1 = "some/path"
path2 = "some/other/path"

listing = os.listdir(path1)    

p = Pool(5) # process 5 images simultaneously

def process_fpath(path):
    im = Image.open(path1 + path)    
    im.resize((50,50))                # need to do some more processing here             
    im.save(os.path.join(path2,path), "JPEG")

p.map(process_fpath, listing)

(edit: use multiprocessing instead of Thread, see that doc for more examples and information)

Sign up to request clarification or add additional context in comments.

Comments

2

You can use glob to read the images one by one

import glob
from PIL import Image


images=glob.glob("*.jpg")
for image in images:
    img = Image.open(image)
    img1 = img.resize(50,50)
    img1.save("newfolder\\"+image)    

1 Comment

This is good, but correct syntax is img.resize((50,50)) with the (50,50) as a tuple. Otherwise the second 50 gets interpreted as the resample argument and you'll get PIL: ValueError: unknown resampling filter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.