import cv2
import scipy.io as scio
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os
import scipy.misc as misc
def MatrixToImage(data):
#new_im = Image.fromarray(data,mode='L')
new_im = Image.fromarray(data.astype(np.uint8))
return new_im
# 添加路径,多个.mat文件所在的文件夹
folder = r'E:/Paper/Alldatasets/dukebox/Normal'
path = os.listdir(folder)
#这个外循环是把文件里的每个mat都遍历一遍,文件里有10个mat文件,所以j是0~9
for each_mat,j in zip(path,range(0,9)):
if each_mat == '.DS_Store':
pass
else:
first_name, second_name = os.path.splitext(each_mat)
# 拆分.mat文件的前后缀名字,注意是**路径**
each_mat = os.path.join(folder, each_mat)
print('第'+format(j)+'个文件')
array_struct = scio.loadmat(each_mat)
array_data = array_struct['images']# 取出需要的数字矩阵部分
#print(array_data.shape) #(512, 1000, 100),每个文件有100张大小为512*1000的切片
for i in range(0,100):
C=array_data[:,:,i] #取出第i+1个二维数组,即第i+1张切片
img = cv2.resize(C, (448, 448)) #修改图片尺寸,函数的参数C的类型是numpy.ndarray
new_im = MatrixToImage(img)# 调用函数,把numpy转成图片
#plt.imshow(C) #显示切片的图片,但是这里显示的图片颜色可能会有问题
#new_im.show() #显示要保存的图片
new_im.save('E:/Paper/Alldatasets/dukebox/object/normal'+format(j)+'_'+format(i)+'.bmp')
i=i+1
只需要把文件路径,图片保存路径,还有两个循环中的文件数量,图片数量这两个数字,你要保存的图片的尺寸,改成你自己的,就可以完美运行了。