官术网_书友最值得收藏!

Image rotation

In this section, we will see how to rotate a given image by a certain angle. We can do it using the following piece of code:

import cv2
import numpy as np

img = cv2.imread('images/input.jpg')
num_rows, num_cols = img.shape[:2]

rotation_matrix = cv2.getRotationMatrix2D((num_cols/2, num_rows/2), 30, 1)
img_rotation = cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows))
cv2.imshow('Rotation', img_rotation)
cv2.waitKey()

If you run the preceding code, you will see an image like this:

Image rotation

What just happened?

In order to understand this, let's see how we handle rotation mathematically. Rotation is also a form of transformation, and we can achieve it by using the following transformation matrix:

What just happened?

Here, θ is the angle of rotation in the counterclockwise direction. OpenCV provides closer control over the creation of this matrix through the function, getRotationMatrix2D. We can specify the point around which the image would be rotated, the angle of rotation in degrees, and a scaling factor for the image. Once we have the transformation matrix, we can use the warpAffine function to apply this matrix to any image.

As we can see from the previous figure, the image content goes out of boundary and gets cropped. In order to prevent this, we need to provide enough space in the output image. Let's go ahead and do that using the translation functionality we discussed earlier:

import cv2
import numpy as np

img = cv2.imread('images/input.jpg')
num_rows, num_cols = img.shape[:2]

translation_matrix = np.float32([ [1,0,int(0.5*num_cols)], [0,1,int(0.5*num_rows)] ])
2*num_cols, 2*num_rows))
rotation_matrix = cv2.getRotationMatrix2D((num_cols, num_rows), 30, img_translation = cv2.warpAffine(img, translation_matrix, (1)
img_rotation = cv2.warpAffine(img_translation, rotation_matrix, (2*num_cols, 2*num_rows)) 

cv2.imshow('Rotation', img_rotation)
cv2.waitKey()

If we run the preceding code, we will see something like this:

What just happened?
主站蜘蛛池模板: 建平县| 大厂| 綦江县| 资阳市| 崇文区| 普宁市| 建昌县| 保靖县| 江城| 济阳县| 米脂县| 夏津县| 龙州县| 仙游县| 城口县| 巧家县| 新野县| 永平县| 西乡县| 湛江市| 广州市| 望城县| 莱州市| 太仆寺旗| 望江县| 丰台区| 田林县| 鱼台县| 沧源| 湖北省| 云和县| 凌源市| 山东| 枣庄市| 静乐县| 萨嘎县| 龙口市| 榆社县| 紫阳县| 五大连池市| 新平|