翻译http://machinelearninguru.com/deep_learning/data_preparation/hdf5/hdf5.html

当我们谈论深度学习时,通常首先想到的是大量数据或大量图像(例如ImageNet中数百万幅图像)。在这种情况下,从硬盘单独加载每个图像并应用图像预处理,然后将其传递到网络进行训练,验证或测试,这并不是非常明智和高效。尽管应用预处理需要时间,但从硬盘读取多个图像要花费更多的时间,而不是将它们全部放在单个文件中,并将它们作为单个数据组读取。我们希望有不同的数据模型和库,如HDF5和TFRecord。希望我们有不同的数据模型和库,如HDF5和TFRecord。在这篇文章中,我们将学习如何将大量图像保存在单个HDF5文件中,然后以批处理方式从文件中加载它们。数据的大小并不重要,或者它大于或小于内存大小。HDF5提供了管理,操作,查看,压缩和保存数据的工具。我们将关注相同的主题,但在我们的使用TFRecord 下一篇文章。

在这篇文章中,我们加载,调整大小并将所有图像保存在着名的Dogs vs. Cats 数据集的train文件夹中 。按照这篇文章的其余部分,你需要下载Dogs vs. Cats数据集的训练部分。

列出图像及其标签

首先,我们需要列出所有图像并标注它们。我们给每个猫图像一个标签= 0,每个狗图像一个标签= 1.下面的代码列出所有图像,给它们适当的标签,然后洗牌数据。我们还将数据集分为三列(%60),验证(%20)和测试部分(%20)。

列出图像并标记它们

from random import shuffle

import glob

shuffle_data = True

# shuffle the addresses before saving

hdf5_path ='Cat vs Dog/dataset.hdf5' # address to where you want to save the hdf5 file

cat_dog_train_path ='Cat vs Dog/train/*.jpg'

#read addresses and labels from the 'train' folder

addrs = glob.glob(cat_dog_train_path)

labels =[0 if 'cat' in addr else 1 for addr in addrs] # 0 = Cat, 1 = Dog

#to shuffle data

if shuffle_data:

c =list(zip(addrs,labels))

shuffle(c)

addrs, labels =zip(*c)

#Divide the hata into 60% train, 20% validation, and 20% test

train_addrs = addrs[0:int(0.6*len(addrs))]

train_labels = labels[0:int(0.6*len(labels))]

val_addrs = addrs[int(0.6*len(addrs)):int(0.8*len(addrs))]

val_labels = labels[int(0.6*len(addrs)):int(0.8*len(addrs))]

test_addrs = addrs[int(0.8*len(addrs)):]

test_labels = labels[int(0.8*len(labels)):]

创建一个HDF5文件

有两个主要的库让你使用HDF5格式,即 h5py 和 tables(PyTables)。我们将在下面解释如何与他们一起工作。第一步是创建一个HDF5文件。为了存储图像,我们应该为每一个训练集,验证集和测试集定义一个数组并按照 Tensorflow older(number of data, image_height, image_width, image_depth)或按照Theano older (number of data, image_height, image_width, image_depth)。对于标签,我们还需要一个数组,用于每个训练,验证和测试集,大小为 (number of data)。最后,我们计算训练集组的像素平均值,并将其保存为(1,image_height,image_width,image_depth)大小的数组 。请注意,当您想为其创建数组时,您总是应该确定数据的类型(dtype)。

tables:在tables中,我们可以使用 create_earray 创建一个空数组(数据数量= 0),我们可以稍后将数据附加到它。对于标签,在这里使用create_array更方便,因为它可以让我们在创建数组时创建标签。要设置数组的dtype,可以为uint8使用表dtype,如tables.UInt8Atom()。

create_earray 和 create_array 方法的第一个属性是data group( we create the arrays in root group),它允许您通过创建不同的data group来管理数据。您可以将组视为HDF5文件中的文件夹。

h5py: 在h5py中,我们使用create_dataset创建一个数组 。请注意,在定义数组时,我们应该确定数组的确切大小。我们也可以使用 create_dataset 作为标签,并立即将标签放在上面。您可以使用numpy dype直接设置数组的dtype。

使用tables案例

import numpy as np

import tables

data_order ='tf'

# 'th' for Theano,'tf' for Tensorflow

img_dtype = tables.UInt8Atom() # dtype in which the images will be saved

#check the order of data and chose proper data shape to save images

if data_order == 'th':

data_shape =(0,3,224,224)

elif data_order == 'tf':

data_shape =(0,224,224,3)

#open a hdf5 file and create earrays

hdf5_file = tables.open_file(hdf5_path,mode='w')

train_storage = hdf5_file.create_earray(hdf5_file.root,'train_img',

img_dtype, shape=data_shape)

val_storage = hdf5_file.create_earray(hdf5_file.root,'val_img',

img_dtype, shape=data_shape)

test_storage = hdf5_file.create_earray(hdf5_file.root,'test_img',

img_dtype, shape=data_shape)

