使用python一一打开文件夹中的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19573809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:05:12  来源:igfitidea点击:

Open images from a folder one by one using python?

pythonpython-imaging-library

提问by user2766019

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!

谢谢!

采纳答案by Christian Ternus

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

听起来你想要多线程。这是一个快速的 rev 可以做到这一点。

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 multiprocessinginstead of Thread, see that doc for more examples and information)

(编辑:使用multiprocessing而不是Thread,有关更多示例和信息,请参阅该文档)

回答by Pankaj Bokdia

You can use glob to read the images one by one

可以使用glob一一读取图片

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)