- OpenCV with Python By Example
- Prateek Joshi
- 269字
- 2021-07-16 19:57:02
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:

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:

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:

- Python數據可視化:基于Bokeh的可視化繪圖
- Django開發從入門到實踐
- 少年輕松趣編程:用Scratch創作自己的小游戲
- PyTorch自然語言處理入門與實戰
- Servlet/JSP深入詳解
- GitLab Repository Management
- Windows Presentation Foundation Development Cookbook
- 用Python實現深度學習框架
- Mastering Predictive Analytics with Python
- Mastering Google App Engine
- 移動界面(Web/App)Photoshop UI設計十全大補
- 從零開始學C語言
- Python High Performance Programming
- 微信小程序開發與實戰(微課版)
- Managing Microsoft Hybrid Clouds