mean_storage = hdf5_file.create_earray(hdf5_file.root,'train_mean',

img_dtype, shape=data_shape)

#create the label arrays and copy the labels data in them

hdf5_file.create_array(hdf5_file.root,'train_labels',train_labels)

hdf5_file.create_array(hdf5_file.root,'val_labels',val_labels)

hdf5_file.create_array(hdf5_file.root,'test_labels',test_labels)

现在,是时候逐一读取图像,应用预处理(只调整我们的代码)然后保存。

# a numpy array to save the mean of the images

mean = np.zeros(data_shape[1:],np.float32)

#loop over train addresses

for i in range(len(train_addrs)):

# print how many images are saved every 1000 images

if i % 1000 == 0 and i > 1:

print'Train data: {}/{}'.format(i,len(train_addrs))

#read an image and resize to (224, 224)

#cv2 load images as BGR, convert it to RGB

addr = train_addrs[i]

img = cv2.imread(addr)

img = cv2.resize(img,(224,224),interpolation=cv2.INTER_CUBIC)

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# add any image pre-processing here

#if the data order is Theano, axis orders should change

if data_order == 'th':

img = np.rollaxis(img,2)

#save the image and calculate the mean so far

train_storage.append(img[None])

mean += img /float(len(train_labels))

#loop over validation addresses

for i in range(len(val_addrs)):

#print how many images are saved every 1000 images

if i % 1000 == 0 and i> 1:

print'Validation data: {}/{}'.format(i,len(val_addrs))

#read an image and resize to (224, 224)

#cv2 load images as BGR, convert it to RGB

addr = val_addrs[i]

img = cv2.imread(addr)

img = cv2.resize(img,(224,224),interpolation=cv2.INTER_CUBIC)

img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

#add any image pre-processing here

# if the data order is Theano, axis orders should change

if data_order == 'th':

img = np.rollaxis(img,2)

#save the image

val_storage.append(img[None])

#loop over test addresses

for i in range(len(test_addrs)):

#print how many images are saved every 1000 images

if i % 1000 == 0 and i> 1:

print'Test data: {}/{}'.format(i,len(test_addrs))

#read an image and resize to (224, 224)

#cv2 load images as BGR, convert it to RGB

addr = test_addrs[i]

img = cv2.imread(addr)

img = cv2.resize(img,(224,224),interpolation=cv2.INTER_CUBIC)

img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

#add any image pre-processing here

#if the data order is Theano, axis orders should change

if data_order == 'th':

img = np.rollaxis(img,2)

#save the image

test_storage.append(img[None])

#save the mean and close the hdf5 file

mean_storage.append(mean[None])

hdf5_file.close()

阅读HDF5文件

是时候检查数据是否正确保存在HDF5文件中。为此,我们以任意大小的批次加载数据并绘制前5批次的第一张图片。我们也检查每张图片的标签。我们定义了一个变量 subtract_mean,它指示我们是否想在显示图像之前减去训练集的平均值。在 表中 ,我们访问每个阵列调用其名称其数据组之后(这样 hdf5_file。组。arrayName中)。您可以将它索引为一个numpy数组。然而,在 h5py中, 我们使用它的名字像字典名称(hdf5_file [ “arrayname” “ ]]来访问数组)。无论哪种情况,您都可以访问数组的形状 。形状 像一个numpy阵列。

import tables

import numpy as np

hdf5_path ='Cat vs Dog/dataset.hdf5'

subtract_mean =False

#open the hdf5 file

hdf5_file = tables.open_file(hdf5_path,mode='r')

#subtract the training mean

if subtract_mean:

mm = hdf5_file.root.train_mean[0]

mm = mm[np.newaxis,...]

#Total number of samples

data_num = hdf5_file.root.train_img.shape[0]

现在我们创建一个批量的列表并对其进行洗牌。现在,我们遍历批次并一次读取每批中的所有图像。

from random import shuffle

from math import ceil

import matplotlib.pyplot as plt

#create list of batches to shuffle the data

batches_list =list(range(int(ceil(float(data_num)/batch_size))))

shuffle(batches_list)

#loop over batches

for n, i in enumerate(batches_list):

i_s = i * batch_size

# index of the first image in this batch

i_e =min([(i+ 1)* batch_size, data_num])

# index of the last image in this batch

#read batch images and remove training mean

images = hdf5_file.root.train_img[i_s:i_e]

if subtract_mean:

images -= mm

#read labels and convert to one hot encoding

labels = hdf5_file.root.train_labels[i_s:i_e]

labels_one_hot = np.zeros((batch_size,nb_class))

labels_one_hot[np.arange(batch_size),labels]= 1

print n+1,'/',len(batches_list)

print labels[0],labels_one_hot[0,:]

plt.imshow(images[0])

plt.show()

if n == 5:

break

hdf5_file.close()

