Dask延迟+ Matplotlib.savefig() - >失败

时间:2017-05-24 11:09:03

标签: python matplotlib multiprocessing dask dask-delayed

我的目标是分别从多个numpy数组生成多个png文件,这些数据从我的HD中的医学图像加载。 为了让事情更快,我使用dask延迟了。 这是我的工作代码:

import os.path
from glob import glob

import nibabel as nib
import numpy as np
from dask import delayed

def process(data):
    # Need to have the import inside so that multiprocessing works.
    # Apparently doesn't solve the issue anyway..
    import matplotlib.pyplot as plt
    outpath = '/Users/user/outputdir/'
    name = os.path.basename(data.get_filename())
    savename = name[:name.index('.')] + '.png'

    plt.imshow(np.rot90(data.get_data()[15:74, 6:82, 18, 0]),
               extent=[0, 1, 0, 1], aspect=1.28, cmap='gray')
    plt.axis('off')
    out = os.path.join(outpath, savename)
    plt.savefig(out)
    plt.close()
    return out


L = []
for fn in glob("/Users/user/imagefiles/mb*.nii.gz"):
    nifti = delayed(nib.load)(fn)
    outpng = delayed(process)(nifti)
    L.append(outpng)

results = delayed(print)(L)
results.compute()

我的问题是,每次运行后,一些输出图像为空(png中没有任何内容),以及哪些图像为空是非常随机的,因为所有输入数据都是有效的。

我怀疑这是多处理和matplotlib的问题,如other related thread.

中所示

是否有人建议如何使用dask

编辑:最小的工作示例

import os.path
import random
import string

import numpy as np
from dask import delayed

def gendata(fn):
    return

def process(data):
    # Need to have the import inside so that multiprocessing works.
    import matplotlib.pyplot as plt

    outpath = '/Users/user/Pictures/test/'
    name = ''.join(random.choices(string.ascii_lowercase, k=10))
    savename = name + '.png'

    data = np.random.randint(0, 255, size=(100,100,20,2))

    plt.imshow(np.rot90(data[15:74, 6:82, 18, 0]),
               extent=[0, 1, 0, 1], aspect=1.28, cmap='gray')
    plt.axis('off')
    out = os.path.join(outpath, savename)
    plt.savefig(out)
    plt.close()
    return out

L = []
for fn in range(0, 10):
    nifti = delayed(gendata)(fn)
    outpng = delayed(process)(nifti)
    L.append(outpng)

results = delayed(print)(L)
results.compute()

0 个答案:

没有答案