**
Python读取及保存mat文件
**
在说明python读取mat文件之前需要强调2点:
- 读取的时候需要注意读出来的shape是什么样的,是否符合自己的预期,如果shape不是自己预期的那样,就需要用np.transpose(mat, [x, x, x])进行修正。
- 读取的时候需要注意取值范围,也就是最大值,因为在作为训练数据的时候需要首先进行归一化(避免无法收敛),而不同的mat文件的最大值是不一样的,有0-1、0-255、0-212、0-216。
python实现mat文件的读取主要有3个函数:
import scipy.io as io
imgpath = r"E:\shujuji\CAVE\CAVE_mat\balloons_ms.mat"
mat = io.loadmat(imgpath)['rad']
import h5py
imgpath = r"E:\shujuji\CAVE\CAVE_mat\balloons_ms.mat"
mat = h5py.File(imgpath, 'r')['rad']
import hdf5storage as hdf5
imgpath = r"E:\shujuji\CAVE\CAVE_mat\balloons_ms.mat"
mat = hdf5.loadmat(imgpath)['rad']
这里推荐使用第三种,也就是使用hdf5storage库进行读取,原因在于前两种与保存该mat文件时所用matlab的版本有关(7.3),也就是说一个mat文件要么能用scipy.io读,要么能用h5py能读。
而hdf5storage就不存在这个问题,一般的mat文件都能读取。
再就是使用不同函数读取时的shape不一致,容易搞乱,使用hdf5storage读取的shape和cv2.imread()读取RGB时的shape一致,方便处理。
python实现mat文件的保存同样建议使用hdf5storage(好像scipy也可):
hdf5storage.savemat(r"output\balloons_ms.mat", {'cube': mat}, format='7.3')
hdf5storage.savemat(r"output\balloons_ms.mat", {'rgb': rgb}, format='7.3')
使用hdf5storage保存时mat的shape是什么样的,用它读出来也就是什么样的,比较方便。
所以建议读取和保存都使用hdf5storage。