python将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文件夹路径即可~

猜你喜欢

转载自blog.csdn.net/weixin_43135178/article/details/123471749