How to Rotate an Image with OpenCV and Python

In this article we want to learn How to Rotate an Image with OpenCV and Python, OpenCV is an open source computer vision and machine learning library that provides different tools and techniques for image processing and manipulation. one of the common image processing tasks is to rotate an image. In this article we are going to explore how to rotate an image using OpenCV and Python.

 

 

First of all we need to install Python OpenCV

 

 

Now we need to import our required libraries from OpenCV

 

 

After that we need to load the image that we want to rotate. we can use cv2.imread() function to read an image from the disk. this function takes the file path as the input and returns  NumPy array that represents the image.

 

 

For rotating an image we need to define rotation matrix. rotation matrix is 2×3 matrix that defines transformation that needs to be applied to image. matrix takes three arguments: angle of rotation, center of rotation and scale of the image.

In the above code first of all we have get height and width of the image using shape attribute of NumPy array. after that we calculate center of the image using height and width. we set angle of rotation to 45 degrees and scale of the image to 1.0, and finally we use the cv2.getRotationMatrix2D() function to generate the rotation matrix.

 

 

Once we have rotation matrix, we can apply it to the image using cv2.warpAffine() function. this function takes input image, rotation matrix, and size of the output image as the input arguments.

In the above code we have used cv2.warpAffine() function to apply the rotation matrix to the input image. after that we pass input image, rotation matrix, and size of the output image as the input arguments.

 

 

Finally we can display rotated image using cv2.imshow() function. we pass title of the window and image array as the input arguments.

In the above code we have used cv2.imshow() function to display rotated image in new window. after that we have used wait for key press using cv2.waitKey() function. and finally we have used cv2.destroyAllWindows() function to close all the windows.

 

 

This is the complete code for this article

 

 

 

Run the complete code and this will be the result

How to Rotate an Image with OpenCV and Python
How to Rotate an Image with OpenCV and Python

 

 

 

 

In this article we have leaned how to rotate an image using OpenCV and Python. also we have learned how to load an image, define rotation matrix, apply rotation matrix to the image and display rotated image. OpenCV provides powerful set of tools for image processing and manipulation, and rotating an image is just one of the many tasks that can be performed using OpenCV.

 

 

 

Learn More on Python

Leave a Comment