歡迎您光臨本站 註冊首頁

tensorflow圖像裁剪進行數據增強操作

←手機掃碼閱讀     月球人 @ 2020-07-01 , reply:0

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

  #!/usr/bin/env python  # encoding: utf-8  '''  @author: lele Ye  @contact: 1750112338@qq.com  @software: pycharm 2018.2  @file: 13mnist.py  @time: 2018/12/17 10:23  @desc:  '''  import tensorflow as tf  import scipy.misc  import matplotlib.pyplot as plt  import random     # 讀取圖像可任意大小  filenames = ['./tianchi.jpg']  # 創建文件讀取隊列  filename_queue = tf.train.string_input_producer(filenames)  # 一個閱讀器,讀取整個文件,返回文件名稱key,以及文件中所有的內容value  reader = tf.WholeFileReader()  # Returns the next record (key, value) pair produced by a reader  key, value = reader.read(filename_queue)  images = tf.image.decode_jpeg(value) # tf.image.decode_png(value)  target_width = target_height = 224     # 裁切圖片  with tf.Session() as sess:    # Coordinator的使用,用於多線程的協調    coord = tf.train.Coordinator()    # 啟動所有graph收集到的隊列運行器(queuerunners)    threads = tf.train.start_queue_runners(coord=coord)    height,width,channels = sess.run(tf.shape(images))    offset_height = random.randint(0,height-target_height)    offset_width = random.randint(0,width-target_width)    reshapeimg = tf.image.crop_to_bounding_box(images, offset_height=offset_height, offset_width=offset_width,                          target_height=target_height,target_width=target_width)    print(type(reshapeimg)) #reimg1 = reshapeimg.eval() # reimg1的類型是scipy.misc.imsave('./crop.jpg', reimg1)    plt.imshow(reimg1)    plt.axis("off")    plt.show()    # 請求線程結束    coord.request_stop()    # 等待線程終止    coord.join(threads)

 

原始圖像480x320x3:

裁剪後224x224x3:

補充知識:Tensorflow 圖像增強(ImageDataGenerator)

當我們訓練一個較為複雜的網絡,並且我們的訓練數據集有限時,網絡十分容易陷入過擬合的狀態。

解決這個問題的一個可能的有效方法是:進行數據增強,即通過已有的有限的數據集,通過圖像處理等方法(旋轉,剪切,縮放…),獲得更多的,類似的,多樣化的數據。

數據增強處理,不會佔用更多的存儲空間,即在數據增強過程中,原始的數據不會被修改,所有的處理過程都是在內存中 即時(on-the-fly) 的處理。

注意:

數據增強不一定是萬能藥(雖然數據多了),數據增強提高了原始數據的隨機性,但是若 測試集或應用場景 並不具有這樣的隨機性,那麼它將不會起到作用,還會增加訓練所需的時間。

使用方法:

  train_datagen = ImageDataGenerator(      rescale=1./255, #數據值除以255,[0-255] ->[0,1]      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)


[月球人 ] tensorflow圖像裁剪進行數據增強操作已經有291次圍觀

http://coctec.com/docs/program/show-post-240535.html