Rotation of image

From Lofaro Lab Wiki
Jump to: navigation, search

We were doing translation where we were shifting our image according to the pixel we want. Rotation of image will rotate the image to some angle let’s say x. so x will represent by how many degrees we want to rotate our image. Let’s explain the concept of rotation using some code.


import cv2
import numpy as np
image = cv2.imread('hubo.jpg',0)
cv2.imshow("Original", image)
# get the dimensions of the image and calculate the center of the image
(h, w) = image.shape[:2]
center = (w / 2, h / 2)
# Rotate the image by 45 degrees
M = cv2.getRotationMatrix2D(center, 45, 1.0)
rotated = cv2.warpAffine(image, M, (w, h))
cv2.imshow("Rotated by 45 Degrees", rotated)
# Rotate our image by -90 degrees
M = cv2.getRotationMatrix2D(center, -90, 1.0)
rotated = cv2.warpAffine(image, M, (w, h))
cv2.imshow("Rotated by -90 Degrees", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()

After importing our packages we loaded our image and showed it so that we can compare it with the next outputs. When we want to rotate an image, we need to specify the center of the image from which we will rotate around. The center is a position of pixel in the image. We can make generally make the center of rotation which is the middle point of the image. We can find out the dimension of the image using the command (h, w) = image.shape[:2], where number of pixels of height would be stored in h, and number of pixels in width will be stored in w. After that, we find out the center dividing the number of pixels by 2.

The way we defined a translation matrix, we need to define a rotation matrix which will have the information about the rotation. We can use cv2.getRotationMatrix2D function to construct the matrix. This method takes 3 arguments first one is the center around which we want to rotate our image. Second argument is the number of degrees we want to rotate our image. The third one is the resizing effect of image. We put that 1 means, we want the image should be in same size as original after rotation. If we give there 2, it will double the size of the image. Giving .5 will halve the size of the image.

Once we get our rotation matrix, we can apply cv2.warpaffine method to get our rotated image. The first is the image we want to rotate, second is the rotation matrix and third is the size of the image. Here we rotated our image in 45 degree. The thing that is important to remember is positive value of degree will rotate the image counter clockwise where negative value will rotate it clock wise. If you examine the second rotation of -90 degree you will see the image is rotated clock wise by 90 degree. See the images below for better understating of the concept.


Rotation.jpg