代码之家  ›  专栏  ›  技术社区  ›  I. A Ziang Yan

如何在tensorflow中随机旋转不同角度的图像

  •  3
  • I. A Ziang Yan  · 技术社区  · 6 年前

    我知道我可以用tensorflow旋转图像 tf.contrib.image.rotate . 但假设我想以-0.3到0.3弧度的角度随机应用旋转,如下所示:

    images = tf.contrib.image.rotate(images, tf.random_uniform(shape=[batch_size], minval=-0.3, maxval=0.3, seed=mseed), interpolation='BILINEAR')
    

    到目前为止,这样做还不错。但当上一次迭代的批大小发生变化时,出现了一个错误。那么,如何修复这些代码并使其在所有情况下都能正常工作呢?请注意,输入图像是使用 tf.data.Dataset 应用程序编程接口。

    非常感谢您的帮助!!

    1 回复  |  直到 6 年前
        1
  •  2
  •   xvan    6 年前

    你不能吃东西 tf.contrib.image.rotate 用角张量。

    但是如果你检查 source code 你可以看到它只是做了一堆参数验证,然后:

    image_height = math_ops.cast(array_ops.shape(images)[1],
                                 dtypes.float32)[None]
    image_width = math_ops.cast(array_ops.shape(images)[2],
                                dtypes.float32)[None]
    output = transform(
        images,
        angles_to_projective_transforms(angles, image_height, image_width),
                                        interpolation=interpolation)
    

    tf.contrib.image.transform() 接收投影变换矩阵。 tf.contrib.image.angles_to_projective_transforms() 从旋转角度生成投影变换。

    两者都接受张量作为参数,因此您可以只调用底层函数。


    下面是一个使用mnist的示例

    import tensorflow as tf
    import numpy as np
    import matplotlib.pyplot as plt
    
    # load mnist
    from tensorflow.examples.tutorials.mnist
    import input_data
    mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
    
    # Tensorflow random angle rotation
    input_size = mnist.train.images.shape[1]
    side_size = int(np.sqrt(input_size))
    
    dataset = tf.placeholder(tf.float32, [None, input_size])
    images = tf.reshape(dataset, (-1, side_size, side_size, 1))
    random_angles = tf.random.uniform(shape = (tf.shape(images)[0], ), minval = -np
        .pi / 4, maxval = np.pi / 4)
    
    rotated_images = tf.contrib.image.transform(
        images,
        tf.contrib.image.angles_to_projective_transforms(
            random_angles, tf.cast(tf.shape(images)[1], tf.float32), tf.cast(tf
                .shape(images)[2], tf.float32)
        ))
    
    # Run and Print
    sess = tf.Session()
    result = sess.run(rotated_images, feed_dict = {
        dataset: mnist.train.images,
    })
    
    original = np.reshape(mnist.train.images * 255, (-1, side_size, side_size)).astype(
        np.uint8)
    rotated = np.reshape(result * 255, (-1, side_size, side_size)).astype(np.uint8)
    
    
    # Print 10 random samples
    fig, axes = plt.subplots(2, 10, figsize = (15, 4.5))
    choice = np.random.choice(range(len(mnist.test.labels)), 10)
    for k in range(10):
        axes[0][k].set_axis_off()
    axes[0][k].imshow(original[choice[k, ]], interpolation = 'nearest', \
        cmap = 'gray')
    axes[1][k].set_axis_off()
    axes[1][k].imshow(rotated[choice[k, ]], interpolation = 'nearest', \
        cmap = 'gray')
    

    enter image description here