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

﹏ヽ暗。殇╰゛Y 2021-06-24 15:58 759阅读 0赞
  1. import os
  2. os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
  3. os.environ["CUDA_VISIBLE_DEVICES"]=""
  4. import sys
  5. import gc
  6. import time
  7. import cv2
  8. import random
  9. import numpy as np
  10. import pandas as pd
  11. import seaborn as sns
  12. import matplotlib.pyplot as plt
  13. from tqdm import tqdm
  14. from random_eraser import get_random_eraser
  15. from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
  16. datagen = ImageDataGenerator(
  17. rotation_range=20, #旋转
  18. width_shift_range=0.1, #水平位置平移
  19. # height_shift_range=0.2, #上下位置平移
  20. shear_range=0.5, #错切变换,让所有点的x坐标(或者y坐标)保持不变,而对应的y坐标(或者x坐标)则按比例发生平移
  21. zoom_range=[0.9,0.9], # 单方向缩放,当一个数值时两个方向等比例缩放,参数为list时长宽不同程度缩放。参数大于0小于1时,执行的是放大操作,当参数大于1时,执行的是缩小操作。
  22. channel_shift_range = 40, #偏移通道数值,改变图片颜色,越大颜色越深
  23. horizontal_flip=True, #水平翻转,垂直翻转vertical_flip
  24. fill_mode='nearest', #操作导致图像缺失时填充方式。“constant”、“nearest”(默认)、“reflect”和“wrap”
  25. 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)
  26. )
  27. # train_generator = datagen.flow_from_directory(
  28. # 'base/Images/',
  29. # save_to_dir = 'base/fake/',
  30. # batch_size=1
  31. # )
  32. # for i in range(5):
  33. # train_generator.next()
  34. # !
  35. # df_train = pd.read_csv('base/Annotations/label.csv', header=None)
  36. # df_train.columns = ['image_id', 'class', 'label']
  37. # classes = ['collar_design_labels', 'neckline_design_labels', 'skirt_length_labels',
  38. # 'sleeve_length_labels', 'neck_design_labels', 'coat_length_labels', 'lapel_design_labels',
  39. # 'pant_length_labels']
  40. # !
  41. # classes = ['collar_design_labels']
  42. # !
  43. # for i in range(len(classes)):
  44. # gc.enable()
  45. # # 单个分类
  46. # cur_class = classes[i]
  47. # df_load = df_train[(df_train['class'] == cur_class)].copy()
  48. # df_load.reset_index(inplace=True)
  49. # del df_load['index']
  50. # # print(cur_class)
  51. # # 加载数据和label
  52. # n = len(df_load)
  53. # # n_class = len(df_load['label'][0])
  54. # # width = 256
  55. # # X = np.zeros((n,width, width, 3), dtype=np.uint8)
  56. # # y = np.zeros((n, n_class), dtype=np.uint8)
  57. # print(f'starting load trainset {cur_class} {n}')
  58. # sys.stdout.flush()
  59. # for i in tqdm(range(n)):
  60. # # tmp_label = df_load['label'][i]
  61. # img = load_img('base/{0}'.format(df_load['image_id'][i]))
  62. # x = img_to_array(img)
  63. # x = x.reshape((1,) + x.shape)
  64. # m=0
  65. # for batch in datagen.flow(x,batch_size=1):
  66. # # plt.imshow(array_to_img(batch[0]))
  67. # # print(batch)
  68. # array_to_img(batch[0]).save(f'base/fake/{format(df_load["image_id"][i])}-{m}.jpg')
  69. # m+=1
  70. # if m>3:
  71. # break
  72. # gc.collect()
  73. # !
  74. img = load_img('base/Images/collar_design_labels/2f639f11de22076ead5fe1258eae024d.jpg')
  75. plt.figure()
  76. plt.imshow(img)
  77. x = img_to_array(img)
  78. x = x.reshape((1,) + x.shape)
  79. i = 0
  80. for batch in datagen.flow(x,batch_size=5):
  81. plt.figure()
  82. plt.imshow(array_to_img(batch[0]))
  83. # print(len(batch))
  84. i += 1
  85. if i >0:
  86. break
  87. #多输入,设置随机种子
  88. # Define the image transformations here
  89. gen = ImageDataGenerator(horizontal_flip = True,
  90. vertical_flip = True,
  91. width_shift_range = 0.1,
  92. height_shift_range = 0.1,
  93. zoom_range = 0.1,
  94. rotation_range = 40)
  95. # Here is the function that merges our two generators
  96. # We use the exact same generator with the same random seed for both the y and angle arrays
  97. def gen_flow_for_two_inputs(X1, X2, y):
  98. genX1 = gen.flow(X1,y, batch_size=batch_size,seed=666)
  99. genX2 = gen.flow(X1,X2, batch_size=batch_size,seed=666)
  100. while True:
  101. X1i = genX1.next()
  102. X2i = genX2.next()
  103. #Assert arrays are equal - this was for peace of mind, but slows down training
  104. #np.testing.assert_array_equal(X1i[0],X2i[0])
  105. yield [X1i[0], X2i[1]], X1i[1]
  106. #手动构造,直接输出多label
  107. generator = ImageDataGenerator(rotation_range=5.,
  108. width_shift_range=0.1,
  109. height_shift_range=0.1,
  110. horizontal_flip=True,
  111. vertical_flip=True)
  112. def generate_data_generator(generator, X, Y1, Y2):
  113. genX = generator.flow(X, seed=7)
  114. genY1 = generator.flow(Y1, seed=7)
  115. while True:
  116. Xi = genX.next()
  117. Yi1 = genY1.next()
  118. Yi2 = function(Y2)
  119. yield Xi, [Yi1, Yi2]
  120. model.fit_generator(generate_data_generator(generator, X, Y1, Y2),
  121. epochs=epochs)
  122. def batch_generator(generator,X,Y):
  123. Xgen = generator.flow(X)
  124. while True:
  125. yield Xgen.next(),Y
  126. h = model.fit_generator(batch_generator(datagen, X_all, y_all),
  127. steps_per_epoch=len(X_all)//32+1,
  128. epochs=80,workers=3,
  129. callbacks=[EarlyStopping(patience=3), checkpointer,ReduceLROnPlateau(monitor='val_loss',factor=0.5,patience=1)],
  130. validation_data=(X_val,y_val))

发表评论

表情:
评论列表 (有 0 条评论,759人围观)

还没有评论,来说两句吧...

相关阅读