網(wǎng)上看了一個下午都沒找到能用的。。。抄來抄去都沒說到點子上
mat文件是Matlab的數(shù)據(jù)存儲的標準格式。
涉及到文件轉(zhuǎn)換肯定要看數(shù)據(jù)的結(jié)構(gòu),
事實上別人的代碼很難成功就是因為大家的mat文件的數(shù)據(jù)結(jié)構(gòu)各不相同
照著這個一步一步來你肯定可以學會
1、第一段代碼,包括了引用和函數(shù),不用修改
import cv2
import scipy.io as scio
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os
# 數(shù)據(jù)矩陣轉(zhuǎn)圖片的函數(shù)
def MatrixToImage(data):
data = data * 255
new_im = Image.fromarray(data.astype(np.uint8))
return new_im
2、然后需要設(shè)置你的文件路徑,三處
# 添加路徑,文件夾下存放多個.mat文件
# 兩個文件夾一個放.mat,一個放轉(zhuǎn)換好的圖片
datafolder = r'D:/新建文件夾/RINDNet-main/run/rindnet/depth/mat'
savefolder = r'D:/新建文件夾/RINDNet-main/run/rindnet/depth/out/'
path = os.listdir(datafolder)
print(os.path.splitext('100007.mat'))
# 這一步用于測試你是否正確設(shè)置了路徑,也展示了splitxt函數(shù)的結(jié)果
運行一下查看一下print輸出的是否正常
3、讀取
# 先取一個文件做實驗,接下來在控制臺一行一行運行
each_mat='100007.mat'
first_name, second_name = os.path.splitext(each_mat)
# 拆分.mat文件的前后綴名字,
each_mat = os.path.join(datafolder, each_mat)
# print(each_mat)
# 校驗步驟,輸出應(yīng)該是路徑
array_struct = scio.loadmat(each_mat)
# print(array_struct)
# 校驗步驟,輸出的應(yīng)該是一個結(jié)構(gòu)體,然后查看你的控制臺,看數(shù)據(jù)被存在了哪個字段里
# 我的數(shù)據(jù)被放在了result里,所以下面填result
array_data = array_struct['result'] # 取出需要的數(shù)字矩陣部分
# print(array_data)
# 校驗步驟,看是否正常讀出了數(shù)據(jù)
new_im = MatrixToImage(array_data) # 調(diào)用函數(shù)
plt.imshow(array_data, cmap=plt.cm.gray, interpolation='nearest')
new_im.show()
new_im.save(savefolder+first_name + '.jpg') # 保存圖片
正常運行完這一段,已經(jīng)能夠完成單張圖片的轉(zhuǎn)換了,如果想要別的格式的圖片,只需要改變最后一行
4 批量處理
完整代碼給出,注意你之前設(shè)置的兩個路徑和一個字段文章來源:http://www.zghlxwxcb.cn/news/detail-406784.html
且最終運行的時候為了處理速度應(yīng)該把所有輸出(print和imshow)都注釋掉。文章來源地址http://www.zghlxwxcb.cn/news/detail-406784.html
import cv2
import scipy.io as scio
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os
# 數(shù)據(jù)矩陣轉(zhuǎn)圖片的函數(shù)
def MatrixToImage(data):
data = data * 255
new_im = Image.fromarray(data.astype(np.uint8))
return new_im
# 添加路徑,metal文件夾下存放mental類的特征的多個.mat文件
datafolder = r'D:/新建文件夾/RINDNet-main/run/rindnet/depth/mat'
savefolder = r'D:/新建文件夾/RINDNet-main/run/rindnet/depth/out/'
path = os.listdir(datafolder)
# print(os.path.splitext('100007.mat'))
for each_mat in path:
# 先取一個文件做實驗
# each_mat='100007.mat'
first_name, second_name = os.path.splitext(each_mat)
# 拆分.mat文件的前后綴名字,
each_mat = os.path.join(datafolder, each_mat)
# print(each_mat)
# 校驗步驟,輸出應(yīng)該是文件名
array_struct = scio.loadmat(each_mat)
# print(array_struct)
# 校驗步驟
array_data = array_struct['result'] # 取出需要的數(shù)字矩陣部分
# print(array_data)
# 校驗步驟
new_im = MatrixToImage(array_data) # 調(diào)用函數(shù)
plt.imshow(array_data, cmap=plt.cm.gray, interpolation='nearest')
# new_im.show()
# print(first_name)
new_im.save(savefolder+first_name + '.jpg') # 保存圖片
到了這里,關(guān)于2022/7 用python批量將.mat文件轉(zhuǎn)為.jpg/.png/.bmp格式圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!