Python如何读取.h5数据的文件并将内容保存为图片

import h5py
import os
import numpy as np
from PIL import Image

dataset = h5py.File('lpba_val.h5', 'r')
first_level_keys = [key for key in dataset.keys()]
for first_level_key in first_level_keys:
    second_level_keys = [key for key in dataset[first_level_key].keys()]
    for second_level_key in second_level_keys:
        if not os.path.exists(second_level_key):
            os.makedirs(os.path.join(first_level_key, second_level_key))
        image_arr = np.array(dataset[first_level_key][second_level_key])
        for idx in range(image_arr.shape[0]):
            image = Image.fromarray(image_arr[idx, :, :])
            image.save(os.path.join(first_level_key, second_level_key, '%03d.png'%idx))
    print(first_level_key)

lpba_val.h5有两级key,最内层key对应一个三维的图像(128,128,128),文件结构如下所示。

├─S01
│  ├─segmentation
│  └─volume
├─S02
│  ├─segmentation
│  └─volume
├─S03
│  ├─segmentation
│  └─volume
├─S04
│  ├─segmentation
│  └─volume
├─S05
│  ├─segmentation
│  └─volume
……
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页