Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 369
user2766019 Avatar asked Oct 24 '13 18:10

user2766019


2 Answers

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)

like image 123
Christian Ternus Avatar answered Nov 01 '22 03:11

Christian Ternus


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)    
like image 2
Pankaj Bokdia Avatar answered Nov 01 '22 03:11

Pankaj Bokdia