简体   繁体   中英

Open images from a folder one by one using python?

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!

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)

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)    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM