4 Painless Strategies to Rotate an Image in Python

Introduction

In python, we have discussed many concepts and conversions. But sometimes, we come to a situation where we need to rotate an image with a particular angle. In this tutorial, we will be discussing 4 different ways to rotate an image with a particular angle, i.e., using python image library and using open-CV to rotate an image by an angle in Python. The rotation of an image is a geometric transformation. It can be done either by the Forward Transformation (or) Inverse Transformation.

Method 1: Using Python Image Library(PIL)

Python Image Library(PIL) is a module that contains in-built functions in python to manipulate and work with images as an input to the functions. The function uses an Inverse transformation. If the Number Of Degrees that we have Specified for Image Rotation is not an Integer Multiple of 90 Degrees, then some Pixel Values Beyond Image Boundaries, i.e., Pixel values lying outside the Dimension of the image. Such Values are not displayed in the output image. 

To rotate an image by an angle with a python pillow, you can use the rotate() method on the Image object. The rotate() method is used to rotate the image in a counter-clockwise direction.

Syntax

image.rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)

Parameters

  • angle: It is the angle in degrees counterclockwise.
  • resample: It is an optional input. It can be one of PIL.Image.NEAREST (use the nearest neighbor), PIL.Image.BILINEAR (linear interpolation in a 2×2 environment), or PIL.Image.BICUBIC (cubic spline interpolation in a 4×4 environment). If omitted, or if the image has mode “1” or “P,” it is set PIL.Image.NEAREST. See Filters.
  • expand: It is an optional input. If set to True, the images expand and become large enough to hold the entire rotated image. If set to False, the output image is of the same size as of input image.
  • center: It is an optional input. It set the center of image rotation. By default, it is the center of the image.
  • translate: It is an optional input. It is a post-rotate translation.
  • fillcolor: It is an optional input. It is a color for an area outside the rotated image.

Example to rotate an image in Python with PIL

In this example, we will have to import the Image module from the PIL library of python. Then, we will be reading the input image on which you want to operate the rotation of an image. Then, we will print the original or input image. After that, we will be applying the rotate() function on the input image and see the output. Let us look at the example for understanding the concept in detail.

#import Image from PIL
from PIL import Image

#read the image
input_image = Image.open("E:\Python-Pool-Home.jpg")
#show image 
input_image.show()

#rotate image
angle = 180
output = input_image.rotate(angle)
output.show()

angle1 = 90
output1 = input_image.rotate(angle1)
output1.show()

Output:

Example to rotate an image in Python with PIL
Original input image
Second Example to rotate an image in Python with PIL
Rotated 180 degree image
Third Example to rotate an image in Python with PIL
Rotated 90 degree image

Explanation:

  • Firstly, we will import the Image module from the PIL library of python.
  • Then, we will be taking the input image to operate rotation on the input image.
  • Then, we will print the input image by the Show() function.
  • After that, we will set an angle by which we want to rotate an image.
  • Then, we will apply the rotate() function in which we will pass the angle of rotation of the image.
  • We have rotated the image with two given angles, i.e., 180 degrees and 90 degrees.
  • At last, we will show both the images of rotation by angle.
  • Hence, you can see all three images.

Method 2: Using open-CV to rotate an image in python

Python open-Cv is a module that handles real-time applications related to computer vision. It has a good number of built-in functions to deal with images as input from the user. It works with the image processing library imutils, which deals with images. With the help of The imutils.rotate() function, we can rotate an image by an angle in Python. Even Open-CV Rotates the image in Counter Clockwise direction to the number of degrees specified.

Syntax

imutils.rotate(image, angle=angle)

Example to rotate an image with open-CV

In this example, we will be using the open-CV module to rotate an image. The Open-CV module is used for handling real-time applications. For this, we need to install the open-CV on our laptop or desktop. Then, we have to import imutils. After that, we will read an input image by cv2.imshow(). Then, we will apply the imutils.rotate() function to rotate an image for a particular angle. Then, we will print the images after rotation. Let us look at the example for understanding the concept in detail.

#import cv2 and imutils module
import cv2  
import imutils
  
# read an image as input using OpenCV
input_image = cv2.imread(r"E:\Python-Pool-Home.jpg")
  
output_image = imutils.rotate(input_image, angle=180)

# display the image of 180 degree angle
cv2.imshow("Rotated", output_image)


output1_image = imutils.rotate(input_image, angle=90)
   
# display the image of 90 degree and=gle
cv2.imshow("Rotated", output1_image)
  
# This is used for To Keep On Displaying
cv2.waitKey(0)

Output:

rotate an image with open-CV
output rotate an image with open-CV

Explanation:

  • Firstly, we will import the cv2 and imutils library.
  • Then, we will be reading the image with the help of the cv2 module as input.
  • Then, we will apply the rotate() function in which we will pass the angle of rotation of the image.
  • We have rotated the image with two given angles, i.e., 180 degrees and 90 degrees.
  • At last, we will show both the images of rotation by angle.
  • Hence, you can see all two images.

Method 3: Using numpy rotate an image

In this example, we have used a numpy module for rotating an image. For this, we have to import the numpy library and Image from the PIL module. Then, we will take an input image from the np.array() function. At last, we will apply np.rot90() to rotate an image. Inside the function, if we have passed the second argument, that means the number of times we need to rotate an image. Suppose, if 1 is passed, it will rotate only 90 degrees, and if 2 is passed, it will rotate 180 degrees. Let us look at the example for understanding the concept in detail.

import numpy as np
from PIL import Image

input_image = np.array(Image.open('E:\Python-Pool-Home.jpg'))

Image.fromarray(np.rot90(input_image)).save('E:\sid.jpg')

Image.fromarray(np.rot90(input_image, 2)).save('E:\sid1.jpg')

Output:

numpy rotate an image
output numpy rotate an image

Explanation:

  • Firstly, we will import a numpy module with an alias name as np.
  • Then, we will import Image from the PIL module.
  • After that, we will be taking an input image from the np.array() function.
  • Then, we will be applying the np.rot90() function.
  • Inside the function, if we have passed the second argument, that means the number of times we need to rotate an image. Suppose, if 1 is passed, then it will rotate only 90 degrees, and if 2 is passed, it will rotate 180 degrees.
  • Hence, you can see the rotated image at the given position.

Method 4: Rotate matplotlib image using scipy in python

In this example, we will be using matplotlib and scipy library to rotate an image. Then, we will be applying misc.face() function from scipy library. Then, we will rotate an image and see the output. Let us look at the example for understanding the concept in detail.

from scipy import ndimage, misc
from matplotlib import pyplot as plt
  
panda = misc.face()

panda_rotate = ndimage.rotate(panda, 90,
                              mode = 'mirror')
plt.imshow(panda_rotate)
plt.show()

Output:

Rotate matplotlib image using scipy in python

Explanation:

  • Firstly, we will import ndimage and misc from the scipy library.
  • Then, we will import the pyplot library from the matplotlib module.
  • After that, we will apply the misc.face() function.
  • Then, we will apply ndimage.rotate() function to rotate an image.
  • At last, we will apply imshow() and show() to show the image.

Conclusion

In this tutorial, we have learned about how to rotate an image in python with the help of two methods, i.e., Using open-CV and using Python installed library(PIL). Both the methods are explained in detail with their syntax and the Sample codes as examples. All the examples will help you to understand the method more deeply.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

FAQs

1. How do you rotate a matrix in python?

We can rotate a matric in python with the help of the following code:

class rotatedMatrix(object):
   def rotate(self, mat):
      temp_matrix = []
      column = len(mat)-1
      for column in range(len(mat)):
         temp = []
         for row in range(len(mat)-1,-1,-1):
            temp.append(mat[row][column])
         temp_matrix.append(temp)
      for i in range(len(mat)):
         for j in range(len(mat)):
            mat[i][j] = temp_matrix[i][j]
      return mat

ob1 = rotatedMatrix()
print(ob1.rotate([[1,2,3],[4,5,6],[7,8,9]]))

Output:

rotate a matrix in python

2. How do you check the orientation of an image in Python?

When there is no correction applied, the orientation of a photograph is determined by the rotation of the camera at which moment the picture was taken. Even though there are many angles possible, rotations by multiple of 90° are the most common. They are also straightforward to correct once detected. We can check the orientation of an image in python by LBP-based features and logistic regression.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments