python如何將mat文件轉為png

將mat文件轉為png

花費瞭很大力氣做這件事,總是出現各種錯誤,現在終於解決瞭

from PIL import Image
import matplotlib.pyplot as plt
import glob
import os
import numpy as np
import mat73
 
# 數據矩陣轉圖片的函數
def MatrixToImage(data):
    data = data*255
    new_im = Image.fromarray(data.astype(np.uint8))
    return new_im
 
def mkdir(path):
    folder = os.path.exists(path)
    if not folder:  # 判斷是否存在文件夾如果不存在則創建為文件夾
        os.makedirs(path)  # makedirs 創建文件時如果路徑不存在會創建這個路徑
        print("--- create new folder...  ---")
    else:
        print("---  There is this folder!  ---")
 
# Get all png files under the input folder
input_img_path = glob.glob("I:/CCCC--數據集/去噪/dnd_2017/input/*.mat")
save_path = "blur13x13/"
 
 
mkdir(save_path)  # 調用函數
i = 0
 
for file in input_img_path:
    file_name = file.split('\\')[-1]
 
    try:
        mat = mat73.loadmat(file)
        new_name = str(mat.keys())
        key_name = list(mat.keys())[-1]
        key_name = mat[key_name]
        print(key_name.shape)
        new_im = MatrixToImage(key_name)
        plt.imshow(key_name,  interpolation='nearest')
        new_im.save(save_path+'{}.png'.format(file_name))
    except Exception as e:
        pass
 
    i = i + 1
    print("The", i, "picture is currently being processed")
    continue

完整代碼如上,隻需要修改輸入的mat文件夾路徑即可~

將圖片轉換為mat格式

import cv2
import numpy as np
import h5py
import math
import glob
import os
import scipy.io as io
 
def save_to_mat(img,output_name):
    new_data_path = os.path.join(os.getcwd(),"matType")
    if not os.path.isdir(new_data_path):
        os.mkdir(new_data_path)
    npy_data = np.array(img,dtype= "uint16")
    np.save(new_data_path+'/{}.npy'.format(output_name),npy_data)
    npy_load = np.load(new_data_path+'/{}.npy'.format(output_name))
    io.savemat(new_data_path+'/{}.mat'.format(output_name),{'data':npy_load})

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: