首页 > 解决方案 > 能够使用 PIL 创建缩略图,但我的多处理代码无法创建 PIL 缩略图

问题描述

我正在尝试学习如何在 64 位 windows 7 pc 上使用 python 2.7 使用 PIL 的多处理。

我可以使用 PIL 成功创建(并保存)缩略图到我电脑上的所需位置。当我尝试实现多处理时,我的代码不会创建任何缩略图,它循环文件的速度大约是原来的两倍。我在多个目录和子目录中有大约 9,000 个图像文件(我无法控制文件名而不是目录结构)

这是有效代码的基础。

from multiprocessing import Pool, freeze_support
import os
from fnmatch import fnmatch
from timeit import default_timer as timer
from PIL import Image, ImageFile

starttime = timer()

SIZE = (125, 125)
SAVE_DIRECTORY = r'c:\path\to\thumbs'
PATH = r'c:\path\to\directories\with\photos

def enumeratepaths(path):
    """ returns the path of all files in a directory recursively"""

def create_thumbnail(_filename):
    try:
        ImageFile.LOAD_TRUNCATED_IMAGES = True
        im = Image.open(_filename)
        im.thumbnail(SIZE, Image.ANTIALIAS)
        base, fname = os.path.split(_filename)
        outfile = os.path.split(_filename)[1] + ".thumb.jpg"
        save_path = os.path.join(SAVE_DIRECTORY, outfile)
        im.save(save_path, "jpeg")
    except IOError:
        print " cannot create thumbnail for ... ",_filename


if __name__ == '__main__':
    freeze_support() # need this in windows; no effect in *nix

    for _path in enumeratepaths(PATH):
        if fnmatch(_path, "*.jpg"):
            create_thumbnail(_path)
            # pool = Pool()
            # pool.map(create_thumbnail, _path)
            # pool.close()
            # pool.join()

该代码工作并在所需位置创建 9,000 个缩略图。当我注释掉 create_thumbnail(_path) 并取消注释多处理代码时,代码会以两倍的速度遍历目录结构,但不会创建任何缩略图。我将如何调整多处理代码以使其工作?

标签: pythonmultiprocessingpython-imaging-library

解决方案


代码 "pool.map(create_thumbnail, _path)" 需要 pool.map(create_thumbnail(_path), _path) 来创建缩略图


推荐阅读