In this Python OpenCV lesson we are going to learn about Python OpenCV Image Rotation, we can use cv2.rotate() function for rotating an image in OpenCV and there are three constant types of rotation that you can pass as parameter in the function, these are the constants.
- cv2.ROTATE_90_CLOCKWISE
- cv2.ROTATE_90_COUNTERCLOCKWISE
- cv2.ROTATE_180
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
#we can rotate an image in opencv using rotate() function #there three constants that you can use a parametr #cv2.ROTATE_90_CLOCKWISE #cv2.ROTATE_90_COUNTERCLOCKWISE #cv2.ROTATE_180 import cv2 import matplotlib.pyplot as plt img = cv2.imread('lena.tif') #Our three rotation img_rotate_90_clockwise = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) img_rotate_90_counterclockwise = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) img_rotate_180 = cv2.rotate(img, cv2.ROTATE_180) #converting images from bgr to rgb original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_clockwise = cv2.cvtColor(img_rotate_90_clockwise, cv2.COLOR_BGR2RGB) img_counterclockwise = cv2.cvtColor(img_rotate_90_counterclockwise, cv2.COLOR_BGR2RGB) img_180 = cv2.cvtColor(img_rotate_180, cv2.COLOR_BGR2RGB) titles = ["Original Image", "Image 90 Clockwise", "Image 90 CounterClockWise", "Image Rotate 180" ] images = [original_image, img_clockwise, img_counterclockwise,img_180 ] for i in range(4): plt.subplot(2,2, i+1) plt.imshow(images[i]) plt.title(titles[i]) plt.xticks([]), plt.yticks([]) plt.show() cv2.waitKey(0) cv2.destroyAllWindows() |
These are our three rotation types.
1 2 3 4 5 |
img_rotate_90_clockwise = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) img_rotate_90_counterclockwise = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) img_rotate_180 = cv2.rotate(img, cv2.ROTATE_180) |
We want to show our all image types in matplotlib, so by this reason we need to convert our color space, as we have already said that opencv uses GBR color space, but matplotlib uses RGB color, we need to convert BGR to RGB color, for more information about color spaces you can check the color space lesson, we can use cv2.cvtColor() for converting the color spaces.
1 2 3 4 5 6 |
original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_clockwise = cv2.cvtColor(img_rotate_90_clockwise, cv2.COLOR_BGR2RGB) img_counterclockwise = cv2.cvtColor(img_rotate_90_counterclockwise, cv2.COLOR_BGR2RGB) img_180 = cv2.cvtColor(img_rotate_180, cv2.COLOR_BGR2RGB) |
Because we are showing four types of images for that we need to use subplot from matplotlib.
1 2 3 4 5 |
for i in range(4): plt.subplot(2,2, i+1) plt.imshow(images[i]) plt.title(titles[i]) plt.xticks([]), plt.yticks([]) |
Run the complete code and this is the result.