How to rotate an image using Python?
Image rotation in Python rotates an image around its centre by a specified angle using forward or inverse methods. When the angle isn’t a multiple of 90 degrees, parts of the image may move outside the visible boundaries and get clipped. To avoid losing important content during rotation you need proper handling. Let’s explore different methods to perform this efficiently.
1. Using cv2.getRotationMatrix2D()
Generates a transformation matrix to rotate an image around a specific centre point by any angle and scale. It provides precise control over rotation but requires manual matrix computation and application.
import cv2
import numpy as np
img = cv2.imread("./gfgrotate.jpg")
h, w = img.shape[:2] # height, width
ctr = (w // 2, h // 2)
ang = 45
scl = 1.0
mat = cv2.getRotationMatrix2D(ctr, ang, scl)
rot = cv2.warpAffine(img, mat, (w, h))
cv2.imshow("Rotated Image", rot)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output

This code sets the rotation angle to 45 degrees with a scale of 1.0 no scaling. Then it creates a rotation matrix using cv2.getRotationMatrix2D() and applies it to the image with cv2.warpAffine() hence giving a rotated image of the same size.
2. Using imutils.rotate()
A convenient wrapper around OpenCV’s rotation function that rotates an image by a given angle. It’s easy to use but keeps the original image size which can crop rotated corners.
import cv2
import imutils
img = cv2.imread("./gfgrotate.jpg")
rot_45 = imutils.rotate(img, angle=45)
rot_90 = imutils.rotate(img, angle=90)
cv2.imshow("Rotated 45 Degrees", rot_45)
cv2.imshow("Rotated 90 Degrees", rot_90)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output


This code reads an image and uses imutils.rotate() to rotate it by 45 and 90 degrees. This function simplifies rotation by handling the transformation internally. The rotated images are then displayed in separate windows until a key is pressed.
3. Using Image.rotate()
Rotates images by any angle with a simple API. Supports an expand=True option to resize the canvas and prevent cropping, making it ideal for flexible rotations.
from PIL import Image
img = Image.open("./gfgrotate.jpg")
rot_180 = img.rotate(180)
rot_60 = img.rotate(60)
rot_180.show()
rot_60.show()
Output


This code opens an image using Pillow and rotates it by 180 and 60 degrees using the rotate() method. It then displays both rotated images in separate windows.
4. Using Image.transpose()
Efficiently rotates images by fixed multiples of 90 degrees (90°, 180°, 270°). It’s very fast, avoids cropping but does not support arbitrary angles.
from PIL import Image
img = Image.open("./gfgrotate.jpg")
rot_90 = img.transpose(Image.ROTATE_270)
rot_180 = img.transpose(Image.ROTATE_180)
rot_90.show()
rot_180.show()
Output


This code opens an image with Pillow and rotates it by fixed angles using transpose() 90 degrees clockwise using ROTATE_270 and 180 degrees. It then displays both rotated images.