【问题标题】:how to import .mat-v7.3 file using h5py如何使用 h5py 导入 .mat-v7.3 文件
【发布时间】:2018-02-13 03:18:54
【问题描述】:

我有 .mat 文件,其中包含 3 个矩阵 A、B、C。

其实我是用 scipy.io 来导入这个 mat 文件的,如下。

data = sio.loadmat('/data.mat')
A = data['A']
B = data['B']
C = data['C']

但是,v7.3 文件无法使用这种方式导入。 所以,我尝试使用 h5py 导入,但我不知道如何使用 h5py。 我的代码如下。

f = h5py.File('/data.mat', 'r')
A = f.get('/A')
A = np.array('A')

哪一部分错了? 谢谢!

【问题讨论】:

标签: python matlab hdf5 h5py hdf5storage


【解决方案1】:

八度音

>> A = [1,2,3;4,5,6];
>> B = [1,2,3,4];
>> save -hdf5 abc.h5 A B

在 Ipython 中

In [138]: import h5py
In [139]: f = h5py.File('abc.h5')
In [140]: list(f.keys())
Out[140]: ['A', 'B']
In [141]: list(f['A'].keys())
Out[141]: ['type', 'value']
In [142]: f['A']['value']
Out[142]: <HDF5 dataset "value": shape (3, 2), type "<f8">
In [143]: A = f['A']['value'][:]
In [144]: A
Out[144]: 
array([[ 1.,  4.],
       [ 2.,  5.],
       [ 3.,  6.]])

另请参阅侧边栏中的链接。

基本上是找到所需的数据集,然后按照http://docs.h5py.org/en/latest/high/dataset.html#reading-writing-data中的描述加载它

https://pypi.python.org/pypi/hdf5storage/0.1.14 - 这个包有MATLAB MAT v7.3 file support。我还没用过。


In [550]: import hdf5storage
In [560]: bar = hdf5storage.read(filename='abc.h5')
In [561]: bar
Out[561]: 
array([ ([(b'matrix', [[ 1.,  4.], [ 2.,  5.], [ 3.,  6.]])], [(b'matrix', [[ 1.], [ 2.], [ 3.], [ 4.]])])],
      dtype=[('A', [('type', 'S7'), ('value', '<f8', (3, 2))], (1,)), ('B', [('type', 'S7'), ('value', '<f8', (4, 1))], (1,))])

因此文件已作为结构化数组加载,具有形状 (1,) 和 2 个字段,“A”和“B”(2 个变量名称)。每个都有一个“类型”和“值”字段。

In [565]: bar['A']['value']
Out[565]: 
array([[[[ 1.,  4.],
         [ 2.,  5.],
         [ 3.,  6.]]]])

或者使用它的loadmat:

In [570]: out = hdf5storage.loadmat('abc.h5',appendmat=False)
In [571]: out
Out[571]: 
{'A': array([(b'matrix', [[ 1.,  4.], [ 2.,  5.], [ 3.,  6.]])],
       dtype=[('type', 'S7'), ('value', '<f8', (3, 2))]),
 'B': array([(b'matrix', [[ 1.], [ 2.], [ 3.], [ 4.]])],
       dtype=[('type', 'S7'), ('value', '<f8', (4, 1))])}

out 是一个字典:

In [572]: out['B']['value']
Out[572]: 
array([[[ 1.],
        [ 2.],
        [ 3.],
        [ 4.]]])

对于读取一个简单的 MATLAB 文件,这并没有增加太多。它可能会添加更多单元格或结构。但是对于编写一个 MATLAB 兼容的文件,它应该是一个很大的帮助(虽然对于编写一个可以坚持使用scipy.io.savemat)。

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2015-01-30
    • 2016-02-04
    • 2021-02-23
    • 2015-02-24
    • 2017-12-13
    • 2017-12-25
    • 2016-07-21
    相关资源
    最近更新 更多