2016-12-15 87 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