html显示hdf5文件,图片转换成HDF5文件(加载,保存)相关推荐

  1. 如何将JPG图片转换成PDF文件

    图片这种文件格式已经不仅仅是在工作中会使用到,作为我们生活中,朋友之间在网络渠道上聊天交流,也会用图片来表达一些情绪,增添聊天中活跃的气氛.虽然很适用于聊天中,但是如果工作中同事之间传送图片文件,会显 ...

  2. 海思AI芯片(Hi3519A/3559A)方案学习(十四)JPEG图片转换成bgr文件

    原文:https://blog.csdn.net/avideointerfaces/article/details/89931156 前言 在系列文章海思AI芯片(Hi3519A/3559A)方案学习 ...

  3. JAVA 将图片转换成pdf文件

    /** * 将图片转换成pdf文件 *imgFilePath 需要被转换的img所存放的位置. 例如imgFilePath="D:\\projectPath\\55555.jpg" ...

  4. jpg图片转换成pdf文件,方法步骤

    如何把jpg图片转换成pdf文件?近期有不少小伙伴问我,能不能把jpg图片转换成pdf文件,让自己的jpg图片文件能稳定的在不同系统查看使用,这样也就避免了因jpg图片多和格式问题而导致的的打开慢或打 ...

  5. 利用MATLAB将图片转换成coe文件、TXT文件、mif文件、bin文件

    利用MATLAB将图片转换成coe文件.TXT文件.mif文件 利用MATLAB将图片转换成coe文件 利用MATLAB将图片转换成txt文件 利用MATLAB将图片转换成mif文件 利用MATLAB ...

  6. 怎么把图片转换成PDF文件?

    为什么要把图片转换成PDF文件?很多小伙伴可能在工作中接触到大量的图片,但是在工作中,我们无论是自己查阅.发送给别人还是存档,对于数量过多的图片来说是非常不方便的,如果能将同类型的图片转换成PDF格式 ...

  7. 将图片转换成svg文件,自定义icon小图标,svg速成

    将图片转换成svg文件,自定义icon小图标,svg速成 一.svg是什么? 二.操作步骤 1.进入网站 2.将svg复制 3.引用svg文件 总结 一.svg是什么? SVG是一种图像文件格式,它的 ...

  8. 怎么将JPG格式的图片转换成PDF文件?

    图片是我们日常分享的一部分,但如果作为正式文件对外发布的话,零散的图片显然是不适合的,那应该怎么办呢?小编觉得将图片转换成PDF文件是非常有必要的,下面小编就把具体的操作步骤教给大家,一定要仔细学习哦 ...

  9. python 图片转换成py文件

    python 图片转换成py文件 app.png 图片转为py文件.py import base64def pic_to_py(path_):"""将图像文件转换为py文 ...

最新文章

  1. 如何自动以管理员身份运行.NET程序?
  2. 2016年10月起微软更改了更新服务模型
  3. mongodb 输出数组字段_三分钟 mongodb 开发快速上手
  4. SQL case when 2种用法
  5. 联想Z5手机夺得京东销量第一,联想这是要翻盘的节奏吗?
  6. 这款刷爆抖音的玩意儿,竟然是程序员的福音!
  7. 跟我一起考PMP---项目成本管理
  8. tensorflow实践笔记:屏蔽GPU版tensorflow的提示、分布式训练部署时的问题以及tensorboard的查看
  9. 【转】【深度学习MobileNet】——深刻解读MobileNet网络结构
  10. Ubuntu安装tftpd服务器
  11. virtualbox设置了共享文件夹却无权限访问
  12. 通俗易懂去讲解反射(Reflect)
  13. 迪文屏幕T5UID3平台学习笔记零:迪文屏幕的学习和开发
  14. 在线java编译器 api_代码在线编译器(上)- 编辑及编译
  15. 使用Java+SSM(Spring+SpringMVC+Mybatis)如何开发个性化音乐推荐系统 在线音乐推荐网站 基于用户、项目的协同过滤推荐算法实现MusicRecommendSystemWeb
  16. oracle 11.2.0.3RAC升级到11.2.0.4
  17. SpringBoot工程如何打war包进行云部署
  18. STM32官方的一些参考手册资料
  19. 西式快餐是否比起肯德基更多人喜欢麦当劳,如果是原因是什么
  20. 论API hook——说360安全浏览器、金山网盾、瑞星、卡巴斯基、傲游浏览器等软件会互相冲突.

热门文章

  1. 2022前端知识整理:十、vue基础
  2. 红月所有物品完全代码
  3. 树莓派4b常用资料汇总
  4. 【Tableau Desktop 企业日常技巧12】Tableau安装版本要求和配置 信息
  5. 流式计算利器-Storm
  6. 互联网快讯:京东公布“双11”节奏;猿辅导、掌门教育布局素质教育
  7. 【OBS Studio】脚本自动生成大量场景思考实践
  8. Springboot与手机的互动
  9. C语言_函数可变参数列表
  10. 河北大学计算机类信息安全专业就业前景,2018信息安全专业就业前景和就业方向分析...