牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2016-04-18 投稿人: 浏览次数:5171

1 安装h5py

sudo apt-get install libhdf5-dev
sudo pip install h5py

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


2 读取mat文件数据

import numpy as np
import h5py
f = 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*255
		img = img.astype("uint8")
		cv2.imwrite(file, img)
#		pyplot.imsave(file, img)

整个代码流程:

import cv2
import numpy as np
import h5py
from matplotlib import pyplot

height = 460
width = 345

def 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*255
		img = 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 = img
		depth = depth.astype("uint8")
		cv2.imwrite(file, depth)
#		pyplot.imsave(file, img)

def main(argv=None):
	# Input  and groundtruth producer
	extract_data()
	extract_labels()
	print("Training data is converted into images!")

if __name__ == "__main__":
	main()






声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。