可选择的方案:
来写的 Jupyter Notebook 兼容版本 示例。
✅ 方法一:使用 pathos.multiprocessing
(Jupyter友好)
from pathos.multiprocessing import ProcessingPool as Pool
from tqdm import tqdm
def process_image(img_path, output_path):
# 你的图像处理逻辑,比如保存图像到 output_path
# 示例代码如下(请根据你实际处理内容修改):
from PIL import Image
img = Image.open(img_path)
img.save(output_path)
return output_path
# 构造参数列表(每个是一个元组)
args = [(img_path, output_path / img_path.name) for img_path in img_paths]
# 初始化 Pool 并并行处理
pool = Pool() # 默认使用 CPU 核心数
# tqdm 不支持 map 直接用,写成 list
results = list(tqdm(pool.uimap(lambda args: process_image(*args), args), total=len(args)))
🔑 特点:
- 支持在 Jupyter 中直接运行;
- 不需要
if __name__ == "__main__"
; - 支持传多个参数(通过
*args
拆包); - 使用
uimap()
可以有 tqdm 进度条(imap
带顺序,map
会等全部完成)。
✅ 方法二:使用 joblib.Parallel
(适合CPU密集,稳定)
from joblib import Parallel, delayed
from tqdm import tqdm
def process_image(img_path, output_path):
from PIL import Image
img = Image.open(img_path)
img.save(output_path)
return output_path
# tqdm 进度条用在参数上
results = Parallel(n_jobs=-1)(
delayed(process_image)(img_path, output_path / img_path.name)
for img_path in tqdm(img_paths)
)
🔑 特点:
n_jobs=-1
表示使用所有可用核心;- 同样支持多个参数;
- 在 Jupyter 运行稳定,依赖
loky
后端; - 避免了
pickle
报错。
📦 安装依赖
如果你没有安装 pathos
或 joblib
:
pip install pathos joblib
✅ 总结对比
特性 | pathos |
joblib |
---|---|---|
Jupyter兼容 | ✅ | ✅ |
多参数传递 | ✅(tuple 拆包) | ✅(delayed(f)(...) ) |
支持 tqdm | ✅(配合 uimap ) |
✅(在 for 循环外) |
稳定性/文档支持 | 中(社区较活跃) | 高(广泛用于 sklearn 等) |
推荐使用场景 | 函数自由写、调试方便 | 大批量 CPU 密集任务 |