Keras 数据增强ImageDataGenerator多输入多输出实例


Posted in Python onJuly 03, 2020

我就废话不多说了,大家还是直接看代码吧~

import os 
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" 
os.environ["CUDA_VISIBLE_DEVICES"]=""
import sys
import gc
import time
import cv2
import random
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm import tqdm

from random_eraser import get_random_eraser
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

datagen = ImageDataGenerator(
  rotation_range=20,   #旋转
  width_shift_range=0.1,  #水平位置平移
#   height_shift_range=0.2,  #上下位置平移
  shear_range=0.5,    #错切变换,让所有点的x坐标(或者y坐标)保持不变,而对应的y坐标(或者x坐标)则按比例发生平移
  zoom_range=[0.9,0.9],  # 单方向缩放,当一个数值时两个方向等比例缩放,参数为list时长宽不同程度缩放。参数大于0小于1时,执行的是放大操作,当参数大于1时,执行的是缩小操作。
  channel_shift_range = 40, #偏移通道数值,改变图片颜色,越大颜色越深
  horizontal_flip=True,  #水平翻转,垂直翻转vertical_flip
  fill_mode='nearest',   #操作导致图像缺失时填充方式。“constant”、“nearest”(默认)、“reflect”和“wrap”
  preprocessing_function = get_random_eraser(p=0.7,v_l=0,v_h=255,s_l=0.01,s_h=0.03,r_1=1,r_2=1.5,pixel_level=True)
  )

# train_generator = datagen.flow_from_directory(
#       'base/Images/',
#       save_to_dir = 'base/fake/',
#       batch_size=1
#       )
# for i in range(5):
#  train_generator.next()

# !
# df_train = pd.read_csv('base/Annotations/label.csv', header=None)
# df_train.columns = ['image_id', 'class', 'label']
# classes = ['collar_design_labels', 'neckline_design_labels', 'skirt_length_labels', 
#   'sleeve_length_labels', 'neck_design_labels', 'coat_length_labels', 'lapel_design_labels', 
#   'pant_length_labels']
# !

# classes = ['collar_design_labels']

# !
# for i in range(len(classes)):
#  gc.enable()

# #  单个分类
#  cur_class = classes[i]
#  df_load = df_train[(df_train['class'] == cur_class)].copy()
#  df_load.reset_index(inplace=True)
#  del df_load['index']

# #  print(cur_class)

# #  加载数据和label
#  n = len(df_load)
# #  n_class = len(df_load['label'][0])
# #  width = 256

# #  X = np.zeros((n,width, width, 3), dtype=np.uint8)
# #  y = np.zeros((n, n_class), dtype=np.uint8)

#  print(f'starting load trainset {cur_class} {n}')
#  sys.stdout.flush()
#  for i in tqdm(range(n)):
# #   tmp_label = df_load['label'][i]
#   img = load_img('base/{0}'.format(df_load['image_id'][i]))
#   x = img_to_array(img)
#   x = x.reshape((1,) + x.shape)
#   m=0
#   for batch in datagen.flow(x,batch_size=1):
# #    plt.imshow(array_to_img(batch[0]))
# #    print(batch)
#    array_to_img(batch[0]).save(f'base/fake/{format(df_load["image_id"][i])}-{m}.jpg')
#    m+=1
#    if m>3:
#     break
#  gc.collect()
# !  

img = load_img('base/Images/collar_design_labels/2f639f11de22076ead5fe1258eae024d.jpg')
plt.figure()
plt.imshow(img)
x = img_to_array(img)

x = x.reshape((1,) + x.shape)

i = 0
for batch in datagen.flow(x,batch_size=5):
 plt.figure()
 plt.imshow(array_to_img(batch[0]))
#  print(len(batch))
 i += 1
 if i >0:
  break
#多输入,设置随机种子
# Define the image transformations here
gen = ImageDataGenerator(horizontal_flip = True,
       vertical_flip = True,
       width_shift_range = 0.1,
       height_shift_range = 0.1,
       zoom_range = 0.1,
       rotation_range = 40)

