【发布时间】:2016-12-15 02:37:19
【问题描述】:
我正在尝试使用 h5py 将数据存储为(图像、角度)的元组列表。图像是来自 OpenCV 的 uint8 类型的大小 (240,320,3) 的 numpy 数组,而角度只是 float16 类型的数字。
使用 h5py 时,您需要有一个预先确定的形状,以保持可用的读/写速度。 H5py 使用任意值预加载整个数据集,您可以稍后在其中索引并将这些值设置为您想要的任何值。
我想知道在为 h5py 初始化数据集的形状时如何设置内部 numpy 数组的形状。我相信同样的解决方案也适用于 numpy。
import h5py
import numpy as np
dset_length = 100
# fake data of same shape
images = np.ones((dset_length,240,320,3), dtype='uint8') * 255
# fake data of same shape
angles = np.ones(dset_length, dtype='float16') * 90
f = h5py.File('dataset.h5', 'a')
dset = f.create_dataset('dset1', shape=(dset_length,2))
for i in range(dset_length):
# does not work since the shape of dset[0][0] is a number,
# and can't store an array datatype
dset[i] = np.array((images[i],angles[i]))
在 numpy 中重新创建问题如下所示:
import numpy as np
a = np.array([
[np.array([0,0]), 0],
[np.array([0,0]), 0],
[np.array([0,0]), 0]
])
a.shape # (3, 2)
b = np.empty((3,2))
b.shape # (3, 2)
a[0][0] = np.array([1,1])
b[0][0] = np.array([1,1]) # ValueError: setting an array element with a sequence.
【问题讨论】:
-
b = np.empty((3,2), dtype=object)将使其行为类似于a。但这并不是您真正希望它的行为方式。