Keras-图片预处理
图片预处理
图片生成器ImageDataGenerator
keras.preprocessing.image.ImageDataGenerator(featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
zca_epsilon=1e-6,
rotation_range=0.,
width_shift_range=0.,
height_shift_range=0.,
shear_range=0.,
zoom_range=0.,
channel_shift_range=0.,
fill_mode='nearest',
cval=0.,
horizontal_flip=False,
vertical_flip=False,
rescale=None,
preprocessing_function=None,
data_format=K.image_data_format())
用以生成一个batch的图像数据,支持实时数据提升。训练时该函数无限生成数据,知道达到规定的epoch次数为止。
参数
- featurewise_center:布尔值,使输入数据集去中心化(均值为0)按feature执行
- samplewise_center:布尔值,使输入数据的每个样本均值为0
- featurewise_std_normalization:布尔值,将输入除以数据集的标准差以完成标准化,按feature执行
- samplewise_std_normalization:布尔值,将输入的每个样本除以其自身的标准差
- zca_whitening:布尔值,对输入数据施加ZCA白化
- zca_epsilon:ZCA使用的eposilon,默认是1e-6
- rotation_range:整数,数据增强时图片随机转动的角度
- width_shift_range:浮点数,图片宽度的某个比例,数据增强时图片水平偏移的幅度
- height_shift_range:浮点数,图片高度的某个比例,数据提升时图片竖直偏移的幅度
- shear_range:浮点数,剪切强度(逆时针方向的剪切变换角度)
- zoom_range:浮点数或形如[lower,upper]的列表,随机缩放的幅度,若为浮点数,则相当于[lower,upper] = [ 1 - zoom_range, 1 + zoom_range ]
- channel_shift_range:浮点数,随机通道偏移的幅度
- fill_mode:'constant','nearest','reflect','wrap'之一,当进行变换时超出边界的点将根据本参数给定的方法进行处理
- cval:浮点数或整数,当fill_model=constant时,指定要向超出边界的点填充的值
- horizontal_flip:布尔值,进行随机水平翻转
- vertical_flip:布尔值,进行随机竖值翻转
- rescale:重放缩因子,默认为None,如果为None或0则不进行放缩,否则会将该数值乘到数据上(在应用其他变换之前)
- preprocessing_function:将被应用于每个输入的函数。该函数将在任何其他修改之前运行。该函数接受一个参数,为一张图片(秩为3的numpy array),并且输出一个具有相同shape的numpy array
- data_format:字符串,“channel_first”或“channel_last”之一,代表图像的通道维的位置。该参数是Keras 1.x中的image_dim_ordering,“channel_last”对应原本的“tf”,“channel_first”对应原本的“th”。以128x128的RGB图像为例,“channel_first”应将数据组织为(3,128,128),而“channel_last”应将数据组织为(128,128,3)。该参数的默认值是
~/.keras/keras.json
中设置的值,若从未设置过,则为“channel_last”
方法
- fit(x, augment=False, rounds=1):计算依赖于数据的变换所需要的统计信息(均值方差等),只有使用
featurewise_center
,featurewise_std_normalization
或zca_whitening
时需要此函数。
X:numpy array,样本数据,秩应为4.在黑白图像的情况下channel轴的值为1,在彩色图像情况下值为3
augment:布尔值,确定是否使用随即提升过的数据
round:若设
augment=True
,确定要在数据上进行多少轮数据提升,默认值为1seed: 整数,随机数种子
- flow(self, X, y, batch_size=32, shuffle=True, seed=None, save_to_dir=None, save_prefix='', save_format='png'):接收numpy数组和标签为参数,生成经过数据提升或标准化后的batch数据,并在一个无限循环中不断的返回batch数据
x:样本数据,秩应为4.在黑白图像的情况下channel轴的值为1,在彩色图像情况下值为3
y:标签
batch_size:整数,默认32
shuffle:布尔值,是否随机打乱数据,默认为True
save_to_dir:None或字符串,该参数能让你将提升后的图片保存起来,用以可视化
save_prefix:字符串,保存提升后图片时使用的前缀, 仅当设置了
save_to_dir
时生效save_format:"png"或"jpeg"之一,指定保存图片的数据格式,默认"jpeg"
yields:形如(x,y)的tuple,x是代表图像数据的numpy数组.y是代表标签的numpy数组.该迭代器无限循环.
seed: 整数,随机数种子
- flow_from_directory(directory): 以文件夹路径为参数,生成经过数据提升/归一化后的数据,在一个无限循环中无限产生batch数据
- directory: 目标文件夹路径,对于每一个类,该文件夹都要包含一个子文件夹.子文件夹中任何JPG、PNG、BNP、PPM的图片都会被生成器使用.详情请查看此脚本
- target_size: 整数tuple,默认为(256, 256). 图像将被resize成该尺寸
- color_mode: 颜色模式,为"grayscale","rgb"之一,默认为"rgb".代表这些图片是否会被转换为单通道或三通道的图片.
- classes: 可选参数,为子文件夹的列表,如['dogs','cats']默认为None. 若未提供,则该类别列表将从
directory
下的子文件夹名称/结构自动推断。每一个子文件夹都会被认为是一个新的类。(类别的顺序将按照字母表顺序映射到标签值)。通过属性class_indices
可获得文件夹名与类的序号的对应字典。 - class_mode: "categorical", "binary", "sparse"或None之一. 默认为"categorical. 该参数决定了返回的标签数组的形式, "categorical"会返回2D的one-hot编码标签,"binary"返回1D的二值标签."sparse"返回1D的整数标签,如果为None则不返回任何标签, 生成器将仅仅生成batch数据, 这种情况在使用
model.predict_generator()
和model.evaluate_generator()
等函数时会用到. - batch_size: batch数据的大小,默认32
- shuffle: 是否打乱数据,默认为True
- seed: 可选参数,打乱数据和进行变换时的随机数种子
- save_to_dir: None或字符串,该参数能让你将提升后的图片保存起来,用以可视化
- save_prefix:字符串,保存提升后图片时使用的前缀, 仅当设置了
save_to_dir
时生效 - save_format:"png"或"jpeg"之一,指定保存图片的数据格式,默认"jpeg"
- flollow_links: 是否访问子文件夹中的软链接
例子
使用.flow()
的例子
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes) datagen = ImageDataGenerator(
featurewise_center=True,
featurewise_std_normalization=True,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True) # compute quantities required for featurewise normalization
# (std, mean, and principal components if ZCA whitening is applied)
datagen.fit(x_train) # fits the model on batches with real-time data augmentation:
model.fit_generator(datagen.flow(x_train, y_train, batch_size=32),
steps_per_epoch=len(x_train), epochs=epochs) # here's a more "manual" example
for e in range(epochs):
print 'Epoch', e
batches = 0
for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32):
loss = model.train(x_batch, y_batch)
batches += 1
if batches >= len(x_train) / 32:
# we need to break the loop by hand because
# the generator loops indefinitely
break
使用.flow_from_directory(directory)
的例子
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory(
'data/train',
target_size=(150, 150),
batch_size=32,
class_mode='binary') validation_generator = test_datagen.flow_from_directory(
'data/validation',
target_size=(150, 150),
batch_size=32,
class_mode='binary') model.fit_generator(
train_generator,
steps_per_epoch=2000,
epochs=50,
validation_data=validation_generator,
validation_steps=800) 同时变换图像和mask # we create two instances with the same arguments
data_gen_args = dict(featurewise_center=True,
featurewise_std_normalization=True,
rotation_range=90.,
width_shift_range=0.1,
height_shift_range=0.1,
zoom_range=0.2)
image_datagen = ImageDataGenerator(**data_gen_args)
mask_datagen = ImageDataGenerator(**data_gen_args) # Provide the same seed and keyword arguments to the fit and flow methods
seed = 1
image_datagen.fit(images, augment=True, seed=seed)
mask_datagen.fit(masks, augment=True, seed=seed) image_generator = image_datagen.flow_from_directory(
'data/images',
class_mode=None,
seed=seed) mask_generator = mask_datagen.flow_from_directory(
'data/masks',
class_mode=None,
seed=seed) # combine generators into one which yields image and masks
train_generator = zip(image_generator, mask_generator) model.fit_generator(
train_generator,
steps_per_epoch=2000,
epochs=50)
Keras-图片预处理的更多相关文章
- python的N个小功能(图片预处理:打开图片,滤波器,增强,灰度图转换,去噪,二值化,切割,保存)
############################################################################################# ###### ...
- caffe Python API 之图片预处理
# 设定图片的shape格式为网络data层格式 transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) ...
- 深度学习原理与框架-神经网络架构 1.神经网络构架 2.激活函数(sigmoid和relu) 3.图片预处理(减去均值和除标准差) 4.dropout(防止过拟合操作)
神经网络构架:主要时表示神经网络的组成,即中间隐藏层的结构 对图片进行说明:我们可以看出图中的层数分布: input layer表示输入层,维度(N_num, input_dim) N_num表示输 ...
- Keras文本预处理
学习了Keras文档里的文本预处理部分,参考网上代码写了个例子 import keras.preprocessing.text as T from keras.preprocessing.text i ...
- [PyTorch 学习笔记] 2.2 图片预处理 transforms 模块机制
PyTorch 的数据增强 我们在安装PyTorch时,还安装了torchvision,这是一个计算机视觉工具包.有 3 个主要的模块: torchvision.transforms: 里面包括常用的 ...
- 『TensorFlow』生成式网络中的图片预处理
简介 这里的生成式网络是广义的生成式,不仅仅指gan网络,还有风格迁移中的类自编码器网络,以及语义分割中的类自编码器网络,因为遇到次数比较多,所以简单的记录一下. 背景 1.像素和数字 图像处理目标一 ...
- keras图像预处理-ImageDataGenerator
相关参数描述:http://keras-cn.readthedocs.io/en/latest/preprocessing/image/其中validation_split参数(官方上使用方法未描述) ...
- 吴裕雄 python 神经网络——TensorFlow图片预处理
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 使用'r'会出错,无法解码,只能以2进制形式读 ...
- 吴裕雄 python 神经网络——TensorFlow图片预处理调整图片
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def distort_color(image, ...
- keras图片数据增强ImageDataGenerator
datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shea ...
随机推荐
- 将android程序中的数据库导出到SD卡
private void copyDBToSDcrad() { String DATABASE_NAME = "数据库文件名"; String oldPath = "da ...
- SQL Server 删除数据库所有表和所有存储过程
场景: SQL Server中,需要删除所有表或所有存储过程时,手动的方式只能逐个进行删除,耗个人时间,所以想弄个语句来实现这样的需求. 如果由于外键约束删除table失败,则先删除所有约束: - ...
- 【Mysql】修改最大连接数
http://www.111cn.net/database/mysql/51934.htm
- linux环境下,清空history中记录的历史命令
需求描述: 今天在数据库主机上操作,通过history看到有刚操作过的历史记录,想把这个清除了, 但是,还不影响后续的命令记录,所以查了下,在此记录. 操作过程: 1.通过history -c命令,完 ...
- Java精选笔记_集合【List(列表)接口】
List(列表)接口 简介 List接口继承自Collection接口,是单列集合的一个重要分支,习惯性地会将实现了List接口的对象称为List集合. 元素是有序的,即元素的存入顺序和取出顺序一致, ...
- Spring装配Bean的过程
首先说一个概念:“懒加载” 懒加载:就是我们在spring容器启动的是先不把所有的bean都加载到spring的容器中去,而是在当需要用的时候,才把这个对象实例化到容器中. spring配置文件中be ...
- mount: block device /dev/cdrom is write-protected, mounting read-only 解决方法
[root@localhost ~]# mount /dev/cdrom /mnt/cdrom/ mount: block device /dev/sr0 is write-protected, mo ...
- js jquery获取当前元素的兄弟级 上一个 下一个元素 jquery如何获取第一个或最后一个子元素
var chils= s.childNodes; //得到s的全部子节点 var par=s.parentNode; //得到s的父节点 var ns=s.nextSbiling; //获得 ...
- 《转》python学习(7) -列表
转自 http://www.cnblogs.com/BeginMan/p/3153842.html 一.序列类型操作符 1.切片[]和[:] 2.成员关系操作符(in ,not in ) 1: s1 ...
- JavaBean与Map<String,Object>相互转换
一.为什么要实现javaBean与Map<String,Object>相互转换 Spring中的BaseCommandController对象可以将传递过来的参数封装到一个JavaBean ...