加快向hdf5 fi写入数百个3D numpy阵列的速度

2024-09-29 21:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发的应用程序将包含多个图像(视野)、平面(Z)和荧光通道的专有tiff文件格式(nikond2文件)转换为numpy数组,然后保存在HDF5文件中。一个典型的数据集通常有50个视场(fov),每个视场有5个通道,每个通道有40个z平面)。整个文件大约6 Gb。在

这是我写的代码:

步骤:

0)导入所有必需的库

import nd2reader as nd2
from matplotlib import pyplot as plt
import numpy as np
import h5py as h5
import itertools
import ast
import glob as glob
from joblib import Parallel, delayed
import time

1)运行nd2文件转换的函数。 向numpy数组的转换是使用nd2reader一个python程序完成的,而且速度很快。 为了减少循环的数量并使用列表理解,我制作了一个元组列表,每个元组包含通道和fov 例子: [('DAPI',0), ('DAPI',1)] 其中DAPI是频道,fov是数字。在

注意:实验通道列表是一个包含字典的文件,它将通道(键)与感兴趣的基因(值)相匹配。在

^{pr2}$

2)将图像合并到3D数组中,然后将其写入HDF5文件。我用h5py。在生成之后,我将每个3D numy数组写入磁盘。在

def SaveImg(DataFile,ImgRef,ExperimentChannelList,ImgStack,*args):
        channel=args[0]
        fov=args[1]
        for idx,image in enumerate(ImgRef.select(channels=channel,z_levels=ImgRef.z_levels,fields_of_view=fov)):
            ImgStack[idx,:,:]=image
        gene=ExperimentChannelList[channel]
        ChannelGroup=DataFile.require_group(gene)
        Fovdataset=ChannelGroup.create_dataset(str(fov), data=ImgStack,dtype=np.float64,compression="gzip")

3)脚本的主体和joblib调用一个目录中所有文件的并行处理。在

if __name__=='__main__':

    # Run the
    # Directory where ND2 file is stored (Ex. User/Data/)
    WorkingDirectory=input('Enter the directory with the files to process (ex. /User/):  ')
    #WorkingDirectory='/Users/simone/Box Sync/test/ND2conversion/'
    NumberOfProcesses=int(input('Enter the number of processes to use:  '))
    #NumberOfProcesses=2
    FileExt='nd2'
    # Iterator with the name of the files to process
    FilesIter=glob.iglob(WorkingDirectory+'*.'+FileExt)  

    now = time.time()
    Parallel(n_jobs=NumberOfProcesses,verbose=5)(delayed(ConvertND2File)(ND2file) for ND2file in FilesIter)
    print("Finished in", time.time()-now , "sec")

运行时间

转换两个5.9 Gb文件的总时间
[并行(n_jobs=2)]:完成1/2 |已用:7.4分钟剩余:7.4分钟
[Parallel(n_jobs=2)]:完成2个(共2个)|已用:7.4分钟完成
在444.8717038631439秒内完成

问题:

我只是想知道是否有更好的方法来处理io到hdf5文件,以加快转换速度,考虑到如果我想扩大这个过程,我将无法在内存中保存所有的3D numpy数组(fov),然后在每个通道被处理后写入它们。 谢谢!在


Tags: 文件theimportnumpy列表timeparallelas

热门问题