如何通过h5py读取v7.3 mat文件? [英] How to read a v7.3 mat file via h5py?

查看:504
本文介绍了如何通过h5py读取v7.3 mat文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由matlab创建并以v7.3格式的mat文件存储的结构数组:

I have a struct array created by matlab and stored in v7.3 format mat file:

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

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

Now I want to read this file via python using h5py:

data = h5py.File('test.mat')
struArray = data['/struArray']

我不知道如何从struArray一一获取结构数据:

I have no idea how to get the struct data one by one from 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>

推荐答案

使用h5py处理Matlab 7.3文件格式并非易事.它依赖于HDF5参考,参见. 关于参考的h5py文档.

Matlab 7.3 file format is not extremely easy to work with h5py. It relies on HDF5 reference, cf. h5py documentation on references.

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

要阅读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

请注意,Matlab将数字存储为大小为(1,1)的数组,因此最后一个[0, 0]会获取该数字.

Notice that Matlab stores a number as an array of size (1, 1), hence the final [0, 0] to get the number.

要阅读struArray(i).data:

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

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

To read struArray(i).name, it is necessary to convert the array of integers to string:

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

这篇关于如何通过h5py读取v7.3 mat文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