python - 如何在python中读取Mat v7.3文件?

标签 python matlab hdf5 mat h5py

我正在尝试读取以下网站 ufldl.stanford.edu/housenumbers 中给出的 mat 文件,在文件 train.tar.gz 中,有一个名为 digitStruct.mat 的 mat 文件。

当我使用 scipy.io 读取 mat 文件时,它提醒我消息“请使用 hdf 阅读器读取 matlab v7.3 文件”。

原始matlab文件如下提供

load digitStruct.mat
for i = 1:length(digitStruct)
    im = imread([digitStruct(i).name]);
    for j = 1:length(digitStruct(i).bbox)
        [height, width] = size(im);
        aa = max(digitStruct(i).bbox(j).top+1,1);
        bb = min(digitStruct(i).bbox(j).top+digitStruct(i).bbox(j).height, height);
        cc = max(digitStruct(i).bbox(j).left+1,1);
        dd = min(digitStruct(i).bbox(j).left+digitStruct(i).bbox(j).width, width);

        imshow(im(aa:bb, cc:dd, :));
        fprintf('%d\n',digitStruct(i).bbox(j).label );
        pause;
    end
end

如上图,mat文件有key'digitStruct',在'digitStruct'中可以找到key'name'和'bbox',我使用h5py API读取文件。

import h5py
f = h5py.File('train.mat')
print len( f['digitStruct']['name'] ), len(f['digitStruct']['bbox']   )

我可以读取数组,但是当我遍历数组时,如何读取每个项目?

for i in f['digitStruct']['name']:
    print i # only print out the HDF5 ref

最佳答案

用 Matlab 编写:

test = {'Hello', 'world!'; 'Good', 'morning'; 'See', 'you!'};
save('data.mat', 'test', '-v7.3') % v7.3 so that it is readable by h5py

enter image description here

用 Python 阅读(适用于任何数字或行或列,但假设每个单元格都是一个字符串):

import h5py
import numpy as np

data = []
with h5py.File("data.mat") as f:
    for column in f['test']:
        row_data = []
        for row_number in range(len(column)):            
            row_data.append(''.join(map(unichr, f[column[row_number]][:])))   
        data.append(row_data)

print data
print np.transpose(data)

输出:

[[u'Hello', u'Good', u'See'], [u'world!', u'morning', u'you!']]

[[u'Hello' u'world!']
 [u'Good' u'morning']
 [u'See' u'you!']]

关于python - 如何在python中读取Mat v7.3文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509163/

相关文章:

python - fillna 与 None 串联

python - 如何通过整个 MainWIndow 将 CSS 样式应用到 QMenu

excel - Matlab - 为什么有时 xslread 不允许使用数字作为工作表参数?

matlab - 在 matlab 中可视化大矩阵

user-interface - 使用 uigetfile 而不是 uigetdir 在 Matlab 中获取目录

c++ - hdf5.h 在Ubuntu和CMake下没有这个文件或目录

python - 安装 pyspeckit 时 matplotlib 错误

python - Pandas:在多索引数据框中创建新的(子级)列并分配值

python - 检查 HDF5 Store 对象是否为空?

c++ - fatal error : H5Cpp. h:没有那个文件或目录