tensorflow圖像裁剪進行數(shù)據(jù)增強操作
我就廢話不多說了,大家還是直接看代碼吧~
#!/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']
# 創(chuàng)建文件讀取隊列
filename_queue = tf.train.string_input_producer(filenames)
# 一個閱讀器,讀取整個文件,返回文件名稱key,以及文件中所有的內(nèi)容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的使用,用于多線程的協(xié)調(diào)
coord = tf.train.Coordinator()
# 啟動所有g(shù)raph收集到的隊列運行器(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)) # <class 'tensorflow.python.framework.ops.Tensor'>
reimg1 = reshapeimg.eval() # reimg1的類型是<class 'numpy.ndarray'>
scipy.misc.imsave('./crop.jpg', reimg1)
plt.imshow(reimg1)
plt.axis("off")
plt.show()
# 請求線程結(jié)束
coord.request_stop()
# 等待線程終止
coord.join(threads)
原始圖像480x320x3:

裁剪后224x224x3:

補充知識:Tensorflow 圖像增強(ImageDataGenerator)
當我們訓練一個較為復雜的網(wǎng)絡(luò),并且我們的訓練數(shù)據(jù)集有限時,網(wǎng)絡(luò)十分容易陷入過擬合的狀態(tài)。
解決這個問題的一個可能的有效方法是:進行數(shù)據(jù)增強,即通過已有的有限的數(shù)據(jù)集,通過圖像處理等方法(旋轉(zhuǎn),剪切,縮放…),獲得更多的,類似的,多樣化的數(shù)據(jù)。
數(shù)據(jù)增強處理,不會占用更多的存儲空間,即在數(shù)據(jù)增強過程中,原始的數(shù)據(jù)不會被修改,所有的處理過程都是在內(nèi)存中 即時(on-the-fly) 的處理。
注意:
數(shù)據(jù)增強不一定是萬能藥(雖然數(shù)據(jù)多了),數(shù)據(jù)增強提高了原始數(shù)據(jù)的隨機性,但是若 測試集或應(yīng)用場景 并不具有這樣的隨機性,那么它將不會起到作用,還會增加訓練所需的時間。
使用方法:
train_datagen = ImageDataGenerator(
rescale=1./255, #數(shù)據(jù)值除以255,[0-255] ->[0,1]
shear_range=0.2, #剪切強度(逆時針方向的剪切角度,以度為單位)
zoom_range=0.2, #隨機縮放范圍
horizontal_flip=True) #水平翻轉(zhuǎn)
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圖像裁剪進行數(shù)據(jù)增強操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
淺談sklearn中predict與predict_proba區(qū)別
這篇文章主要介紹了淺談sklearn中predict與predict_proba區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

