首页 > python教程

使用TensorFlow对图像进行随机旋转的实现示例

时间:2020-10-30 python教程 查看: 741

在使用深度学习对图像进行训练时,对图像进行随机旋转有助于提升模型泛化能力。然而之前在做旋转等预处理工作时,都是先对图像进行旋转后保存到本地,然后再输入模型进行训练,这样的过程会增加工作量,如果图片数量较多,生成旋转的图像会占用更多的空间。直接在训练过程中便对图像进行随机旋转,可有效提升工作效率节省硬盘空间。

使用TensorFlow对图像进行随机旋转如下:

TensorFlow版本为1.13.1

#-*- coding:utf-8 -*-
'''
  使用TensorFlow进行图像的随机旋转示例
'''

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对图像进行随机旋转
  :param input_image: 图像输入
  :param min_angle: 最小旋转角度
  :param max_angle: 最大旋转角度
  :return: 旋转后的图像
  '''
  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()

结果如下:

原图:

随机旋转后的图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

展开全文
上一篇:TensorFLow 不同大小图片的TFrecords存取实例
下一篇:如何通过Django使用本地css/js文件
输入字:
相关知识
Python 实现图片色彩转换案例

我们在看动漫、影视作品中,当人物在回忆过程中,体现出来的画面一般都是黑白或者褐色的。本文将提供将图片色彩转为黑白或者褐色风格的案例详解,感兴趣的小伙伴可以了解一下。

python初学定义函数

这篇文章主要为大家介绍了python的定义函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助,希望能够给你带来帮助

图文详解Python如何导入自己编写的py文件

有时候自己写了一个py文件,想要把它导入到另一个py文件里面,所以下面这篇文章主要给大家介绍了关于Python如何导入自己编写的py文件的相关资料,需要的朋友可以参考下

python二分法查找实例代码

二分算法是一种效率比较高的查找算法,其输入的是一个有序的元素列表,如果查找元素包含在列表中,二分查找返回其位置,否则返回NONE,下面这篇文章主要给大家介绍了关于python二分法查找的相关资料,需要的朋友可以参考下