1. 程式人生 > >python-mat轉為圖片儲存

python-mat轉為圖片儲存

資料如上所示,主資料夾下有/home/kls/Desktop/data/ucf101_fea_video/51_v_Lungers_g21_c05.mat,mat第一維為fea_tmp也是一個mat,第二維為fea_spa也是一個mat,我們要將fea_tmp轉換為jpg

import cv2
import scipy.io as scio
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os

# 資料矩陣轉圖片的函式
def MatrixToImage(data):
    new_im = Image.fromarray(data,mode='RGB')
    return new_im

folder = r'/home/kls/Desktop/data/ucf101_fea_video/'
path = os.listdir(folder)
for each_mat in path:
        first_name, second_name = os.path.splitext(each_mat)
        # 拆分.mat檔案的前後綴名字,注意是**路徑**
        #yong yu fen ge wen jian min yu kuo zhan min
        each_mat = os.path.join(folder, each_mat)
        # print(each_mat)
        array_struct = scio.loadmat(each_mat)
        fea_spa=array_struct['fea_spa']
        fea_tmp=array_struct['fea_tmp']
        for i  in range(1,len(fea_spa)):
             fea_spa_1=np.reshape(fea_spa[i],(32,32))
             print('i=',i)
             fea_spa_image = MatrixToImage(fea_spa_1)# 呼叫函式
             path='/home/kls/Desktop/data/fea_spa/'+first_name+'/'
             if os.path.exists(path) is False:
                 os.makedirs(path)
             fea_spa_image.save(path+str(i)+'.jpg')# 儲存圖片
             
             fea_tmp_1=np.reshape(fea_tmp[i],(32,32))
             print('i1=',i)
             fea_tmp_image = MatrixToImage(fea_tmp_1)# 呼叫函式
             path='/home/kls/Desktop/data/fea_tmp/'+first_name+'/'
             if os.path.exists(path) is False:
                 os.makedirs(path)
             fea_tmp_image.save(path+str(i)+'.jpg')# 儲存圖片