大家好我需要逐个打开文件夹中的图像对图像进行一些处理并将它们保存回其他文件夹。我这样做是使用以下示例代码。
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")
有没有最好的方法呢?
谢谢!
答案 0 :(得分:12)
听起来你想要多线程。这是一个快速转换,它会做到这一点。
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
,请参阅该文档了解更多示例和信息)
答案 1 :(得分: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)