How to Perform Image Rotation in OpenCV using Python
One of the most common image processing tasks is image rotation. With OpenCV and Python, performing image rotation is easy and straightforward. In this tutorial, we will show you how to rotate an image using OpenCV in Python.
Importing Libraries
The first step is to import the necessary libraries in python. To do this, we commonly use the following lines of code:
import cv2
import numpy as np
Here, we import two important libraries. cv2
, which is short for OpenCV, is the library responsible for image processing tasks. numpy
, on the other hand, is a numerical computing library that is commonly used in scientific and mathematical computing.
Loading the Image
The next step is to load the image. You can load the image using the imread
function provided by OpenCV. Here’s an example code to load and display an image:
img = cv2.imread('image.jpg')
cv2.imshow('Original Image', img)
Here, we use the imread
function to load an image file named image.jpg
. We then display the loaded image using the imshow
function.
Rotating the Image
To perform image rotation in OpenCV, we can use the getRotationMatrix2D
and warpAffine
functions. The getRotationMatrix2D
function returns the rotation matrix that can be used to rotate an image. The warpAffine
function then applies this rotation to the image.
Here’s an example code to rotate an image by 90 degrees clockwise:
rows, cols = img.shape[:2]
# getRotationMatrix2D returns a rotation matrix
# The third parameter is the degree of rotation
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), -90, 1)
# Apply the rotation
rotated_img = cv2.warpAffine(img, M, (cols, rows))
cv2.imshow('Rotated Image', rotated_img)
Here, we first get the number of rows and columns of the loaded image using the shape
function provided by OpenCV. We then use the getRotationMatrix2D
function to generate a rotation matrix. The first parameter is the center of the rotation, which is computed as the center of the image. The second parameter is the angle of rotation, which is set to -90 degrees to rotate the image 90 degrees clockwise. The third parameter is the scaling factor, which is set to 1.
Finally, we apply the rotation to the loaded image using the warpAffine
function. The first parameter is the input image; the second parameter is the rotation matrix; and the third parameter is the output image size. We then display the rotated image using the imshow
function.
Conclusion
In this tutorial, we have shown how to rotate an image using OpenCV in Python. We have used the getRotationMatrix2D
and warpAffine
functions provided by OpenCV to perform the rotation. By changing the degree of rotation, you can create an image that is rotated by any arbitrary angle. We hope this tutorial was helpful, and we encourage you to experiment with different rotation angles to see how they affect your images.