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

使用python逐个打开文件夹中的图像?,python,python-imaging-library,Python,Python Imaging Library,大家好,我需要从一个文件夹中逐个打开图像,对图像进行一些处理,然后将它们保存回另一个文件夹。我使用下面的示例代码来实现这一点 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((5

大家好,我需要从一个文件夹中逐个打开图像,对图像进行一些处理,然后将它们保存回另一个文件夹。我使用下面的示例代码来实现这一点

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")
有没有最好的办法


谢谢

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

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)

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

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

一个接一个地处理似乎没问题,避免了对内存的加载。仅供参考,Python注释字符是
,而不是
%
(LaTeX程序员?)。这可能会在将来为您节省一些麻烦。:)你到底想做什么?请在你的问题中多加一点描述——帮助我们尽可能完整地回答你的问题。如果你不想让它成为阻塞调用,我会为每个图像处理创建一个
线程。@ChristianTernus:正如我上面提到的,我需要打开一个文件夹中的图像,通过进行一些处理,我需要将它们保存在另一个文件夹中。目前,我这样做是通过一次打开一个图像,处理它,然后保存到另一个文件夹。我的问题是,是否可以一次对所有图像执行此操作,而不是逐个打开它们?这很好,但正确的语法是
img.resize((50,50))
,将
(50,50)
作为元组。否则,第二个50将被解释为
resample
参数,您将得到
PIL:ValueError:unknown resampling filter