使用TensorFlow對(duì)圖像進(jìn)行隨機(jī)旋轉(zhuǎn)的實(shí)現(xiàn)示例
在使用深度學(xué)習(xí)對(duì)圖像進(jìn)行訓(xùn)練時(shí),對(duì)圖像進(jìn)行隨機(jī)旋轉(zhuǎn)有助于提升模型泛化能力。然而之前在做旋轉(zhuǎn)等預(yù)處理工作時(shí),都是先對(duì)圖像進(jìn)行旋轉(zhuǎn)后保存到本地,然后再輸入模型進(jìn)行訓(xùn)練,這樣的過(guò)程會(huì)增加工作量,如果圖片數(shù)量較多,生成旋轉(zhuǎn)的圖像會(huì)占用更多的空間。直接在訓(xùn)練過(guò)程中便對(duì)圖像進(jìn)行隨機(jī)旋轉(zhuǎn),可有效提升工作效率節(jié)省硬盤空間。
使用TensorFlow對(duì)圖像進(jìn)行隨機(jī)旋轉(zhuǎn)如下:
TensorFlow版本為1.13.1
#-*- coding:utf-8 -*-
'''
使用TensorFlow進(jìn)行圖像的隨機(jī)旋轉(zhuǎn)示例
'''
import tensorflow as tf
import numpy as np
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('tf.jpg')
img = cv2.resize(img,(220,220))
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
def tf_rotate(input_image, min_angle = -np.pi/2, max_angle = np.pi/2):
'''
TensorFlow對(duì)圖像進(jìn)行隨機(jī)旋轉(zhuǎn)
:param input_image: 圖像輸入
:param min_angle: 最小旋轉(zhuǎn)角度
:param max_angle: 最大旋轉(zhuǎn)角度
:return: 旋轉(zhuǎn)后的圖像
'''
distorted_image = tf.expand_dims(input_image, 0)
random_angles = tf.random.uniform(shape=(tf.shape(distorted_image)[0],), minval = min_angle , maxval = max_angle)
distorted_image = tf.contrib.image.transform(
distorted_image,
tf.contrib.image.angles_to_projective_transforms(
random_angles, tf.cast(tf.shape(distorted_image)[1], tf.float32), tf.cast(tf.shape(distorted_image)[2], tf.float32)
))
rotate_image = tf.squeeze(distorted_image, [0])
return rotate_image
global_init = tf.global_variables_initializer()
with tf.Session() as sess:
init = tf.initialize_local_variables()
sess.run([init, global_init])
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
image = tf.placeholder(shape=(220, 220, 3), dtype=tf.float32)
rotate_image = tf_rotate(image, -np.pi/2, np.pi/2)
output = sess.run(rotate_image, feed_dict={image:img})
# print('output:',output)
plt.imshow(output.astype('uint8'))
plt.title('rotate image')
plt.show()
結(jié)果如下:
原圖:

隨機(jī)旋轉(zhuǎn)后的圖:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python按綜合、銷量排序抓取100頁(yè)的淘寶商品列表信息
這篇文章主要為大家詳細(xì)介紹了python按綜合、銷量排序抓取100頁(yè)的淘寶商品列表信息,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
Python限制內(nèi)存和CPU使用量的方法(Unix系統(tǒng)適用)
這篇文章主要介紹了Python限制內(nèi)存和CPU的使用量的方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-08-08
tensorflow將圖片保存為tfrecord和tfrecord的讀取方式
今天小編就為大家分享一篇tensorflow將圖片保存為tfrecord和tfrecord的讀取方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
python實(shí)現(xiàn)輸出一個(gè)序列的所有子序列示例
今天小編就為大家分享一篇python實(shí)現(xiàn)輸出一個(gè)序列的所有子序列示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11

