Rotation of 90, 180 and 270 using python and tensorflow

Viewed 874

I want to randomly rotate my images in 90, 180, and 270 degrees, that is, by multiples of 90 degrees.

Currently, I am using the ImageDatagenerator to augment my data:

train_dataGen = ImageDataGenerator(rescale=None,horizontal_flip=True,rotation_range=90,
                                   vertical_flip=True)

If rotation_range variable is equal to 90, like the code above, does it only do rotations of 90 degrees? or does it perform rotations of multiples of 90?

2 Answers
def rotate_image(image):
    return np.rot90(image, np.random.choice([-1, 0, 1]))

train_dataGen = ImageDataGenerator(
    preprocessing_function=rotate_image)

This function will rotate by either -90, 0, or 90 degrees.

To apply these rotations to images, one can use the function apply_affine_transform() within keras preprocessing. This function is used by ImageDataGenerator to perform transforms.

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

x = np.arange(256).reshape(16, 16)
x = np.tile(x[..., np.newaxis], 3)
# x.shape == (16, 16, 3)
plt.imshow(x)

theta=0deg

x_90 = tf.keras.preprocessing.image.apply_affine_transform(x, theta=90)
plt.imshow(x_90)

theta=90deg

x_180 = tf.keras.preprocessing.image.apply_affine_transform(x, theta=180)
plt.imshow(x_180)

theta=180deg

x_270 = tf.keras.preprocessing.image.apply_affine_transform(x, theta=270)
plt.imshow(x_270)

theta=270deg


The rotation_range parameter of ImageDataGenerator specifies a range of possible rotations. A random is taken from the uniform distribution between -rotation_range and rotation_range. Here is the source.

if self.rotation_range:
    theta = np.random.uniform(
        -self.rotation_range,
        self.rotation_range)
else:
    theta = 0
Related