热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

翻译http:machinelearninguru.comdeep_learningdata_preparationhdf5hdf5.html当我们谈论深度学习时,通

翻译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()



推荐阅读
  • 颜色迁移(reinhard VS welsh)
    不要谈什么天分,运气,你需要的是一个截稿日,以及一个不交稿就能打爆你狗头的人,然后你就会被自己的才华吓到。------ ... [详细]
  • Day2列表、字典、集合操作详解
    本文详细介绍了列表、字典、集合的操作方法,包括定义列表、访问列表元素、字符串操作、字典操作、集合操作、文件操作、字符编码与转码等内容。内容详实,适合初学者参考。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • OpenCV4.5.0+contrib编译流程及解决错误方法
    本文介绍了OpenCV4.5.0+contrib的编译流程,并提供了解决常见错误的方法,包括下载失败和路径修改等。同时提供了相关参考链接。 ... [详细]
  • 本文介绍了PhysioNet网站提供的生理信号处理工具箱WFDB Toolbox for Matlab的安装和使用方法。通过下载并添加到Matlab路径中或直接在Matlab中输入相关内容,即可完成安装。该工具箱提供了一系列函数,可以方便地处理生理信号数据。详细的安装和使用方法可以参考本文内容。 ... [详细]
  • 解决Cydia数据库错误:could not open file /var/lib/dpkg/status 的方法
    本文介绍了解决iOS系统中Cydia数据库错误的方法。通过使用苹果电脑上的Impactor工具和NewTerm软件,以及ifunbox工具和终端命令,可以解决该问题。具体步骤包括下载所需工具、连接手机到电脑、安装NewTerm、下载ifunbox并注册Dropbox账号、下载并解压lib.zip文件、将lib文件夹拖入Books文件夹中,并将lib文件夹拷贝到/var/目录下。以上方法适用于已经越狱且出现Cydia数据库错误的iPhone手机。 ... [详细]
  • 本文介绍了在Windows环境下如何配置php+apache环境,包括下载php7和apache2.4、安装vc2015运行时环境、启动php7和apache2.4等步骤。希望对需要搭建php7环境的读者有一定的参考价值。摘要长度为169字。 ... [详细]
  • 本文讨论了Kotlin中扩展函数的一些惯用用法以及其合理性。作者认为在某些情况下,定义扩展函数没有意义,但官方的编码约定支持这种方式。文章还介绍了在类之外定义扩展函数的具体用法,并讨论了避免使用扩展函数的边缘情况。作者提出了对于扩展函数的合理性的质疑,并给出了自己的反驳。最后,文章强调了在编写Kotlin代码时可以自由地使用扩展函数的重要性。 ... [详细]
  • Redis底层数据结构之压缩列表的介绍及实现原理
    本文介绍了Redis底层数据结构之压缩列表的概念、实现原理以及使用场景。压缩列表是Redis为了节约内存而开发的一种顺序数据结构,由特殊编码的连续内存块组成。文章详细解释了压缩列表的构成和各个属性的含义,以及如何通过指针来计算表尾节点的地址。压缩列表适用于列表键和哈希键中只包含少量小整数值和短字符串的情况。通过使用压缩列表,可以有效减少内存占用,提升Redis的性能。 ... [详细]
  • Windows7 64位系统安装PLSQL Developer的步骤和注意事项
    本文介绍了在Windows7 64位系统上安装PLSQL Developer的步骤和注意事项。首先下载并安装PLSQL Developer,注意不要安装在默认目录下。然后下载Windows 32位的oracle instant client,并解压到指定路径。最后,按照自己的喜好对解压后的文件进行命名和压缩。 ... [详细]
  • 本文介绍了安全性要求高的真正密码随机数生成器的概念和原理。首先解释了统计学意义上的伪随机数和真随机数的区别,以及伪随机数在密码学安全中的应用。然后讨论了真随机数的定义和产生方法,并指出了实际情况下真随机数的不可预测性和复杂性。最后介绍了随机数生成器的概念和方法。 ... [详细]
  • OpenMap教程4 – 图层概述
    本文介绍了OpenMap教程4中关于地图图层的内容,包括将ShapeLayer添加到MapBean中的方法,OpenMap支持的图层类型以及使用BufferedLayer创建图像的MapBean。此外,还介绍了Layer背景标志的作用和OMGraphicHandlerLayer的基础层类。 ... [详细]
  • #define_CRT_SECURE_NO_WARNINGS#includelist.h#includevoidSListInit(PNode*pHead ... [详细]
  • Python教学练习二Python1-12练习二一、判断季节用户输入月份,判断这个月是哪个季节?3,4,5月----春 ... [详细]
author-avatar
千片叶
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有