我正在尝试读取以下网站 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
用 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/