当ndims在运行时可能有所不同时,如何在julia中使用HDF5编写块?

时间:2016-09-11 21:29:50

标签: julia hdf5

如果我有1000片64x64图像,我可以写成64x64x1块,如下所示:

using HDF5

filename = "test.h5"
# open file
fmode ="w"
# get a file object
fid = h5open(filename, fmode)
# matrix to write in chunks
B = rand(64,64,1000)
# figure out its dimensions
sizeTuple = size(B)
ndims = length(sizeTuple)
# set up to write in chunks of sizeArray
sizeArray = ones(Int, ndims)
[sizeArray[i] = sizeTuple[i] for i in 1:(ndims-1)] # last value of size  array is :...:,1
# create a dataset models within root
dset = d_create(fid, "models", datatype(Float64), dataspace(size(B)), "chunk", sizeArray)
[dset[:,:,i] = slicedim(B, ndims, i) for i in 1:size(B, ndims)]
close(fid)

这很好用,但是dset [:,:,i]中的赋值语法特定于ndims = 3.如果我在运行时指定了1000个任意超量角的切片,我怎么能改变呢?例如,B =兰德(64,64,3,1000)或兰特(64,64,64,3,1000)?

由于

1 个答案:

答案 0 :(得分:1)

所以我在谷歌的julia用户小组得到了一些失误后的答案。它非常简单:

    using HDF5

    filename = "test.h5"
    # open file
    fmode ="w"
    # get a file object
    fid = h5open(filename, fmode)
    # matrix to write in chunks
    B = rand(64,64,1000)
    # figure out its dimensions
    Ndims = ndims(B)
    # set up to write in chunks of sizeArray
    sizeArray = ones(Int, Ndims)
    [sizeArray[i] = size(B, i) for i in 1:(Ndims-1)] # last value of size array is :...:,1
    # create a dataset models within root
    dset = d_create(fid, "models", datatype(Float64), dataspace(size(B)), "chunk", sizeArray)
    # write in slices of (:,:,i) 
    [dset[(fill(:,Ndims-1))...,i] = slicedim(B, Ndims, i) for i in 1:size(B, Ndims)]
    close(fid)

fill和splat ...语法非常非常有用。