keras 数据读取几种方式

33 篇文章 1 订阅
7 篇文章 0 订阅

keras数据读取(图像数据)的方式,可以不使用keras的方法而使用opencv或者pil直接读取做处理。这里主要总结了keras封装的几种图像数据读取方法,

一、keras.preprocessing.image.load_img()读取单张图像

1)load_img()指定图像路径读取图像,看源码可知就是对pil的简单封装,使用PIL.mage.open()读取

def load_img(path, grayscale=False, target_size=None,
             interpolation='nearest'):
    """Loads an image into PIL format.

    # Arguments
        path: Path to image file
        grayscale: Boolean, whether to load the image as grayscale.
        target_size: Either `None` (default to original size)
            or tuple of ints `(img_height, img_width)`.
        interpolation: Interpolation method used to resample the image if the
            target size is different from that of the loaded image.
            Supported methods are "nearest", "bilinear", and "bicubic".
            If PIL version 1.1.3 or newer is installed, "lanczos" is also
            supported. If PIL version 3.4.0 or newer is installed, "box" and
            "hamming" are also supported. By default, "nearest" is used.

    # Returns
        A PIL Image instance.

    # Raises
        ImportError: if PIL is not available.
        ValueError: if interpolation method is not supported.
    """

2)img_to_array()和array_to_img()

load_img()读取后的图像是PIL Image的实例,并不是Numpy数据,这两种方法实现了两种格式的相互转换。

使用load_img()的示例:

# 加载图像
img = image.load_img(image_path, target_size=(224, 224))
x = image.img_to_array(img)
'''
# 读取完图像是三维向量,而模型输入要求四维
# nums*weight*height*depth,输入模型前要扩展维度
'''
x = np.expand_dims(x, axis=0)  
'''                              
# 图像预处理
#视自己情形是否需要图像预处理(如均值归一化处理等)
'''
x = preprocess_input(x)       

二、keras.preprocessing.image.ImageDataGenerator()

keras.preprocessing.image.ImageDataGenerator()是一个类,可进行实时数据增强,生成一个batch的数据。该类的具体参数可参见官方中文文档。具体参数的使用结果示例可参见博客

 def __init__(self,
                 featurewise_center=False,#使数据集去中心化,使均值为0。统计整个数据集的均值
                 samplewise_center=False, #使每个样本去中心化,只统计当前样本的均值
                 featurewise_std_normalization=False,#除以数据集的标准差完成标准化,统计整个数 
                                                     #据集的标准差
                 samplewise_std_normalization=False, #除以当前样本的标准差完成标准化,统计当前 
                                                     #样本的标准差
                 zca_whitening=False,      #对数据进行zca白化
                 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=None):

下面主要介绍几个该类常用的方法,假设该类的实例为

datagen = ImageDataGenerator(
    preprocessing_function=preprocess_input, #图像预处理函数
    rotation_range=30,                       #旋转角度范围
    width_shift_range=0.2,                   #
    height_shift_range=.2,                   #
    shear_range=.2,
    zoom_range=.2,
    horizontal_flip=True,
    rescale=1./255
)

1)datagen.fit(train_data)

如果featurewise_center=True,featurewise_std_normalization=True或zca_whitening=True。根据整个数据集的统计信息进行处理,就需要提供相应的统计信息。mean,std 和 principal components。

datagen.fit(train_data)正是用于计算train_data数据的均值,标准差等会更新self.mean,self.std,self.principal_compoments。

from keras.preprocessing.image import ImageDataGenerator
from keras.datasets import mnist
from keras.datasets import cifar10
from keras.utils import np_utils
import numpy as np
import matplotlib.pyplot as plt
num_classes = 10
seed = 1
# featurewise需要数据集的统计信息,因此需要先读入一个x_train,用于对增强图像的均值和方差处理。
x_train = np.load('images-224.npy')
imagegen = ImageDataGenerator(
    featurewise_center=True,
    featurewise_std_normalization=True,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)

maskgen = ImageDataGenerator(
     rescale = 1./255,
     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)
imagegen.fit(x_train)
image_iter = imagegen.flow_from_directory('../data/images',target_size=(224,224), class_mode=None, batch_size=8, seed=seed)
mask_iter = maskgen.flow_from_directory('../data/masks', color_mode='rgb', target_size=(224,224), class_mode=None, batch_size=8, seed=seed)

    

2)flow() 、flow_from_diretory()、flow_from_dataframe()

定义不同形式的数据读取方式。这三种方式都会返回一个迭代器。每次生成一个batch的数据(而并非将全部数据一次读进内存),并可以进行实时的数据增强(每次生成一个batch的数据并进行随机处理)。不同之处仅仅是数据来源的格式不同而已

flow:numpy数组

flow_from_directory:从文件夹中读取图像。制定的路径应该包含对应类别的子文件夹

flow_from_dataframe:输入dataframe和目录的路径

 

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值