【问题标题】:H5PY/Numpy - Setting the inner shape of a numpy arrays (for h5py)H5PY/Numpy - 设置 numpy 数组的内部形状(用于 h5py)
【发布时间】: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。但这并不是您真正希望它的行为方式。

标签: python numpy h5py


【解决方案1】:

@Eric 创建的dtype 应该与numpyh5py 一起使用。但我想知道你是否真的想要或需要它。另一种方法是在numpyimagesangles 中有两个数组,一个是4d uint8,另一个是浮点数。在h5py 中,您可以创建一个group,并将这两个数组存储为datasets

您可以选择ith' 图像的值

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

例如:

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')

具有复合 dtype 的数据集:

g.create_dataset('data', (3,), dtype=dt)
g['data'][:] = data

或具有两个数组的数据集

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
    

    【讨论】:

      猜你喜欢
      • 2014-02-26
      • 2014-01-22
      • 2018-01-02
      • 2019-05-08
      • 1970-01-01
      • 2015-06-01
      • 2016-07-16
      • 1970-01-01
      • 2013-09-05
      相关资源
      最近更新 更多