【问题标题】:Open images from a folder one by one using python?使用python一张一张打开文件夹中的图像?
【发布时间】:2017-07-24 23:15:44
【问题描述】:

大家好,我需要一张一张打开文件夹中的图像,对图像进行一些处理并将它们保存回其他文件夹。我正在使用以下示例代码执行此操作。

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")

有没有最好的方法来做到这一点?

谢谢!

【问题讨论】:

  • 一个接一个地处理似乎没问题,避免了对内存的负载。
  • 仅供参考,Python 注释字符是 #,而不是 %(LaTeX 程序员?)。这可能会在将来为您节省一些麻烦。 :)
  • 你到底想做什么?请在您的问题中添加更多描述 - 帮助我们帮助您,使您的问题尽可能完整。
  • 如果你希望它不是阻塞调用,我会为每个图像处理创建一个thread
  • @ChristianTernus:正如我上面提到的,我需要从一个文件夹中打开图像,并通过一些处理将它们保存在另一个文件夹中。目前我通过一次打开一个图像,处理它然后将其保存到另一个文件夹来做到这一点。我的问题是是否可以一次对所有图像完成而不是一张一张地打开它们?

标签: python python-imaging-library


【解决方案1】:

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

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)

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

【讨论】:

    【解决方案2】:

    您可以使用 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)    
    

    【讨论】:

    • 这很好,但正确的语法是 img.resize((50,50))(50,50) 作为一个元组。否则,第二个 50 将被解释为 resample 参数,您将得到 PIL: ValueError: unknown resampling filter
    猜你喜欢
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    相关资源
    最近更新 更多