How to rotate an image using OpenCV

This recipe helps you rotate an image using OpenCV

Recipe Objective: How to rotate an image using OpenCV?

In this recipe, let us understand how to rotate an image using OpenCV

Deep Learning Project for Text Detection in Images using Python

Step 1: Import the libraries and read the image

Let us first import the necessary libraries and read the image. Let us also store the dimension of the image using the .shape() function. The image that we are using here is the one shown below.

input image

import cv2
from matplotlib import pyplot as plt
image = cv2.imread('project.jpg')
rows,cols,channels= image.shape

Step 2: Image Rotation

We can rotate a given image using OpenCV in two ways. One is using the cv.rotate() function and other is using cv2.getRotationMatrix2D() function. Let us see how each function works in detail.

The cv2.rotate() function takes in two parameters. They are

  • src: The image which is to be rotated
  • rotateCode: The type of rotation

There are three rotateCodes available in OpenCV. They are

  • cv2.ROTATE_90_CLOCKWISE: Rotates the image in a clockwise direction by 90 degrees
  • cv2.ROTATE_90_COUNTERCLOCKWISE: Rotates the image in a counter-clockwise direction by 90 degrees
  • cv2.ROTATE_180: Rotates the image in a clockwise direction by 180 degrees

rotate_90 = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
rotate_90_counter = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
rotate_180 = cv2.rotate(image, cv2.ROTATE_180)

One disadvantage in this approach is that the image can be rotated only by multiples of 90 degrees. What if we want to rotate an image by, say, 70 degrees? That is when cv2.getRotationMatrix2D() comes into play. This function takes the following input parameters

  • center: The central point of rotation in the given image
  • angle: The angle of rotation. (Positive value denotes clockwise rotation while negative values denote anti-clockwise rotation)
  • scale: Isotropic scaling factor

The cv2.getRotationMatrix2D() returns a transformation matrix which can be used on any image using the cv2.warpAffine() function.

In this example, let us rotate the input image by 30 degrees in a counter-clockwise direction.

M = cv2.getRotationMatrix2D((cols/2,rows/2),-30,1)
rotate_30 = cv2.warpAffine(image,M,(cols,rows))

Step 3: Displaying the output

Let us plot the images using matplotlib subplots for a better comparison of results.

plt.figure(figsize=(13,6))
titles = ['Rotate 90',"Rotate 90 degree counter clock wise","Rotate 180","Rotate 30 counter clockwise"]
images = [rotate_90, rotate_90_counter, rotate_180, rotate_30]
plt.figure(figsize=(13,5))
for i in range(4):
    plt.subplot(2,2,i+1)
    plt.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))
    plt.title(titles[i])
plt.tight_layout()
plt.show()

Output:

rotate.png

Download Materials

What Users are saying..

profile image

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

MLOps Project on GCP using Kubeflow for Model Deployment
MLOps using Kubeflow on GCP - Build and deploy a deep learning model on Google Cloud Platform using Kubeflow pipelines in Python

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

Build an AI Chatbot from Scratch using Keras Sequential Model
In this NLP Project, you will learn how to build an AI Chatbot from Scratch using Keras Sequential Model.

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.

Natural language processing Chatbot application using NLTK for text classification
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.

Deploy Transformer BART Model for Text summarization on GCP
Learn to Deploy a Machine Learning Model for the Abstractive Text Summarization on Google Cloud Platform (GCP)

Recommender System Machine Learning Project for Beginners-4
Collaborative Filtering Recommender System Project - Comparison of different model based and memory based methods to build recommendation system using collaborative filtering.

NLP Project for Beginners on Text Processing and Classification
This Project Explains the Basic Text Preprocessing and How to Build a Classification Model in Python

Create Your First Chatbot with RASA NLU Model and Python
Learn the basic aspects of chatbot development and open source conversational AI RASA to create a simple AI powered chatbot on your own.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.