python - 能够使用 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) 并取消注释多处理代码时,代码会以两倍的速度遍历目录结构,但不会创建任何缩略图。我将如何调整多处理代码以使其工作?
解决方案
代码 "pool.map(create_thumbnail, _path)" 需要 pool.map(create_thumbnail(_path), _path) 来创建缩略图
推荐阅读
- python - 我试图在 tkinter 中显示表情符号,但它只显示黑白表情符号
- database - 这段代码是否有任何理由不会更新我的数据库?
- javascript - 如何使 onkeyup 在下一行工作?如何使 Javascript 在下一行工作?
- doctrine-orm - Symfony 从 String 类声明中获取 className 对象
- java - Java LinkedList addLast() 方法实现错误
- regex - 正则表达式不提取组
- excel - 如何获取整个网页的内容
- typescript - 具有泛型的 Apollo 服务器快速返回类型
- python-3.x - x 秒后超时 discord.py 重写
- python - exe 文件可以修改包含的文本文件吗?