- python在讀寫(xiě)matlab文件時(shí)常用到scipy.io文件,但針對(duì)大文件以及存儲(chǔ)版本在“matlab-v7.3”以上的文件就只能用h5py模塊。
- 如果你的matlab的版本比較舊,保存的.mat 格式為‘-v7.3’以前的版本,可以采用:scipy.io即可。如果你的matlab的版本比較新,保存的.mat格式為‘-v7.3’的版本,由于scipy.io不支持,所以要采用hdf5
import scipy.io as sio
import numpy as np
import h5py
from PIL import Image
import matplotlib.pyplot as plt # plt 用于顯示圖片
def loadmat2npy(files,filename):
train_x=[]
train_y=[]
test_x=[]
test_y=[]
for i in range(len(files)):
a=sio.loadmat(files[i])
train_x.extend(a['train_x'])
train_y.extend(a['train_y'])
test_x.extend(a['test_x'])
test_y.extend(a['test_y'])
tr_x=np.array(train_x)
tr_y=np.array(train_y)
te_x=np.array(test_x)
te_y=np.array(test_y)
tr_x=np.reshape(tr_x,[-1,28,28,3])
te_x=np.reshape(te_x,[-1,28,28,3])
Tr_y=[]
Te_y=[]
for j in range(len(tr_y)):
Tr_y.append(np.argmax(tr_y[j]))
for j in range(len(te_y)):
Te_y.append(np.argmax(te_y[j]))
np.save(filename+'train_x',tr_x)
np.save(filename+'train_y',Tr_y)
np.save(filename+'test_x',te_x)
np.save(filename+'test_y',Te_y)
print(tr_x.shape,tr_y.shape,te_x.shape,te_y.shape)
def h5py_mat2npy(datemat):
a = h5py.File(datemat)
a.keys()
#test=a['a']
test=a['test']
test=np.array(test)
test=test.T
test_x = np.reshape(test,[-1,28,28,3])
print(np.shape(test_x))
datemat='/home/zx/桌面/代碼/datasets/data1.mat'
filename='/home/zx/桌面/代碼/datasets/'
import h5py
import numpy as np
from sklearn.utils import shuffle
X_train = []
X_test = []
for filename in ["gap_ResNet50.h5", "gap_Xception.h5", "gap_InceptionV3.h5"]:
with h5py.File(filename, 'r') as h:
X_train.append(np.array(h['train']))
X_test.append(np.array(h['test']))
y_train = np.array(h['label'])
X_train = np.concatenate(X_train, axis=1)
X_test = np.concatenate(X_test, axis=1)
X_train, y_train = shuffle(X_train, y_train)
# .npy 文件轉(zhuǎn)換為.mat文件:
#加載.npy文件:
numpy_file = np.load('file_name.npy')
#通過(guò)scipy.io轉(zhuǎn)換:
import scipy.io as io
io.savemat('file_name.mat',{'data':numpy_file}
# 通過(guò)h5py轉(zhuǎn)換:
import h5py
file = h5py.File('your_file_name.mat','w')
file.creat_dataset('data',data=numpy_file)
|