Open images from a folder one by one using python?

前端 未结 2 1054
耶瑟儿~
耶瑟儿~ 2021-02-20 14:56

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.



        
相关标签:
2条回答
  • 2021-02-20 15:38

    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)    
    
    0 讨论(0)
  • 2021-02-20 15:47

    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)

    0 讨论(0)
提交回复
热议问题