Python实现mat文件与PNG图片互转:从矩阵到图像

Felix
Felix
发布时间:2026-10-15 | 4人浏览过
原创

本文介绍如何使用Python将MATLAB数据文件(.mat)转换为PNG图片,以及将图片保存为mat格式。通过调用mat73库读取数据,利用PIL和numpy进行矩阵到图像的转换,并提供完整代码示例,涵盖路径配置、文件夹创建及异常处理,解决常见转换错误。

将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})

以上分享为个人实践经验,旨在提供参考,欢迎支持。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表