【问题标题】:ValueError: Saving saving in appending mode in PytablesValueError:在 Pytables 中以附加模式保存保存
【发布时间】:2020-10-31 12:34:33
【问题描述】:

我有 100 张图片,每张图片都是 85*85 size (width*height),由 numpy 数组 (data) 给出,如下所示。

import numpy as np
import tables as tb


data = np.random.rand(100, 85, 85)
print (data.shape)

我想以追加方式将每张图片一张一张保存到h5文件中。

fo = "data.h5"

h5 = tb.open_file(fo, mode='w')

group = h5.create_group(h5.root, 'data')

atom = tb.Float64Atom()

ds = h5.create_earray(group, 'test', atom,
                       (0, data.shape[1], data.shape[2]))

for ix in range(data.shape[0]):
    dd = data[ix, :, :]
       
    ds.append(dd)

ds.flush()
ds.close()

但是,我收到以下错误:

ValueError: 附加对象 (2) 和 /data/test EArray (3) 的等级不同

【问题讨论】:

    标签: python-3.x numpy hdf5 pytables


    【解决方案1】:

    访问data 数组元素时请注意语法。当您使用dd = data[ix, :, :] 时,dd.shape=(85, 85) 您需要dd = data[ix:ix+1, :, :] 才能获得 1 行。

    如果您必须追加大量行,则逐行加载数据效率不高。最好将它们放在一个数组中并附加整个数组。这体现在ds2.append(data)的创建中

    这是更新的解决方案。请注意,我更喜欢 with/as 打开文件以进行更清晰的文件错误处理。

    with tb.open_file(fo, mode='w') as h5:
        group = h5.create_group(h5.root, 'data')
        atom = tb.Float64Atom() 
        ds = h5.create_earray(group, 'test', atom,
                             (0, data.shape[1], data.shape[2]))
        for ix in range(data.shape[0]):
            dd = data[ix:ix+1, :, :]
            print (dd.shape)   
            ds.append(dd)
    
    # Method to create Earray with parent groups, 
    # then append all image data at one time
        ds2 = h5.create_earray('/data2', 'test2', atom,
                         (0, data.shape[1], data.shape[2]),
                         createparents=True)
        ds2.append(data)
    

    如果您想加载 1 个 Earray 中的所有数据,使用引用您的数组的 obj=data 参数加载很简单。这保留了可在维度 0 中扩展的形状定义。请参阅下面的修改代码。

    h5 = tb.open_file(fo, mode='w')
    group = h5.create_group(h5.root, 'data')
    ds = h5.create_earray('/data', 'test', atom,
                         (0, data.shape[1], data.shape[2]),
                         obj=data)
    ds.flush() # not necessary
    ds.close() # not necessary
    h5.close() ## REQUIRED!!!!
    

    【讨论】:

    • 我知道 obj 方法,但我想在附加模式下实现它。我很想通过for循环来扩展数组。
    • 好的,看新的例子。旧方法留作参考。
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多