joblib

joblib 提供两个最核心的功能:caching 和 parallel computing.

使用 joblib.Parallel 进行并行计算

joblib.Parallel 的基础用法是通过 n_jobs 指定进程数(指定 n_jobs=-1 则表示能用多少用多少),初始化类后,用 joblib.delayed(<function>)(args) 指定每一个进程的工作

并行读取图片,保存为 NumPy Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt # 读取图片
from joblib import Parallel, delayed # 并行计算
from rich.progress import track # 可视化进度条


def read_img(path):
return plt.imread(path)

imgs = Parallel(n_jobs=-1)(
delayed(read_img)(path)
for path in track(csv["im_name"], description="Loading images ... ", transient=True)
# transient=True 指定进度条在完成后隐藏
) # parallel() 结束之后,imgs 是 List[np.ndarray]

imgs = np.asarray(imgs) # 转化为 np.ndarray