# Here is the function that merges our two generators
# We use the exact same generator with the same random seed for both the y and angle arrays
def gen_flow_for_two_inputs(X1, X2, y):
 genX1 = gen.flow(X1,y, batch_size=batch_size,seed=666)
 genX2 = gen.flow(X1,X2, batch_size=batch_size,seed=666)
 while True:
   X1i = genX1.next()
   X2i = genX2.next()
   #Assert arrays are equal - this was for peace of mind, but slows down training
   #np.testing.assert_array_equal(X1i[0],X2i[0])
   yield [X1i[0], X2i[1]], X1i[1]
#手动构造,直接输出多label
generator = ImageDataGenerator(rotation_range=5.,
        width_shift_range=0.1, 
        height_shift_range=0.1, 
        horizontal_flip=True, 
        vertical_flip=True)

def generate_data_generator(generator, X, Y1, Y2):
 genX = generator.flow(X, seed=7)
 genY1 = generator.flow(Y1, seed=7)
 while True:
   Xi = genX.next()
   Yi1 = genY1.next()
   Yi2 = function(Y2)
   yield Xi, [Yi1, Yi2]
model.fit_generator(generate_data_generator(generator, X, Y1, Y2),
    epochs=epochs)
def batch_generator(generator,X,Y):
 Xgen = generator.flow(X)
 while True:
  yield Xgen.next(),Y
h = model.fit_generator(batch_generator(datagen, X_all, y_all), 
       steps_per_epoch=len(X_all)//32+1,
       epochs=80,workers=3,
       callbacks=[EarlyStopping(patience=3), checkpointer,ReduceLROnPlateau(monitor='val_loss',factor=0.5,patience=1)], 
       validation_data=(X_val,y_val))

补充知识:读取图片成numpy数组,裁剪并保存 和 数据增强(ImageDataGenerator)

我就废话不多说了,大家还是直接看代码吧~

from PIL import Image
import numpy as np
from PIL import Image
from keras.preprocessing import image
import matplotlib.pyplot as plt
import os
import cv2
# from scipy.misc import toimage
import matplotlib
# 生成图片地址和对应标签
file_dir = '../train/'
image_list = []
label_list = []
cate = [file_dir + x for x in os.listdir(file_dir) if os.path.isdir(file_dir + x)]
for name in cate:
 temp = name.split('/')
 path = '../train_new/' + temp[-1]
 isExists = os.path.exists(path)
 if not isExists:
  os.makedirs(path) # 目录不存在则创建
 class_path = name + "/"

 for file in os.listdir(class_path):
  print(file)
  img_obj = Image.open(class_path + file) # 读取图片
  img_array = np.array(img_obj)
  resized = cv2.resize(img_array, (256, 256)) # 裁剪
  resized = resized.astype('float32')
  resized /= 255.
  # plt.imshow(resized)
  # plt.show()
  save_path = path + '/' + file
  matplotlib.image.imsave(save_path, resized) # 保存

keras之数据增强

from PIL import Image
import numpy as np
from PIL import Image
from keras.preprocessing import image
import os
import cv2
# 生成图片地址和对应标签
file_dir = '../train/'

label_list = []
cate = [file_dir + x for x in os.listdir(file_dir) if os.path.isdir(file_dir + x)]
for name in cate:
 image_list = []
 class_path = name + "/"
 for file in os.listdir(class_path):
  image_list.append(class_path + file)
 batch_size = 64
 if len(image_list) < 10000:
  num = int(10000 / len(image_list))
 else:
  num = 0
 # 设置生成器参数
 datagen = image.ImageDataGenerator(fill_mode='wrap', # 填充模式
          rotation_range=40, # 指定旋转角度范围
          width_shift_range=0.2, # 水平位置平移
          height_shift_range=0.2, # 上下位置平移
          horizontal_flip=True, # 随机对图片执行水平翻转操作
          vertical_flip=True, # 对图片执行上下翻转操作
          shear_range=0.2,
          rescale=1./255, # 缩放
          data_format='channels_last')
 if num > 0:
  temp = name.split('/')
  path = '../train_datage/' + temp[-1]
  isExists = os.path.exists(path)
  if not isExists:
   os.makedirs(path)

  for image_path in image_list:
   i = 1
   img_obj = Image.open(image_path) # 读取图片
   img_array = np.array(img_obj)
   x = img_array.reshape((1,) + img_array.shape)  #要求为4维
   name_image = image_path.split('/')
   print(name_image)
   for batch in datagen.flow(x,
        batch_size=1,
        save_to_dir=path,
        save_prefix=name_image[-1][:-4] + '_',
        save_format='jpg'):
    i += 1
    if i > num:
     break

