【H5】h5文件之——深度学习训练样本制作

    技术2022-07-10  122

    every blog every motto: Light tomorrow with today.

    0. 前言

    作为深度学习的萌新可能都知道,训练以后的参数保存成h5格式文件。那有时候看到训练数据也是h5格式又是为什么呢? 当训练大量数据(图片)时,如果从硬盘加载并预处理,然后传递进网络,这可能是一个非常耗时的过程。 其中从硬盘读取图片会花费大量时间,更可行的方法是将其存在在单个文件中,如HDF5和TFRecord。 其中TFRecord可以参考文章1、文章2等


    本节主要介绍制作自己的H5格式训练数据 说明: 更多关于h5文件介绍,可参考文后链接。

    1. 正文

    1.1 图片转数组

    如果是普通图片,可直接利用下方代码。 from PIL import Image img = Image.Open('./1.png') img_array = np.array(img) 如果是一张大的遥感影像, 遥感影像转数组,点我点我

    1.2 数组切成小块(patch)

    如果上方单张图片就是一个训练样本(patch),可不用切成小块。否则点击下方链接: 对数组进行切割成patch,点我

    1.3 数组保存到h5文件中

    说明: 不以具体数据说明,仅用少量数据进行展示

    import numpy as np import h5py file_path = './1.h5' patches = np.zeros((250, 128, 128, 3)) patches_y = np.zeros(250)

    写入文件

    with h5py.File(file_path, 'w') as f: f['x'] = patches f['y'] = patches_y

    读取文件 说明: 读取时如果用with ,读取到的数据要在with 内,否组容易出错,具体见附录

    f = h5py.File(file_path, 'r') print(f.keys()) print(f['x'].shape) print(f['y'].shape) f.close()

    1.3.1 读取文件尝试(附录)

    下方打印在with 外面,报错。

    # 读取文件 with h5py.File('t.h5','r') as f: x_train = f['x'] y_train = f['y'] print(y_train.shape)

    1.3.2 追加数据(附录)

    第一次写入

    import h5py import numpy as np array = np.zeros(250) arr = np.ones(10) path = './dataset/w.h5' # f = h5py.File(path, 'a') # f['x'] = array # f.close()

    添加新数据

    # f = h5py.File(path, 'a') # f['y'] = arr # f.close()

    参考文献

    [1] https://blog.csdn.net/Hero_Never_GIVE_UP/article/details/85006835 [2] https://blog.csdn.net/mzpmzk/article/details/89188968 [3] https://www.jianshu.com/p/ae12525450e8 [4] https://www.jianshu.com/p/19f3ca564644 [5] https://reference.wolfram.com/language/ref/format/HDF5.html [6] https://blog.csdn.net/u010945683/article/details/79931702 [7] https://blog.csdn.net/chaofanjun/article/details/88850324 [8] https://blog.csdn.net/lsh894609937/article/details/77018622 [9] https://blog.csdn.net/w5688414/article/details/78907180?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase [10] https://blog.csdn.net/weixin_39190382/article/details/106441762 [11] https://blog.csdn.net/weixin_39190382/article/details/104348060 [12] https://blog.csdn.net/w5688414/article/details/86104271

    Processed: 0.010, SQL: 9