Template
import cv2 img = cv2.imread("./origin.jpg") h, w = img.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, 45, 0.5) rotated = cv2.warpAffine(img, M, (w, h)) cv2.imwrite("./rotated.jpg", rotated)
Demo
原圖像:
rotated_45.jpg:
rotated_-90.jpg:
Code
實現代碼:
# encoding:utf-8 import cv2 img = cv2.imread("./girl.jpg") h, w = img.shape[:2] center = (w // 2, h // 2) # 旋轉中心座標,逆時針旋轉:45°,縮放因子:0.5 M_1 = cv2.getRotationMatrix2D(center, 45, 0.5) rotated_1 = cv2.warpAffine(img, M_1, (w, h)) cv2.imwrite("./rotated_45.jpg", rotated_1) # 旋轉中心座標,逆時針旋轉:-90°,縮放因子:1 M_2 = cv2.getRotationMatrix2D(center, -90, 1) rotated_2 = cv2.warpAffine(img, M_2, (w, h)) cv2.imwrite("./rotated_-90.jpg", rotated_2)
Cons
但是不管怎麼旋轉,該圖像的shape始終和原圖像一致。這在某種程度上會造成不好的影響。
如果想要無損地旋轉圖像,請參看我的另一篇blog:圖像處理: 無損地旋轉圖像。