How to Rotate an Image with OpenCV
Step by step tutorial for rotating an image in OpenCV
Updated March 19, 2023
Learn more about OpenCV and Computer Vision from this YouTube Channel!
As a computer vision enthusiast, you might wonder why image rotation is even important in the first place. After all, why would you need to rotate an image when it’s already in front of you? Well, as it turns out, image rotation is an essential element of many computer vision projects. It allows you to manipulate your images in ways that can make algorithmic detection much more efficient. Not to mention, rotating an image can help align it properly for alignment with other images or even perform image stitching.
That’s why I’m here today to show you precisely how to rotate an image with OpenCV, and trust me, it’s not as daunting as it sounds. In this tutorial, we’ll cover the theory behind image rotation, how to implement it in OpenCV, and explore multiple code examples to solidify your understanding.
Theory behind Image Rotation
Before we dive into the code, let’s talk about image rotation theory. It’s essential to know what happens under the hood of your code, so you know exactly what’s going on with your images. So let’s jump right in.
At the fundamental level, any image is just a collection of pixels, each with their own value. When you rotate an image, those pixels need to be moved to a new location based on the rotation angle. For this, we use something called an affine transformation matrix.
Simply put, an affine transformation matrix is a tool that can transform an input image by changing its location, scale, or orientation, amongst other things. When we use an affine transformation matrix, we can define how the pixels of the original image will move to their new location following a rotation.
The rotation angle is an indispensable element of this transformation. It defines precisely how the input image will rotate, based on the angle value you provide to the code. In general, rotation angles in OpenCV are defined in degrees, with positive values representing a clockwise rotation and negative values representing a counterclockwise rotation.
Once you have defined the rotation angle in degrees and created an affine transformation matrix, you’re ready to implement your first image rotation in your code.
How to Rotate an Image with OpenCV
Now that we’ve covered the theory behind image rotation let’s dive into the code. First, you’ll want to import the necessary Python libraries, including NumPy and the Cv2 (OpenCV) library.
import cv2 import numpy as np
Once you have your libraries imported, you can use the “cv2.getRotationMatrix2D()” function to create your affine transformation matrix. This function takes three inputs: the rotation angle in degrees, the center point of rotation, and the scaling factor.
The scaling factor is an optional parameter, but I prefer to include it because it helps preserve the image’s size better. For instance, if the scaling factor is set to 1.0, the resulting image will have the same pixel size as the original image.
Here’s an example of how to create your transformation matrix in OpenCV:
angle = 30 scale_factor = 1.0 # Define a center point for the rotation (h, w) = image.shape[:2] center = (w // 2, h // 2) # Create the affine transformation matrix for image rotation M = cv2.getRotationMatrix2D(center, angle, scale_factor)
Here, we’re defining the rotation angle to be 30 degrees and setting our scaling factor to 1.0. We also retrieve the center point of the image, which is equivalent to the image’s width and height divided by two.
Now that we have created our transformation matrix, we’re ready to implement image rotation. To do this, we use another OpenCV function called
warpAffine(). This function takes two inputs: the original image and the affine transformation matrix. Here’s what the code looks like:
# Apply the affine transformation matrix to rotate the image rotated_image = cv2.warpAffine(image, M, (w, h))
Again, we use the “cv2.warpAffine()” function to apply the affine transformation matrix to the original image. The resulting rotated_image variable will contain a copy of the image that has been rotated based on the affine transformation matrix we created earlier. The last two input arguments, (w, h), indicate that the function should return an output image that has the same width and height as the input image.
That’s it! With these simple lines of code, you can rotate your image by any degree angle.
Now that we’ve gotten the basics down, let’s take a look at some example code that shows just how easy it is to rotate an image in OpenCV.
First, let’s start with a simple example of rotating an image by 45 degrees:
# Load the original image image = cv2.imread('example_image.jpg') # Define the rotation angle and the scaling factor angle = 45 scale_factor = 1.0 # Get the image dimensions (h, w) = image.shape[:2] # Get the center point for rotation center = (w // 2, h // 2) # Create an affine transformation matrix for rotation M = cv2.getRotationMatrix2D(center, angle, scale_factor) # Apply the affine transformation matrix to rotate the image rotated_image = cv2.warpAffine(image, M, (w, h)) # Display the original and rotated images cv2.imshow('Original Image', image) cv2.imshow('Rotated Image', rotated_image) cv2.waitKey(0)
In this example code we load an image file (‘example_image.jpg’) and assign it to the ‘image’ variable. Then we define our rotation angle as 45 degrees and our scale factor as 1.0.
After getting the dimensions and center point of the image, we use the cv2.getRotationMatrix2D() function to create our transformation matrix. Finally, we apply the transformation matrix to the original image to get the rotated_image variable. At the end of the code, we display the original and rotated images using cv2.imshow() function and wait for user input with cv2.waitkey(0).
Here’s one more example where we’ll rotate the image by a different angle and then save the rotated image to disk:
# Load the original image image = cv2.imread('example_image.jpg') # Define the rotation angle and the scaling factor angle = -90 scale_factor = 1.0 # Get the image dimensions (h, w) = image.shape[:2] # Get the center point for rotation center = (w // 2, h // 2) # Create an affine transformation matrix for rotation M = cv2.getRotationMatrix2D(center, angle, scale_factor) # Apply the affine transformation matrix to rotate the image rotated_image = cv2.warpAffine(image, M, (w, h)) # Save the rotated image to disk cv2.imwrite('rotated_image.jpg', rotated_image) # Display the original and rotated images cv2.imshow('Original Image', image) cv2.imshow('Rotated Image', rotated_image) cv2.waitKey(0)
In this example, we’re loading the same image file as before (‘example_image.jpg’). Then we’re changing the rotation angle to -90 degrees and using the cv2.imwrite() function to save the resulting rotated image to the disk.
Overall, this is probably one of the most straightforward image rotation that you can use in your projects using OpenCV.
In summary, image rotation is an essential part of many computer vision projects, and it’s no surprise OpenCV provides a few ways to implement it easily. With affine transformation matrices and OpenCV functions, you can rotate any image by any degree with just a few lines of code.
I hope this tutorial helps you understand image rotation better and encourages you to experiment with image rotation techniques in OpenCV. Just remember, with great power comes great responsibility! It’s up to you to be creative and make your images do extraordinary things.