OpenCV provides several functions to rotate an image. The most common and simplest is the cv2.warpAffine() function. This function takes the matrix as an input, along with the size of the image, and performs the rotation. It can also be used to scale, translate, or perform any other affine transformation. Other functions for rotating images include cv2.rotate() and cv2.getRotationMatrix2D().
what is cv2.getRotationMatrix2D() function.
The cv2.getRotationMatrix2D() function is a built-in OpenCV function that returns a 2x3 matrix that can be used to rotate an image around a specified point. The function takes some parameters such as the center of rotation, the rotation angle, and the scale to apply to the image. We can use cv2.warpAffine() function to wrap up the output of cv2.getRotationMatrix2D() function.
what is cv2.warpAffine() function.
cv2.warpAffine is a function in the OpenCV. It is used for image warping. It takes a 2x3 transformation matrix as an argument and applies that matrix to the input image to warp its shape according to the specified transformation. This function is useful for tasks such as image rotation, scaling, translation, shearing, and more.
Let's understand the concept with some practical work.
import cv2 img = cv2.imread('demo.png') (rows,column)=img.shape[:2] rotation_point = (rows/2,column/2) degree = 90 matrix = cv2.getRotationMatrix2D(rotation_point,degree,1) new = cv2.warpAffine(img, matrix,(column,rows)) cv2.imshow('Rotated Image', new) cv2.imwrite('rotated.jpg',new) cv2.waitKey(0) cv2.destroyAllWindows()
Here, first, we imported cv2. then we used cv2.imread to read the image of the given path. Then we declared two variables to store the shape of the image (number of rows and columns) in two variables, rows and column. After this, we defined the point of rotation as the center of the image. Then, we created a rotation matrix that is used to rotate the image. At last, we used the warpAffine function of OpenCV to rotate the image according to the rotation matrix and displayed the image.
Using cv2.rotate() function
import cv2 img = cv2.imread('demo.png') image = cv2.rotate(img, cv2.ROTATE_180) cv2.imshow('Rotated Image', image) cv2.waitKey(0) cv2.destroyAllWindows()
Here, first, we imported cv2. then we used cv2.imread to read the image of the given path. Then we used cv2.rotate() function with cv2.ROTATE_180 argument to rotate the input image 180 degrees. At last, we used cv2.imshow() to display the final image.