以上这篇Keras 数据增强ImageDataGenerator多输入多输出实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python操作SQLite简明教程
Jul 10 Python
Python中暂存上传图片的方法
Feb 18 Python
Python配置文件解析模块ConfigParser使用实例
Apr 13 Python
图文讲解选择排序算法的原理及在Python中的实现
May 04 Python
python实现的多线程端口扫描功能示例
Jan 21 Python
python多线程同步之文件读写控制
Feb 25 Python
使用OpenCV实现仿射变换—平移功能
Aug 29 Python
Python 内置函数globals()和locals()对比详解
Dec 23 Python
Python使用qrcode二维码库生成二维码方法详解
Feb 17 Python
Django Xadmin多对多字段过滤实例
Apr 07 Python
一个非常简单好用的Python图形界面库(PysimpleGUI)
Dec 28 Python
python实现简单聊天功能
Jul 07 Python
keras和tensorflow使用fit_generator 批次训练操作
Jul 03 #Python
基于Python+QT的gui程序开发实现
Jul 03 #Python
keras 两种训练模型方式详解fit和fit_generator(节省内存)
Jul 03 #Python
一文弄懂Pytorch的DataLoader, DataSet, Sampler之间的关系
Jul 03 #Python
keras分类模型中的输入数据与标签的维度实例
Jul 03 #Python
keras自动编码器实现系列之卷积自动编码器操作
Jul 03 #Python
Python with语句用法原理详解
Jul 03 #Python
You might like
Fine Uploader文件上传组件应用介绍
2013/01/06 PHP
php实现三级级联下拉框
2016/04/17 PHP
Linux系统中为php添加pcntl扩展
2016/08/28 PHP
PHP实现Unicode编码相互转换的方法示例
2020/11/17 PHP
php实现微信支付之现金红包
2018/05/30 PHP
向左滚动文字 js代码效果
2013/08/17 Javascript
cookie的复制与使用记住用户名实现代码
2013/11/04 Javascript
基于jquery扩展漂亮的CheckBox(自己编写)
2013/11/19 Javascript
javascript等号运算符使用详解
2015/04/16 Javascript
jQuery+formdata实现上传进度特效遇到的问题
2016/02/24 Javascript
jQuery基于扩展简单实现倒计时功能的方法
2016/05/14 Javascript
jQuery实现图片向左向右切换效果的简单实例
2016/05/18 Javascript
JS中位置与大小的获取方法
2016/11/22 Javascript
jQuery返回定位插件详解
2017/05/15 jQuery
Node.js 使用递归实现遍历文件夹中所有文件
2017/09/18 Javascript
Angular中管道操作符(|)的使用方法
2017/12/15 Javascript
JavaScript 继承 封装 多态实现及原理详解
2019/07/29 Javascript
js实现点击按钮随机生成背景颜色
2020/09/05 Javascript
利用Python如何生成随机密码
2016/04/20 Python
python xml.etree.ElementTree遍历xml所有节点实例详解
2016/12/04 Python
Python处理菜单消息操作示例【基于win32ui模块】
2018/05/09 Python
对Python信号处理模块signal详解
2019/01/09 Python
Python网络爬虫之爬取微博热搜
2019/04/18 Python
使用tensorflow根据输入更改tensor shape
2020/06/23 Python
python+selenium爬取微博热搜存入Mysql的实现方法
2021/01/27 Python
SmartBuyGlasses丹麦:网上购买名牌太阳镜、眼镜和隐形眼镜
2016/10/01 全球购物
生产厂厂长岗位职责
2013/12/25 职场文书
党员党性分析材料
2014/02/17 职场文书
测试工程师程序员求职信范文
2014/02/20 职场文书
网络编辑岗位职责
2014/03/18 职场文书
乡镇干部个人对照检查材料思想汇报(原创篇)
2014/09/28 职场文书
优秀学生干部事迹材料
2014/12/24 职场文书
党员干部廉政承诺书
2015/04/28 职场文书
建党伟业的观后感
2015/06/01 职场文书
python自动化之如何利用allure生成测试报告
2021/05/02 Python
一文搞懂Golang 时间和日期相关函数
2021/12/06 Golang