python读取mat文件中的struct

All devils are in the details,做个笔记。

mat文件结构如下
ground_truth_data 是1x1的struct(结构体),包含2个字段,一个是list,一个是imgszie.如图1所示

python读取mat文件中的struct

                                                                                            图1

list是一个352x1的cell,点开后如图2,可以看到list中的每一个cell又由1x1的strcuct组成.

python读取mat文件中的struct

                                                                                           图2

点开1x1的struct如图3:

python读取mat文件中的struct

                                                                                           图3 

如果我现在想把这352个1x1的struct值(包括imgname和bbox)都用python提出来然后以txt的格式存储,应该怎么做?

经过查找资料,总结如下

1、我使用scipy.io模块加载时,pycharm控制台报错如下:

python读取mat文件中的struct

这是因为scipy.io只能支持matlab版本小于v7.3版本的mat文件。换句话说就是,如果你的matlab版本比较旧,保存的mat格式为-v7.3及其以前的版本,可以用scipy.io读取. 如果是比较新的matlab保存的mat文件,就只能用h5py模块载入了,并且它支持大文件的存储和读取.

解决办法:改用h5py模块载入mat并读取struct值,代码如下

import h5py
data = h5py.File("D:\\Build_my_net\\tensorflow-vgg-master\\tensorflow-vgg-master\help_others\\train_ground_truth_data.mat")
test = data['ground_truth_data/list']
print(test.shape)  #执行完这一行,输出的是(1,352) ,这里和python中numpy数组的shape返回的不一
#样,这里第一个值表示的列,第二个值表示的是行
for i in range(test.shape[1]):   #test.shape[1]的值是352
    for k in data[(test[0][i])].values():
        print(k[:])

 

如果有字符,记得用chr()函数转成字符后显示.