【问题标题】:reading HDF5-format MATLAB file in python with h5py使用 h5py 在 python 中读取 HDF5 格式的 MATLAB 文件
【发布时间】:2017-04-23 03:32:47
【问题描述】:

我正在尝试使用 h5py 库在 python 中读取 HDF5 格式的 MATLAB 文件。该文件名为“Q_visSDF_accurate.mat”,有两个键:“filename”和“sdf”。 “文件名包含一个单元格数组字符串。“sdf”是一个包含浮点数的 [6001, 49380] 矩阵。使用以下代码提取变量 sdf 没有问题:

import h5py
data = h5py.File("Q_visSDF_accurate.mat", 'r')
sdf = data.get("sdf")[:,:]
sdf = sdf.astype(float)

但是,我无法读取文件名变量。我试过了:

filename = data.get("filename")[0]

但代码返回:

array([<HDF5 object reference>, <HDF5 object reference>,
   <HDF5 object reference>, ..., <HDF5 object reference>,
   <HDF5 object reference>, <HDF5 object reference>], dtype=object)

我可以取消引用文件名变量的包含吗?使用 hdf5storage 包不是解决方案,因为它仅适用于 python 32 位并且只能读取 matlab 变量的子集。

【问题讨论】:

  • 您是否尝试过使用hdf5storage?它可以将基于 hdf5 的 .mat 文件读取为更可用的形式。
  • 我相应地编辑了我的原始帖子。
  • 你解决了吗?我仍然坚持你的确切问题

标签: python matlab h5py


【解决方案1】:

在 Octave 中,我创建了一个包含单元格和矩阵的文件

>> xmat = [1,2,3;4,5,6;7,8,9];
>> xcell = {1,2,3;4,5,6;7,8,9};
>> save -hdf5 testmat.h5 xmat xcell

ipythonh5py中,我发现这个文件包含2组

In [283]: F = h5py.File('../testmat.h5','r')
In [284]: list(F.keys())
Out[284]: ['xcell', 'xmat']

矩阵组有一个typevalue 数据集:

In [285]: F['xmat']
Out[285]: <HDF5 group "/xmat" (2 members)>
In [286]: list(F['xmat'].keys())
Out[286]: ['type', 'value']
In [287]: F['xmat']['type']
Out[287]: <HDF5 dataset "type": shape (), type "|S7">
In [288]: F['xmat']['value']
Out[288]: <HDF5 dataset "value": shape (3, 3), type "<f8">
In [289]: F['xmat']['value'][:]
Out[289]: 
array([[ 1.,  4.,  7.],
       [ 2.,  5.,  8.],
       [ 3.,  6.,  9.]])

单元格具有相同的typevalue,但value 是另一个组:

In [291]: F['xcell']['type']
Out[291]: <HDF5 dataset "type": shape (), type "|S5">
In [292]: F['xcell']['value']
Out[292]: <HDF5 group "/xcell/value" (10 members)>

In [294]: list(F['xcell']['value'].keys())
Out[294]: ['_0', '_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', 'dims']
...
In [296]: F['xcell']['value']['dims'][:]
Out[296]: array([3, 3])

我不得不使用[...] 来获取单元格的值,因为它是一个 0d 数组:

In [301]: F['xcell']['value']['_0']['value'][...]
Out[301]: array(1.0)

要真正复制我应该创建字符串单元格值的问题,但我认为这很好地说明了单元格的存储方式 - 作为数据组中的命名数据集。

我假设 Octave h5 存储与 MATLAB 兼容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 2022-10-19
    • 2016-02-11
    • 2016-04-08
    • 2015-04-09
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多