欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Keras 數(shù)據(jù)增強ImageDataGenerator多輸入多輸出實例

 更新時間:2020年07月03日 14:14:04   作者:青盞  
這篇文章主要介紹了Keras 數(shù)據(jù)增強ImageDataGenerator多輸入多輸出實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

我就廢話不多說了,大家還是直接看代碼吧~

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,   #旋轉(zhuǎn)
  width_shift_range=0.1,  #水平位置平移
#   height_shift_range=0.2,  #上下位置平移
  shear_range=0.5,    #錯切變換,讓所有點的x坐標(biāo)(或者y坐標(biāo))保持不變,而對應(yīng)的y坐標(biāo)(或者x坐標(biāo))則按比例發(fā)生平移
  zoom_range=[0.9,0.9],  # 單方向縮放,當(dāng)一個數(shù)值時兩個方向等比例縮放,參數(shù)為list時長寬不同程度縮放。參數(shù)大于0小于1時,執(zhí)行的是放大操作,當(dāng)參數(shù)大于1時,執(zhí)行的是縮小操作。
  channel_shift_range = 40, #偏移通道數(shù)值,改變圖片顏色,越大顏色越深
  horizontal_flip=True,  #水平翻轉(zhuǎn),垂直翻轉(zhuǎn)vertical_flip
  fill_mode='nearest',   #操作導(dǎo)致圖像缺失時填充方式?!癱onstant”、“nearest”(默認(rèn))、“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)

# #  加載數(shù)據(jù)和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
#多輸入,設(shè)置隨機種子
# 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]
#手動構(gòu)造,直接輸出多l(xiāng)abel
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數(shù)組,裁剪并保存 和 數(shù)據(jù)增強(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
# 生成圖片地址和對應(yīng)標(biāo)簽
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) # 目錄不存在則創(chuàng)建
 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之?dāng)?shù)據(jù)增強

from PIL import Image
import numpy as np
from PIL import Image
from keras.preprocessing import image
import os
import cv2
# 生成圖片地址和對應(yīng)標(biāo)簽
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
 # 設(shè)置生成器參數(shù)
 datagen = image.ImageDataGenerator(fill_mode='wrap', # 填充模式
          rotation_range=40, # 指定旋轉(zhuǎn)角度范圍
          width_shift_range=0.2, # 水平位置平移
          height_shift_range=0.2, # 上下位置平移
          horizontal_flip=True, # 隨機對圖片執(zhí)行水平翻轉(zhuǎn)操作
          vertical_flip=True, # 對圖片執(zhí)行上下翻轉(zhuǎn)操作
          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 數(shù)據(jù)增強ImageDataGenerator多輸入多輸出實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python數(shù)據(jù)分析之繪制m1-m2數(shù)據(jù)

    Python數(shù)據(jù)分析之繪制m1-m2數(shù)據(jù)

    這篇文章主要介紹了Python數(shù)據(jù)分析之繪制m1-m2數(shù)據(jù),文章基于python的相關(guān)資料展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-05-05
  • 利用Pandas實現(xiàn)對數(shù)據(jù)進行移動計算

    利用Pandas實現(xiàn)對數(shù)據(jù)進行移動計算

    這篇文章主要為大家詳細(xì)介紹了如何利用Pandas實現(xiàn)對數(shù)據(jù)進行移動計算,文中的示例代碼講解詳細(xì),對我們了解Pandas有一定幫助,需要的可以參考一下
    2022-07-07
  • python利用文件讀寫編寫一個博客

    python利用文件讀寫編寫一個博客

    這篇文章主要為大家詳細(xì)介紹了python利用文件讀寫編寫一個博客,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Python趣味挑戰(zhàn)之實現(xiàn)簡易版音樂播放器

    Python趣味挑戰(zhàn)之實現(xiàn)簡易版音樂播放器

    小伙伴們天天學(xué)編程應(yīng)該都學(xué)累了,今天特地給大家整理了這篇文章,讓大家在學(xué)習(xí)的時候也收貨快樂,文中有非常詳細(xì)的代碼示例,需要的朋友可以參考下
    2021-05-05
  • Python中url標(biāo)簽使用知識點總結(jié)

    Python中url標(biāo)簽使用知識點總結(jié)

    這篇文章主要介紹了Python中url標(biāo)簽使用知識點以及相關(guān)實例代碼,需要的朋友們參考下。
    2020-01-01
  • Pandas計算元素的數(shù)量和頻率的方法(出現(xiàn)的次數(shù))

    Pandas計算元素的數(shù)量和頻率的方法(出現(xiàn)的次數(shù))

    本文主要介紹了Pandas計算元素的數(shù)量和頻率的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • Python如何省略括號方法詳解

    Python如何省略括號方法詳解

    這篇文章主要介紹了Python如何省略括號方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-03-03
  • Python腳本化Git的操作詳解

    Python腳本化Git的操作詳解

    如何判定此次測試是否達(dá)標(biāo),代碼覆蓋率是衡量的標(biāo)準(zhǔn)之一,利用fastapi框架重寫了覆蓋率統(tǒng)計服務(wù),然后通過diff操作統(tǒng)計增量代碼覆蓋率,當(dāng)然要使用diff操作,避免不了與git打交道,那python如何操作gi t呢,本文將詳細(xì)介紹了Python腳本化Git的操作
    2024-03-03
  • centos6.5安裝python3.7.1之后無法使用pip的解決方案

    centos6.5安裝python3.7.1之后無法使用pip的解決方案

    今天小編就為大家分享一篇關(guān)于centos6.5安裝python3.7.1之后無法使用pip的解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • python繪制折線圖和條形圖的方法

    python繪制折線圖和條形圖的方法

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)折線圖和條形圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-04-04

最新評論