日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python讀取及保存mat文件的注意事項說明_python

作者:向bug低頭。 ? 更新時間: 2023-01-12 編程語言

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。

Python讀取嵌套.mat文件

從網上下載的數據集可能是保存為.mat文件的,保存著很多圖片

我們先來看一下本次實驗所需要的.mat文件,主要結構體為dataset,包含3個字段,分別是train,test,mapping

其中test是11的


在這里插入圖片描述

train和test下分別還有三個字段,分別是images,labels,writers

其中test下的labels是208001的


在這里插入圖片描述

1.首先我們先加載對應的模塊,并用這個模塊加載對應的.mat文件

from scipy.io import loadmat
X = loadmat(r"letters.mat")

注:這里的路徑需要修改

2.然后讀取結構體dataset

data_all = X['dataset'] 

3.讀取結構體下test下三個字段

#此處僅讀取嵌套結構體下的test,還不是存儲的數據
data = data_all[0,0]['test']
print('data.shape',data.shape)
 

#此處讀取真正存儲數據
data_labels = data[0,0]['labels']
print('data_labels.shape',data_labels.shape)

結果為:


在這里插入圖片描述

證明正確讀取嵌套結構體的.mat文件

總結

原文鏈接:https://blog.csdn.net/weixin_43773318/article/details/116429981

欄目分類
最近更新