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

Jingwei Li

Graduate Research assistance at Stony Brook University
linkedin profile url

ProjectPro is an awesome platform that helps me learn much hands-on industrial experience with a step-by-step walkthrough of projects. There are two primary paths to learn: Data Science and Big Data.... Read More

Relevant Projects

Loan Eligibility Prediction in Python using H2O.ai
In this loan prediction project you will build predictive models in Python using H2O.ai to predict if an applicant is able to repay the loan or not.

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.

Build ARCH and GARCH Models in Time Series using Python
In this Project we will build an ARCH and a GARCH model using Python

Build CNN for Image Colorization using Deep Transfer Learning
Image Processing Project -Train a model for colorization to make grayscale images colorful using convolutional autoencoders.

Multilabel Classification Project for Predicting Shipment Modes
Multilabel Classification Project to build a machine learning model that predicts the appropriate mode of transport for each shipment, using a transport dataset with 2000 unique products. The project explores and compares four different approaches to multilabel classification, including naive independent models, classifier chains, natively multilabel models, and multilabel to multiclass approaches.

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.

Learn to Build Generative Models Using PyTorch Autoencoders
In this deep learning project, you will learn how to build a Generative Model using Autoencoders in PyTorch

Build a Credit Default Risk Prediction Model with LightGBM
In this Machine Learning Project, you will build a classification model for default prediction with LightGBM.

MLOps Project to Build Search Relevancy Algorithm with SBERT
In this MLOps SBERT project you will learn to build and deploy an accurate and scalable search algorithm on AWS using SBERT and ANNOY to enhance search relevancy in news articles.

Model Deployment on GCP using Streamlit for Resume Parsing
Perform model deployment on GCP for resume parsing model using Streamlit App.