要遍历形状为 (1, 1, 256, 256, 3)
的MAT文件中的每个文件夹并将其转换为PNG格式,你可以使用以下代码作为参考。这里,我们假设每个文件夹包含一个图像,你可能需要根据实际情况进行调整:
import scipy.io as scio import os datafolder = r'你文件的绝对路径但不包括文件名' each_mat = '文件名称.mat' each_mat = os.path.join(datafolder, each_mat) array_struct = scio.loadmat(each_mat) print(array_struct)
获取你mat文件的键值
然后开始mat转png
import os import scipy.io as scio from PIL import Image import numpy as np # 读取MAT文件 dataFile = r'文件路径' #文件的相对/绝对路径 data = scio.loadmat(dataFile) # 从键中获取五维数据 a = data['文件的键值'] # 获取数据的形状 num_samples, _, height, width, channels = a.shape # 遍历每个文件夹 for sample_index in range(num_samples): # 取得每个文件夹中的数据 image_data = a[sample_index, 0, :, :, :] # 将数据转为PNG图像 image_data = (image_data * 255).astype(np.uint8) new_im = Image.fromarray(image_data) # 创建文件夹用于保存PNG图像 output_folder = f'output_folder_{sample_index}' os.makedirs(output_folder, exist_ok=True) # 保存PNG图像 output_path = os.path.join(output_folder, f'image_{sample_index}.png') new_im.save(output_path) print(f"Saved PNG image to {output_path}")
运行后会保存在当前文件夹,很多个文件夹。
这个代码会遍历每个文件夹(通过 sample_index
迭代),将对应的图像数据保存为PNG格式,并放置在以 output_folder_0
, output_folder_1
, ... 命名的文件夹中。确保 output_folder
是一个合适的目录,你可以根据需要调整保存的路径和文件名。