python读取.mat数据之scipy.io&h5py

  • python在读写matlab文件时常用到scipy.io文件,但针对大文件以及存储版本在“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/'
  • 导入.h5格式文件
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 文件转换为.mat文件:
#加载.npy文件:
numpy_file = np.load('file_name.npy')
 
#通过scipy.io转换:
import scipy.io as io
io.savemat('file_name.mat',{'data':numpy_file}
 
# 通过h5py转换:
import h5py
file = h5py.File('your_file_name.mat','w')
file.creat_dataset('data',data=numpy_file)
  • 0
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值