概述
H5文件是層次數據格式第5代的版本(Hierarchical Data Format,HDF5),它是用於存儲科學數據的一種文件格式和庫文件。由美國超級計算中心與應用中心研發的文件格式,用以存儲和組織大規模數據。
h5文件為一個存放數據的容器,包括group名稱和datasets,group名稱為key,datasets為value,文件結構如下圖:
首先讀取文件的group值,也即key值,根據key值加載datasets,datasets的文件可為圖像、文本、pdf 或其他數據形式。
import h5py as h5
## 獲取文件的group(key)值
file = h5.File(file_path, "r")
groups = [key for key in file.keys()]
print(groups)
代碼
# 加載.h5圖片數據
## import
import os
from PIL import Image
import numpy as np
import h5py as h5
## functions
def save_image(file, groups):
'''
將.h5/group下的array轉換為灰度圖像並存儲
:param group: .h5文件包中的組名(key值)
:param save_path: 圖像存儲的路徑
:return: None
'''
for group in groups:
print(group + " 組:")
image_path = input("請輸入第一組圖片要存儲的路徑(不存儲輸入N):")
counter = 0
for i in file[group][:]:
if image_path == "N":
continue
else:
makedir(image_path)
save_path = image_path + str(counter) + ".png"
image = np.array(i)
image *= 255 # 變換為0-255的灰度值
image = Image.fromarray(image)
image = image.convert('L') # 灰度為L,彩色為RGB’
image.save(save_path)
print(counter + 1)
counter += 1
print("done!")
def makedir(dir_path):
'''
創建文件夾
:param dir_path: 文件夾路徑
:return: None
'''
isExists = os.path.exists(dir_path)
if not isExists: # 判斷如果文件不存在,則創建
os.makedirs(dir_path)
def load_h5(file_path):
'''
加載.h5數據
:param file_path: .h5文件路徑
:return: groups, file
'''
file = h5.File(file_path, "r")
groups = [key for key in file.keys()]
print("該文件共有以下幾組:", groups)
return groups, file
## main
if __name__ == "__main__":
h5_file = input("輸入.h5文件路徑:")
groups, file = load_h5(h5_file)
save_image(file, groups)
操作說明
-
輸入.h5文件路徑
-
根據提示輸入每組的存儲路徑 (注意路徑最后要加 \ )
-
無需創建文件夾,輸入路徑會自動創建
-
提取的圖片如下