如何通过h5py读取v7.3 mat文件?

Eas*_*sun 15 python matlab hdf5 h5py mat

我有一个由matlab创建的struct数组,并存储在v7.3格式的mat文件中:

struArray = struct('name', {'one', 'two', 'three'}, 
                   'id', {1,2,3}, 
                   'data', {[1:10], [3:9], [0]})
save('test.mat', 'struArray', '-v7.3')
Run Code Online (Sandbox Code Playgroud)

现在我想通过python使用h5py读取这个文件:

data = h5py.File('test.mat')
struArray = data['/struArray']
Run Code Online (Sandbox Code Playgroud)

我不知道如何逐个获取结构数据struArray:

for index in range(<the size of struArray>):
    elem = <the index th struct in struArray>
    name = <the name of elem>
    id = <the id of elem>
    data = <the data of elem>
Run Code Online (Sandbox Code Playgroud)

nbe*_*dou 7

使用h5py处理Matlab 7.3文件格式不是很容易。它依赖于HDF5参考,参见。h5py参考文献文档

>>> import h5py
>>> f = h5py.File('test.mat')
>>> list(f.keys())
['#refs#', 'struArray']
>>> struArray = f['struArray']
>>> struArray['name'][0, 0]  # this is the HDF5 reference
<HDF5 object reference>
>>> f[struArray['name'][0, 0]].value  # this is the actual data
array([[111],
       [110],
       [101]], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)

阅读struArray(i).id

>>> f[struArray['id'][0, 0]][0, 0]
1.0
>>> f[struArray['id'][1, 0]][0, 0]
2.0
>>> f[struArray['id'][2, 0]][0, 0]
3.0
Run Code Online (Sandbox Code Playgroud)

请注意,Matlab将数字存储为大小为(1,1)的数组,因此最终存储[0, 0]了该数字。

阅读struArray(i).data

>>> f[struArray['data'][0, 0]].value
array([[  1.],
       [  2.],
       [  3.],
       [  4.],
       [  5.],
       [  6.],
       [  7.],
       [  8.],
       [  9.],
       [ 10.]])
Run Code Online (Sandbox Code Playgroud)

要读取struArray(i).name,必须将整数数组转换为字符串:

>>> f[struArray['name'][0, 0]].value.tobytes()[::2].decode()
'one'
>>> f[struArray['name'][1, 0]].value.tobytes()[::2].decode()
'two'
>>> f[struArray['name'][2, 0]].value.tobytes()[::2].decode()
'three'
Run Code Online (Sandbox Code Playgroud)