python使用h5py读取mat文件数据,并保存图像

来源:互联网 发布:psv重新构筑数据库 编辑:程序博客网 时间:2024/04/30 03:14

1 安装h5py

sudo apt-get install libhdf5-devsudo pip install h5py

假设你已经安装好python和numpy模块


2 读取mat文件数据

import numpy as npimport h5pyf = h5py.File('data.mat') data = f['cell_name'][:]
cell_name是元胞数组的名称,假如有多级元胞目录,可以指定任意的元胞数组进行读取,比如
data = f['cell_name/.../指定的元胞数组'][:]


3 保存图像

img = images[i,...].transpose((2, 1, 0))file = 'make3d_dataset_f460/images/'+str(i+1)+'.jpg'img = img*255img = img.astype('uint8')cv2.imwrite(file, img)#pyplot.imsave(file, img)

整个代码流程:

import cv2import numpy as npimport h5pyfrom matplotlib import pyplotheight = 460width = 345def extract_data():with h5py.File('make3d_dataset_f460.mat','r') as f:images = f['make3d_dataset_fchange/images'][:]image_num = len(images)for i in range(image_num):img = images[i,...].transpose((2, 1, 0))file = 'make3d_dataset_f460/images/'+str(i+1)+'.jpg'img = img*255img = img.astype('uint8')cv2.imwrite(file, img)#pyplot.imsave(file, img)def extract_labels():with h5py.File('make3d_dataset_f460.mat','r') as f:depths = f['make3d_dataset_fchange/depths'][:]depth_num = len(depths)for i in range(depth_num):img = depths[i,...].transpose((1, 0))file = 'make3d_dataset_f460/depths/'+str(i+1)+'.jpg'depth = imgdepth = depth.astype('uint8')cv2.imwrite(file, depth)#pyplot.imsave(file, img)def main(argv=None):# Input  and groundtruth producerextract_data()extract_labels()print("Training data is converted into images!")if __name__ == '__main__':main()






1 0