Rotate image with OpenCV


Python OpenCV - Rotate Image

To rotate an image by 90 degrees, 180 degrees, or 270 degrees, with OpenCV in Python, you can use cv2.rotate() function.

https://youtu.be/-W3bEG2Dmso?si=eyhosul5PFjpFI_F

In this tutorial, you will learn how to use cv2.rotate() function to rotate a given image by a specific angle.

Syntax of cv2.rotate()

The syntax of cv2.rotate() function is

rotate(src, rotateCode)

where

ParameterDescription
src2D array. The source image that is read into a 2D array.
rotateCodecv2.ROTATE_90_CLOCKWISE to rotate the image by 90 degrees clockwise.
cv2.ROTATE_180 to rotate the image by 180 degrees.
cv2.ROTATE_90_COUNTERCLOCKWISE to rotate the image by 270 degrees clockwise, or 90 degrees counter clockwise.

Steps to rotate an image

  1. Read an image into an array using cv2.imread() function.
  2. Rotate the image (2D array) by 90 degrees, 180 degrees, or 270 degrees, using cv2.rotate() function with the respective rotate code. The function returns the rotated image (2D array).
  3. Save the rotated image using cv2.imwrite() function.

Examples

In the following examples, we take an image, an rotate it to 90, 180, or 270 degrees.

The input image test_image_house.jpg we are taking is shown below.

1. Rotate image by 90 degrees clockwise

In the following program, we take an image test_image_house.jpg, rotate this image by 90 degrees, then save the rotated image to rotated_image.jpg.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Rotate the image by 90 degrees clockwise
rotated_img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)

# Save rotated image
cv2.imwrite('rotated_image.jpg', rotated_img)

rotated_image.jpg

Python OpenCV - Rotate image by 90 degrees clockwise

2. Rotate image by 180 degrees

In the following program, we rotate the image test_image_house.jpg by 180 degrees. Since, it is 180 degrees, both clockwise or counterclockwise would be same.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Rotate the image by 180 degrees
rotated_img = cv2.rotate(img, cv2.ROTATE_180)

# Save rotated image
cv2.imwrite('rotated_image.jpg', rotated_img)

rotated_image.jpg

Python OpenCV - Rotate image by 180 degrees

3. Rotate image by 270 degrees clockwise

In the following program, we rotate the image test_image_house.jpg by 270 degrees clockwise, or 90 degrees counterclockwise.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Rotate the image by 90 degrees counterclockwise
rotated_img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)

# Save rotated image
cv2.imwrite('rotated_image.jpg', rotated_img)

rotated_image.jpg

Python OpenCV - Rotate image by 270 degrees

Summary

In this Python OpenCV Tutorial, we have seen how to rotate an image by 90 degrees, 180 degrees, or 270 degrees using cv2.rotate() function.