2016-12-15 90 views
2

我试图用h5py将数据存储为(图像,角度)的元组列表。图像是来自OpenCV的uint8类型的大小为(240,320,3)的numpy数组,而角度只是float16类型的数字。H5PY/Numpy - 设置numpy数组的内部形状(对于h5py)

使用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])) 

Recreateing在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. 
+0

'B = np.empty((3,2),D型细胞=对象)'将使其行为类似于'A'。但是,这不是你想要的行为。 – Eric

回答

2

dtype@Eric创建应与工作均为numpyh5py。但是我想知道你是真的想要还是需要这个。另一种方法是在numpy,imagesangles中有两个数组,一个是4d uint8,另一个是浮点数。在h5py中,您可以创建一个group,并将这两个数组存储为datasets

import h5py 
dt = np.dtype([('angle', np.float16), ('image', np.uint8, (40,20,3))]) 
data = np.ones((3,), dt) 

f = h5py.File('test.h5','w') 
g = f.create_group('data') 

数据集与化合物D型:

g.create_dataset('data', (3,), dtype=dt) 
g['data'][:] = data 
与两个阵列

或数据集

你可以与

images[i,...], angles[i]  # or 
data[i]['image'], data[i]['angle'] 

例如选择用于ith'图像的值

g.create_dataset('image', (3,40,20,3), dtype=np.uint8) 
g.create_dataset('angle', (3,), dtype=np.float16) 
g['image'][:] = data['image'] 
g['angle'][:] = data['angle'] 

从任一数据集取角度阵列:

g['data']['angle'][:] 
g['angle'][:] 
2

在numpy的,你可以在数据存储与结构化数组:

dtype = np.dtype([('angle', np.float16), ('image', np.uint8, (240,320,3))]) 
data = np empty(10, dtype=dtype) 
data[0]['angle'] = ... # etc